Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -11,130 +11,44 @@ import json
|
|
| 11 |
import base64
|
| 12 |
from PIL import Image
|
| 13 |
import io
|
|
|
|
| 14 |
|
| 15 |
# Initialize clients
|
| 16 |
text_client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
| 17 |
SPACE_URL = "https://ijohn07-dalle-4k.hf.space"
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
try:
|
| 33 |
-
script = detect_script(text)
|
| 34 |
-
except:
|
| 35 |
-
pass
|
| 36 |
-
return lang, script
|
| 37 |
-
except:
|
| 38 |
-
return 'en', None
|
| 39 |
-
|
| 40 |
-
def is_romanized_indic(text: str) -> bool:
|
| 41 |
-
"""Check if text appears to be romanized Indic language.
|
| 42 |
-
More strict pattern matching."""
|
| 43 |
-
# Common Bengali romanized patterns with word boundaries
|
| 44 |
-
bengali_patterns = [
|
| 45 |
-
r'\b(ami|tumi|apni)\b', # Common pronouns
|
| 46 |
-
r'\b(ache|achen|thako|thaken)\b', # Common verbs
|
| 47 |
-
r'\b(kemon|bhalo|kharap)\b', # Common adjectives
|
| 48 |
-
r'\b(ki|kothay|keno)\b' # Common question words
|
| 49 |
-
]
|
| 50 |
-
|
| 51 |
-
# Require multiple matches to confirm it's actually Bengali
|
| 52 |
-
text_lower = text.lower()
|
| 53 |
-
matches = sum(1 for pattern in bengali_patterns if re.search(pattern, text_lower))
|
| 54 |
-
return matches >= 2 # Require at least 2 matches to consider it Bengali
|
| 55 |
-
|
| 56 |
-
def translate_text(text: str, target_lang='en') -> tuple[str, str, bool]:
|
| 57 |
-
"""Translate text to target language, with more conservative translation logic."""
|
| 58 |
-
# Skip translation for very short inputs or basic greetings
|
| 59 |
-
if len(text.split()) <= 2 or text.lower() in ['hello', 'hi', 'hey']:
|
| 60 |
-
return text, 'en', False
|
| 61 |
-
|
| 62 |
-
original_lang, script = detect_language_script(text)
|
| 63 |
-
is_transliterated = False
|
| 64 |
-
|
| 65 |
-
# Only process if confident it's non-English
|
| 66 |
-
if original_lang != 'en' and len(text.split()) > 2:
|
| 67 |
-
try:
|
| 68 |
-
translator = GoogleTranslator(source='auto', target=target_lang)
|
| 69 |
-
translated = translator.translate(text)
|
| 70 |
-
return translated, original_lang, is_transliterated
|
| 71 |
-
except Exception as e:
|
| 72 |
-
print(f"Translation error: {e}")
|
| 73 |
-
return text, 'en', False
|
| 74 |
-
|
| 75 |
-
# Check for romanized Indic text only if it's a longer input
|
| 76 |
-
if original_lang == 'en' and len(text.split()) > 2 and is_romanized_indic(text):
|
| 77 |
-
text = romanized_to_bengali(text)
|
| 78 |
-
return translate_text(text, target_lang) # Recursive call with Bengali script
|
| 79 |
-
|
| 80 |
-
return text, 'en', False
|
| 81 |
-
|
| 82 |
-
def check_custom_responses(message: str) -> str:
|
| 83 |
-
"""Check for specific patterns and return custom responses."""
|
| 84 |
-
message_lower = message.lower()
|
| 85 |
-
custom_responses = {
|
| 86 |
-
"what is ur name?": "xylaria",
|
| 87 |
-
"what is your name?": "xylaria",
|
| 88 |
-
"what's your name?": "xylaria",
|
| 89 |
-
"whats your name": "xylaria",
|
| 90 |
-
"how many 'r' is in strawberry?": "3",
|
| 91 |
-
"who is your developer?": "sk md saad amin",
|
| 92 |
-
"how many r is in strawberry": "3",
|
| 93 |
-
"who is ur dev": "sk md saad amin",
|
| 94 |
-
"who is ur developer": "sk md saad amin",
|
| 95 |
-
}
|
| 96 |
-
for pattern, response in custom_responses.items():
|
| 97 |
-
if pattern in message_lower:
|
| 98 |
-
return response
|
| 99 |
-
return None
|
| 100 |
-
|
| 101 |
-
def is_image_request(message: str) -> bool:
|
| 102 |
-
"""Detect if the message is requesting image generation."""
|
| 103 |
-
image_triggers = [
|
| 104 |
-
"generate an image",
|
| 105 |
-
"create an image",
|
| 106 |
-
"draw",
|
| 107 |
-
"make a picture",
|
| 108 |
-
"generate a picture",
|
| 109 |
-
"create a picture",
|
| 110 |
-
"generate art",
|
| 111 |
-
"create art",
|
| 112 |
-
"make art",
|
| 113 |
-
"visualize",
|
| 114 |
-
"show me",
|
| 115 |
-
]
|
| 116 |
-
message_lower = message.lower()
|
| 117 |
-
return any(trigger in message_lower for trigger in image_triggers)
|
| 118 |
-
|
| 119 |
-
def generate_image_space(prompt: str) -> Image.Image:
|
| 120 |
-
"""Generate an image using the DALLE-4K Space."""
|
| 121 |
try:
|
| 122 |
# First get the session hash
|
| 123 |
response = requests.post(f"{SPACE_URL}/queue/join")
|
| 124 |
session_hash = response.json().get('session_hash')
|
| 125 |
|
| 126 |
-
#
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
"
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
| 134 |
|
|
|
|
| 135 |
response = requests.post(f"{SPACE_URL}/run/predict", json={
|
| 136 |
"data": [
|
| 137 |
-
prompt, # Prompt
|
| 138 |
"", # Negative prompt
|
| 139 |
7.5, # Guidance scale
|
| 140 |
30, # Steps
|
|
@@ -205,6 +119,7 @@ def respond(
|
|
| 205 |
max_tokens,
|
| 206 |
temperature,
|
| 207 |
top_p,
|
|
|
|
| 208 |
):
|
| 209 |
# First check for custom responses
|
| 210 |
custom_response = check_custom_responses(message)
|
|
@@ -215,9 +130,10 @@ def respond(
|
|
| 215 |
# Check if this is an image generation request
|
| 216 |
if is_image_request(message):
|
| 217 |
try:
|
| 218 |
-
image = generate_image_space(message)
|
| 219 |
if image:
|
| 220 |
-
|
|
|
|
| 221 |
return
|
| 222 |
else:
|
| 223 |
yield "Sorry, I couldn't generate the image. Please try again."
|
|
@@ -226,14 +142,11 @@ def respond(
|
|
| 226 |
yield f"An error occurred while generating the image: {str(e)}"
|
| 227 |
return
|
| 228 |
|
| 229 |
-
#
|
| 230 |
translated_msg, original_lang, was_transliterated = translate_text(message)
|
| 231 |
-
|
| 232 |
-
# Prepare conversation history - only translate if necessary
|
| 233 |
messages = [{"role": "system", "content": system_message}]
|
| 234 |
for val in history:
|
| 235 |
if val[0]:
|
| 236 |
-
# Only translate longer messages
|
| 237 |
if len(val[0].split()) > 2:
|
| 238 |
trans_user_msg, _, _ = translate_text(val[0])
|
| 239 |
messages.append({"role": "user", "content": trans_user_msg})
|
|
@@ -244,7 +157,6 @@ def respond(
|
|
| 244 |
|
| 245 |
messages.append({"role": "user", "content": translated_msg})
|
| 246 |
|
| 247 |
-
# Get response from model
|
| 248 |
response = ""
|
| 249 |
for message in text_client.chat_completion(
|
| 250 |
messages,
|
|
@@ -256,7 +168,6 @@ def respond(
|
|
| 256 |
token = message.choices[0].delta.content
|
| 257 |
response += token
|
| 258 |
|
| 259 |
-
# Only translate back if the original was definitely non-English
|
| 260 |
if original_lang != 'en' and len(message.split()) > 2:
|
| 261 |
try:
|
| 262 |
translator = GoogleTranslator(source='en', target=original_lang)
|
|
@@ -267,7 +178,7 @@ def respond(
|
|
| 267 |
else:
|
| 268 |
yield response
|
| 269 |
|
| 270 |
-
# Updated Gradio interface
|
| 271 |
demo = gr.ChatInterface(
|
| 272 |
respond,
|
| 273 |
additional_inputs=[
|
|
@@ -278,7 +189,7 @@ demo = gr.ChatInterface(
|
|
| 278 |
gr.Slider(
|
| 279 |
minimum=1,
|
| 280 |
maximum=2048,
|
| 281 |
-
value=
|
| 282 |
step=1,
|
| 283 |
label="Max new tokens"
|
| 284 |
),
|
|
@@ -296,6 +207,12 @@ demo = gr.ChatInterface(
|
|
| 296 |
step=0.05,
|
| 297 |
label="Top-p (nucleus sampling)"
|
| 298 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
]
|
| 300 |
)
|
| 301 |
|
|
|
|
| 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 |
SPACE_URL = "https://ijohn07-dalle-4k.hf.space"
|
| 19 |
|
| 20 |
+
# Add image style options
|
| 21 |
+
IMAGE_STYLES = {
|
| 22 |
+
"3840 x 2160": "3840 x 2160",
|
| 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 |
# First get the session hash
|
| 35 |
response = requests.post(f"{SPACE_URL}/queue/join")
|
| 36 |
session_hash = response.json().get('session_hash')
|
| 37 |
|
| 38 |
+
# Modify prompt based on style
|
| 39 |
+
if style != "(No style)":
|
| 40 |
+
# Format the prompt according to the style
|
| 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
|
|
|
|
| 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 |
# Check if this is an image generation request
|
| 131 |
if is_image_request(message):
|
| 132 |
try:
|
| 133 |
+
image = generate_image_space(message, image_style)
|
| 134 |
if image:
|
| 135 |
+
style_info = f" using {image_style} style" if image_style != "(No style)" else ""
|
| 136 |
+
yield (image, f"Here's your generated image based on: {message}{style_info}")
|
| 137 |
return
|
| 138 |
else:
|
| 139 |
yield "Sorry, I couldn't generate the image. Please try again."
|
|
|
|
| 142 |
yield f"An error occurred while generating the image: {str(e)}"
|
| 143 |
return
|
| 144 |
|
| 145 |
+
# Rest of the code remains the same...
|
| 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 |
|
| 158 |
messages.append({"role": "user", "content": translated_msg})
|
| 159 |
|
|
|
|
| 160 |
response = ""
|
| 161 |
for message in text_client.chat_completion(
|
| 162 |
messages,
|
|
|
|
| 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 |
else:
|
| 179 |
yield response
|
| 180 |
|
| 181 |
+
# Updated Gradio interface with image style selector
|
| 182 |
demo = gr.ChatInterface(
|
| 183 |
respond,
|
| 184 |
additional_inputs=[
|
|
|
|
| 189 |
gr.Slider(
|
| 190 |
minimum=1,
|
| 191 |
maximum=2048,
|
| 192 |
+
value=2048,
|
| 193 |
step=1,
|
| 194 |
label="Max new tokens"
|
| 195 |
),
|
|
|
|
| 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 |
|