Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,84 +6,128 @@ from indic_transliteration.detect import detect as detect_script
|
|
| 6 |
from indic_transliteration.sanscript import transliterate
|
| 7 |
import langdetect
|
| 8 |
import re
|
| 9 |
-
import requests
|
| 10 |
-
import json
|
| 11 |
-
import base64
|
| 12 |
-
from PIL import Image
|
| 13 |
-
import io
|
| 14 |
-
import time
|
| 15 |
|
| 16 |
# Initialize clients
|
| 17 |
text_client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 18 |
-
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
"2560 x 1440": "2560 x 1440",
|
| 24 |
-
"Photo": "Photo",
|
| 25 |
-
"Cinematic": "Cinematic",
|
| 26 |
-
"Anime": "Anime",
|
| 27 |
-
"3D Model": "3D Model",
|
| 28 |
-
"No style": "(No style)"
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
def generate_image_space(prompt: str, style: str) -> Image.Image:
|
| 32 |
-
"""Generate an image using the DALLE-4K Space with specified style."""
|
| 33 |
try:
|
| 34 |
-
#
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
if style in ["3840 x 2160", "2560 x 1440"]:
|
| 42 |
-
# For resolution styles, add the resolution to the prompt
|
| 43 |
-
prompt = f"{prompt}, {style} resolution"
|
| 44 |
-
else:
|
| 45 |
-
# For other styles, append the style to the prompt
|
| 46 |
-
prompt = f"{prompt}, {style.lower()} style"
|
| 47 |
-
|
| 48 |
-
# Send the generation request
|
| 49 |
-
response = requests.post(f"{SPACE_URL}/run/predict", json={
|
| 50 |
-
"data": [
|
| 51 |
-
prompt, # Prompt with style
|
| 52 |
-
"", # Negative prompt
|
| 53 |
-
7.5, # Guidance scale
|
| 54 |
-
30, # Steps
|
| 55 |
-
"DPM++ SDE Karras", # Scheduler
|
| 56 |
-
False, # High resolution
|
| 57 |
-
False, # Image to image
|
| 58 |
-
None, # Image upload
|
| 59 |
-
1 # Batch size
|
| 60 |
-
],
|
| 61 |
-
"session_hash": session_hash
|
| 62 |
-
})
|
| 63 |
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
except Exception as e:
|
| 84 |
print(f"Image generation error: {e}")
|
| 85 |
return None
|
| 86 |
-
|
| 87 |
def romanized_to_bengali(text: str) -> str:
|
| 88 |
"""Convert romanized Bengali text to Bengali script."""
|
| 89 |
bengali_mappings = {
|
|
@@ -119,7 +163,6 @@ def respond(
|
|
| 119 |
max_tokens,
|
| 120 |
temperature,
|
| 121 |
top_p,
|
| 122 |
-
image_style: str, # New parameter for image style
|
| 123 |
):
|
| 124 |
# First check for custom responses
|
| 125 |
custom_response = check_custom_responses(message)
|
|
@@ -130,10 +173,11 @@ def respond(
|
|
| 130 |
# Check if this is an image generation request
|
| 131 |
if is_image_request(message):
|
| 132 |
try:
|
| 133 |
-
image =
|
| 134 |
if image:
|
| 135 |
-
|
| 136 |
-
|
|
|
|
| 137 |
return
|
| 138 |
else:
|
| 139 |
yield "Sorry, I couldn't generate the image. Please try again."
|
|
@@ -142,11 +186,14 @@ def respond(
|
|
| 142 |
yield f"An error occurred while generating the image: {str(e)}"
|
| 143 |
return
|
| 144 |
|
| 145 |
-
#
|
| 146 |
translated_msg, original_lang, was_transliterated = translate_text(message)
|
|
|
|
|
|
|
| 147 |
messages = [{"role": "system", "content": system_message}]
|
| 148 |
for val in history:
|
| 149 |
if val[0]:
|
|
|
|
| 150 |
if len(val[0].split()) > 2:
|
| 151 |
trans_user_msg, _, _ = translate_text(val[0])
|
| 152 |
messages.append({"role": "user", "content": trans_user_msg})
|
|
@@ -157,6 +204,7 @@ def respond(
|
|
| 157 |
|
| 158 |
messages.append({"role": "user", "content": translated_msg})
|
| 159 |
|
|
|
|
| 160 |
response = ""
|
| 161 |
for message in text_client.chat_completion(
|
| 162 |
messages,
|
|
@@ -168,6 +216,7 @@ def respond(
|
|
| 168 |
token = message.choices[0].delta.content
|
| 169 |
response += token
|
| 170 |
|
|
|
|
| 171 |
if original_lang != 'en' and len(message.split()) > 2:
|
| 172 |
try:
|
| 173 |
translator = GoogleTranslator(source='en', target=original_lang)
|
|
@@ -178,7 +227,7 @@ def respond(
|
|
| 178 |
else:
|
| 179 |
yield response
|
| 180 |
|
| 181 |
-
# Updated Gradio interface
|
| 182 |
demo = gr.ChatInterface(
|
| 183 |
respond,
|
| 184 |
additional_inputs=[
|
|
@@ -189,7 +238,7 @@ demo = gr.ChatInterface(
|
|
| 189 |
gr.Slider(
|
| 190 |
minimum=1,
|
| 191 |
maximum=2048,
|
| 192 |
-
value=
|
| 193 |
step=1,
|
| 194 |
label="Max new tokens"
|
| 195 |
),
|
|
@@ -207,12 +256,6 @@ demo = gr.ChatInterface(
|
|
| 207 |
step=0.05,
|
| 208 |
label="Top-p (nucleus sampling)"
|
| 209 |
),
|
| 210 |
-
gr.Radio(
|
| 211 |
-
choices=list(IMAGE_STYLES.values()),
|
| 212 |
-
value="3840 x 2160",
|
| 213 |
-
label="Image Style",
|
| 214 |
-
info="Select the style for generated images"
|
| 215 |
-
),
|
| 216 |
]
|
| 217 |
)
|
| 218 |
|
|
|
|
| 6 |
from indic_transliteration.sanscript import transliterate
|
| 7 |
import langdetect
|
| 8 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
# Initialize clients
|
| 11 |
text_client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 12 |
+
image_client = InferenceClient("ijohn07/DALLE-4K")
|
| 13 |
|
| 14 |
+
def detect_language_script(text: str) -> tuple[str, str]:
|
| 15 |
+
"""Detect language and script of the input text.
|
| 16 |
+
Returns (language_code, script_type)"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
try:
|
| 18 |
+
# Use confidence threshold to avoid false detections
|
| 19 |
+
lang_detect = langdetect.detect_langs(text)
|
| 20 |
+
if lang_detect[0].prob > 0.8:
|
| 21 |
+
# Only accept high confidence detections
|
| 22 |
+
lang = lang_detect[0].lang
|
| 23 |
+
else:
|
| 24 |
+
lang = 'en' # Default to English if unsure
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
script = None
|
| 27 |
+
try:
|
| 28 |
+
script = detect_script(text)
|
| 29 |
+
except:
|
| 30 |
+
pass
|
| 31 |
+
return lang, script
|
| 32 |
+
except:
|
| 33 |
+
return 'en', None
|
| 34 |
+
|
| 35 |
+
def is_romanized_indic(text: str) -> bool:
|
| 36 |
+
"""Check if text appears to be romanized Indic language.
|
| 37 |
+
More strict pattern matching."""
|
| 38 |
+
# Common Bengali romanized patterns with word boundaries
|
| 39 |
+
bengali_patterns = [
|
| 40 |
+
r'\b(ami|tumi|apni)\b', # Common pronouns
|
| 41 |
+
r'\b(ache|achen|thako|thaken)\b', # Common verbs
|
| 42 |
+
r'\b(kemon|bhalo|kharap)\b', # Common adjectives
|
| 43 |
+
r'\b(ki|kothay|keno)\b' # Common question words
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
# Require multiple matches to confirm it's actually Bengali
|
| 47 |
+
text_lower = text.lower()
|
| 48 |
+
matches = sum(1 for pattern in bengali_patterns if re.search(pattern, text_lower))
|
| 49 |
+
return matches >= 2 # Require at least 2 matches to consider it Bengali
|
| 50 |
+
|
| 51 |
+
def translate_text(text: str, target_lang='en') -> tuple[str, str, bool]:
|
| 52 |
+
"""Translate text to target language, with more conservative translation logic."""
|
| 53 |
+
# Skip translation for very short inputs or basic greetings
|
| 54 |
+
if len(text.split()) <= 2 or text.lower() in ['hello', 'hi', 'hey']:
|
| 55 |
+
return text, 'en', False
|
| 56 |
+
|
| 57 |
+
original_lang, script = detect_language_script(text)
|
| 58 |
+
is_transliterated = False
|
| 59 |
+
|
| 60 |
+
# Only process if confident it's non-English
|
| 61 |
+
if original_lang != 'en' and len(text.split()) > 2:
|
| 62 |
+
try:
|
| 63 |
+
translator = GoogleTranslator(source='auto', target=target_lang)
|
| 64 |
+
translated = translator.translate(text)
|
| 65 |
+
return translated, original_lang, is_transliterated
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Translation error: {e}")
|
| 68 |
+
return text, 'en', False
|
| 69 |
+
|
| 70 |
+
# Check for romanized Indic text only if it's a longer input
|
| 71 |
+
if original_lang == 'en' and len(text.split()) > 2 and is_romanized_indic(text):
|
| 72 |
+
text = romanized_to_bengali(text)
|
| 73 |
+
return translate_text(text, target_lang) # Recursive call with Bengali script
|
| 74 |
+
|
| 75 |
+
return text, 'en', False
|
| 76 |
+
|
| 77 |
+
def check_custom_responses(message: str) -> str:
|
| 78 |
+
"""Check for specific patterns and return custom responses."""
|
| 79 |
+
message_lower = message.lower()
|
| 80 |
+
custom_responses = {
|
| 81 |
+
"what is ur name?": "xylaria",
|
| 82 |
+
"what is your name?": "xylaria",
|
| 83 |
+
"what's your name?": "xylaria",
|
| 84 |
+
"whats your name": "xylaria",
|
| 85 |
+
"how many 'r' is in strawberry?": "3",
|
| 86 |
+
"who is your developer?": "sk md saad amin",
|
| 87 |
+
"how many r is in strawberry": "3",
|
| 88 |
+
"who is ur dev": "sk md saad amin",
|
| 89 |
+
"who is ur developer": "sk md saad amin",
|
| 90 |
+
}
|
| 91 |
+
for pattern, response in custom_responses.items():
|
| 92 |
+
if pattern in message_lower:
|
| 93 |
+
return response
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
def is_image_request(message: str) -> bool:
|
| 97 |
+
"""Detect if the message is requesting image generation."""
|
| 98 |
+
image_triggers = [
|
| 99 |
+
"generate an image",
|
| 100 |
+
"create an image",
|
| 101 |
+
"draw",
|
| 102 |
+
"make a picture",
|
| 103 |
+
"generate a picture",
|
| 104 |
+
"create a picture",
|
| 105 |
+
"generate art",
|
| 106 |
+
"create art",
|
| 107 |
+
"make art",
|
| 108 |
+
"visualize",
|
| 109 |
+
"show me",
|
| 110 |
+
]
|
| 111 |
+
message_lower = message.lower()
|
| 112 |
+
return any(trigger in message_lower for trigger in image_triggers)
|
| 113 |
+
|
| 114 |
+
def generate_image(prompt: str) -> str:
|
| 115 |
+
"""Generate an image using DALLE-4K model."""
|
| 116 |
+
try:
|
| 117 |
+
response = image_client.text_to_image(
|
| 118 |
+
prompt,
|
| 119 |
+
parameters={
|
| 120 |
+
"negative_prompt": "blurry, bad quality, nsfw",
|
| 121 |
+
"num_inference_steps": 30,
|
| 122 |
+
"guidance_scale": 7.5
|
| 123 |
+
}
|
| 124 |
+
)
|
| 125 |
+
# Save the image and return the path or base64 string
|
| 126 |
+
# Note: Implementation depends on how you want to handle the image output
|
| 127 |
+
return response
|
| 128 |
except Exception as e:
|
| 129 |
print(f"Image generation error: {e}")
|
| 130 |
return None
|
|
|
|
| 131 |
def romanized_to_bengali(text: str) -> str:
|
| 132 |
"""Convert romanized Bengali text to Bengali script."""
|
| 133 |
bengali_mappings = {
|
|
|
|
| 163 |
max_tokens,
|
| 164 |
temperature,
|
| 165 |
top_p,
|
|
|
|
| 166 |
):
|
| 167 |
# First check for custom responses
|
| 168 |
custom_response = check_custom_responses(message)
|
|
|
|
| 173 |
# Check if this is an image generation request
|
| 174 |
if is_image_request(message):
|
| 175 |
try:
|
| 176 |
+
image = generate_image(message)
|
| 177 |
if image:
|
| 178 |
+
yield f"Here's your generated image based on: {message}"
|
| 179 |
+
# You'll need to implement the actual image display logic
|
| 180 |
+
# depending on your Gradio interface requirements
|
| 181 |
return
|
| 182 |
else:
|
| 183 |
yield "Sorry, I couldn't generate the image. Please try again."
|
|
|
|
| 186 |
yield f"An error occurred while generating the image: {str(e)}"
|
| 187 |
return
|
| 188 |
|
| 189 |
+
# Handle translation with more conservative approach
|
| 190 |
translated_msg, original_lang, was_transliterated = translate_text(message)
|
| 191 |
+
|
| 192 |
+
# Prepare conversation history - only translate if necessary
|
| 193 |
messages = [{"role": "system", "content": system_message}]
|
| 194 |
for val in history:
|
| 195 |
if val[0]:
|
| 196 |
+
# Only translate longer messages
|
| 197 |
if len(val[0].split()) > 2:
|
| 198 |
trans_user_msg, _, _ = translate_text(val[0])
|
| 199 |
messages.append({"role": "user", "content": trans_user_msg})
|
|
|
|
| 204 |
|
| 205 |
messages.append({"role": "user", "content": translated_msg})
|
| 206 |
|
| 207 |
+
# Get response from model
|
| 208 |
response = ""
|
| 209 |
for message in text_client.chat_completion(
|
| 210 |
messages,
|
|
|
|
| 216 |
token = message.choices[0].delta.content
|
| 217 |
response += token
|
| 218 |
|
| 219 |
+
# Only translate back if the original was definitely non-English
|
| 220 |
if original_lang != 'en' and len(message.split()) > 2:
|
| 221 |
try:
|
| 222 |
translator = GoogleTranslator(source='en', target=original_lang)
|
|
|
|
| 227 |
else:
|
| 228 |
yield response
|
| 229 |
|
| 230 |
+
# Updated Gradio interface to handle images
|
| 231 |
demo = gr.ChatInterface(
|
| 232 |
respond,
|
| 233 |
additional_inputs=[
|
|
|
|
| 238 |
gr.Slider(
|
| 239 |
minimum=1,
|
| 240 |
maximum=2048,
|
| 241 |
+
value=512,
|
| 242 |
step=1,
|
| 243 |
label="Max new tokens"
|
| 244 |
),
|
|
|
|
| 256 |
step=0.05,
|
| 257 |
label="Top-p (nucleus sampling)"
|
| 258 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
]
|
| 260 |
)
|
| 261 |
|