GChilukala commited on
Commit
a09777d
ยท
verified ยท
1 Parent(s): ba98102

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -128
app.py CHANGED
@@ -1,5 +1,5 @@
1
  """
2
- ๐Ÿ“ฑ Instagram Caption Generator - Simplified Version
3
  ==================================================
4
 
5
  AI-Powered Instagram Content Creation Suite with SambaNova Integration
@@ -8,7 +8,7 @@ Multi-Modal AI Analysis (Vision + Text) + Multi-Language Support
8
  ๐Ÿš€ Key Features:
9
  - SambaNova Llama-4-Maverick Integration
10
  - Multi-Language Support (German, Chinese, French, Arabic via Hugging Face)
11
- - Advanced Gradio Interface
12
  - Advanced Error Handling & Security
13
 
14
  Author: MCP Hackathon 2025 Participant
@@ -133,14 +133,14 @@ class AdvancedInstagramGenerator:
133
  print("โœ… AI models setup completed!")
134
 
135
  def setup_huggingface_client(self):
136
- """Initialize Hugging Face client for translations"""
137
  try:
138
- # Initialize Hugging Face client
139
  hf_token = os.environ.get("HF_TOKEN")
140
  if hf_token:
 
141
  self.hf_client = InferenceClient(
142
- provider="hf-inference",
143
- api_key=hf_token,
144
  )
145
  print("โœ… Hugging Face client initialized successfully!")
146
  self.hf_client_working = True
@@ -1026,16 +1026,18 @@ Format:
1026
  [Hashtags]"""
1027
 
1028
 
1029
- # Global generator instance with caching
1030
  @functools.lru_cache(maxsize=1)
1031
  def get_generator():
1032
  """Get cached generator instance"""
1033
  return AdvancedInstagramGenerator()
1034
 
 
1035
  try:
1036
  generator = get_generator()
1037
  setup_success = True
1038
  setup_error = ""
 
1039
  except Exception as e:
1040
  generator = None
1041
  setup_success = False
@@ -1043,25 +1045,35 @@ except Exception as e:
1043
  print(f"โŒ Setup failed: {e}")
1044
 
1045
 
1046
- # Gradio Interface Functions
1047
- async def generate_advanced_caption_interface(uploaded_files, style, audience,
1048
- custom_prompt):
1049
- """Advanced interface function for caption generation"""
1050
  if not setup_success:
1051
  return f"โŒ Setup Error: {setup_error}", ""
1052
 
 
 
 
 
 
1053
  images = []
1054
  if uploaded_files:
1055
  for file in uploaded_files[:3]:
1056
  try:
1057
  image = Image.open(file.name)
1058
  images.append(image)
 
1059
  except Exception as e:
1060
  return f"โŒ Error processing file: {e}", ""
1061
 
1062
- result = await generator.generate_advanced_caption(
1063
- images, style, audience, custom_prompt
1064
- )
 
 
 
 
 
1065
 
1066
  # Extract clean caption for multi-language processing
1067
  caption_only = ""
@@ -1087,12 +1099,14 @@ async def generate_advanced_caption_interface(uploaded_files, style, audience,
1087
  return result, caption_only
1088
 
1089
 
1090
- async def generate_multiple_captions_interface(uploaded_files, style, audience,
1091
- custom_prompt):
1092
- """Generate multiple caption variations using Meta-Llama-3.2-3B-Instruct"""
1093
  if not setup_success:
1094
  return f"โŒ Setup Error: {setup_error}"
1095
 
 
 
 
1096
  images = []
1097
  if uploaded_files:
1098
  for file in uploaded_files[:3]:
@@ -1105,126 +1119,141 @@ async def generate_multiple_captions_interface(uploaded_files, style, audience,
1105
  if not images:
1106
  return "โŒ Please upload at least one image to generate caption variations."
1107
 
1108
- # First generate the main caption using Llama-4-Maverick
1109
- main_result = await generator.generate_advanced_caption(
1110
- images, style, audience, custom_prompt
1111
- )
1112
-
1113
- # Extract just the caption text (without the header and footer)
1114
- base_caption = ""
1115
- if "โœจ AI-GENERATED INSTAGRAM CONTENT:" in main_result:
1116
- lines = main_result.split('\n')
1117
- caption_lines = []
1118
- start_capturing = False
1119
 
1120
- for line in lines:
1121
- if "โœจ AI-GENERATED INSTAGRAM CONTENT:" in line:
1122
- start_capturing = True
1123
- continue
1124
- elif "๐Ÿค– Powered by SambaNova" in line:
1125
- break
1126
- elif start_capturing and line.strip():
1127
- caption_lines.append(line)
1128
 
1129
- base_caption = '\n'.join(caption_lines).strip()
1130
-
1131
- if not base_caption:
1132
- return "โŒ Failed to generate base caption for variations"
1133
-
1134
- # Generate 3 variations using Meta-Llama-3.2-3B-Instruct
1135
- variations = await generator.generate_mistral_variations(base_caption, count=3)
1136
-
1137
- # Format the results
1138
- formatted_result = "โœจ ALTERNATIVE CAPTIONS:\n\n"
1139
- formatted_result += "=" * 60 + "\n\n"
1140
-
1141
- for i, variation in enumerate(variations, 1):
1142
- formatted_result += f"๐Ÿ“ ALTERNATIVE {i}:\n"
1143
- formatted_result += f"{variation}\n"
 
 
 
 
 
 
 
 
 
 
 
1144
  formatted_result += "=" * 60 + "\n\n"
1145
-
1146
- return formatted_result
 
 
 
 
 
 
 
1147
 
1148
 
1149
- async def translate_caption_interface(base_caption, selected_languages):
1150
- """Generate multi-language versions of captions"""
1151
  if not base_caption.strip():
1152
  return "โŒ Please provide a caption to translate"
1153
 
1154
  if not selected_languages:
1155
  return "โŒ Please select at least one language"
1156
 
 
 
 
1157
  result = "๐ŸŒ MULTI-LANGUAGE CAPTION VERSIONS:\n\n"
1158
  result += "=" * 60 + "\n\n"
1159
 
 
 
 
1160
  for language in selected_languages:
1161
- if language == "๐Ÿ‡ฉ๐Ÿ‡ช German":
1162
- # Use Hugging Face for German translation
1163
- if generator and generator.hf_client_working:
1164
- try:
1165
- german_translation = await generator.translate_to_german(base_caption)
1166
- result += "๐Ÿ‡ฉ๐Ÿ‡ช GERMAN VERSION (Hugging Face T5):\n"
1167
- result += f"{german_translation}\n\n"
1168
- result += "=" * 60 + "\n\n"
1169
- except Exception as e:
 
 
 
 
 
1170
  fallback_german = generator.get_fallback_german_translation(base_caption)
1171
  result += f"{fallback_german}\n\n"
1172
  result += "=" * 60 + "\n\n"
1173
- else:
1174
- fallback_german = generator.get_fallback_german_translation(base_caption)
1175
- result += f"{fallback_german}\n\n"
1176
- result += "=" * 60 + "\n\n"
1177
-
1178
- elif language == "๐Ÿ‡จ๐Ÿ‡ณ Chinese":
1179
- # Use Hugging Face for Chinese translation
1180
- if generator and generator.hf_client_working:
1181
- try:
1182
- chinese_translation = await generator.translate_to_chinese(base_caption)
1183
- result += "๐Ÿ‡จ๐Ÿ‡ณ CHINESE VERSION (Hugging Face MT5):\n"
1184
- result += f"{chinese_translation}\n\n"
1185
- result += "=" * 60 + "\n\n"
1186
- except Exception as e:
1187
  fallback_chinese = generator.get_fallback_chinese_translation(base_caption)
1188
  result += f"{fallback_chinese}\n\n"
1189
  result += "=" * 60 + "\n\n"
1190
- else:
1191
- fallback_chinese = generator.get_fallback_chinese_translation(base_caption)
1192
- result += f"{fallback_chinese}\n\n"
1193
- result += "=" * 60 + "\n\n"
1194
-
1195
- elif language == "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi":
1196
- # Use Hugging Face for Hindi translation
1197
- if generator and generator.hf_client_working:
1198
- try:
1199
- hindi_translation = await generator.translate_to_hindi(base_caption)
1200
- result += "๐Ÿ‡ฎ๐Ÿ‡ณ HINDI VERSION (Hugging Face Helsinki-NLP):\n"
1201
- result += f"{hindi_translation}\n\n"
1202
- result += "=" * 60 + "\n\n"
1203
- except Exception as e:
1204
  fallback_hindi = generator.get_fallback_hindi_translation(base_caption)
1205
  result += f"{fallback_hindi}\n\n"
1206
  result += "=" * 60 + "\n\n"
1207
- else:
1208
- fallback_hindi = generator.get_fallback_hindi_translation(base_caption)
1209
- result += f"{fallback_hindi}\n\n"
1210
- result += "=" * 60 + "\n\n"
1211
-
1212
- elif language == "๐Ÿ‡ธ๐Ÿ‡ฆ Arabic":
1213
- # Use Hugging Face for Arabic translation
1214
- if generator and generator.hf_client_working:
1215
- try:
1216
- arabic_translation = await generator.translate_to_arabic(base_caption)
1217
- result += "๐Ÿ‡ธ๐Ÿ‡ฆ ARABIC VERSION (Hugging Face Marefa):\n"
1218
- result += f"{arabic_translation}\n\n"
1219
- result += "=" * 60 + "\n\n"
1220
- except Exception as e:
1221
  fallback_arabic = generator.get_fallback_arabic_translation(base_caption)
1222
  result += f"{fallback_arabic}\n\n"
1223
  result += "=" * 60 + "\n\n"
1224
- else:
1225
- fallback_arabic = generator.get_fallback_arabic_translation(base_caption)
1226
- result += f"{fallback_arabic}\n\n"
1227
- result += "=" * 60 + "\n\n"
1228
 
1229
  if any(lang in selected_languages for lang in ["๐Ÿ‡ฉ๐Ÿ‡ช German", "๐Ÿ‡จ๐Ÿ‡ณ Chinese", "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi", "๐Ÿ‡ธ๐Ÿ‡ฆ Arabic"]):
1230
  hf_langs = []
@@ -1245,7 +1274,7 @@ async def translate_caption_interface(base_caption, selected_languages):
1245
 
1246
 
1247
  def create_gradio_app():
1248
- """Create the Gradio app with SambaNova and Hugging Face integration"""
1249
 
1250
  # Championship-level CSS
1251
  css = """
@@ -1399,7 +1428,12 @@ def create_gradio_app():
1399
  }
1400
  """
1401
 
1402
- with gr.Blocks(css=css, title="๐Ÿ“ฑ Instagram Generator - MCP Hackathon 2025", theme=gr.themes.Glass()) as app:
 
 
 
 
 
1403
 
1404
  # Main Header
1405
  gr.HTML("""
@@ -1448,7 +1482,9 @@ def create_gradio_app():
1448
  gr.Markdown("### โš™๏ธ AI Configuration")
1449
 
1450
  with gr.Row():
 
1451
  caption_style = gr.Dropdown(
 
1452
  choices=[
1453
  "๐ŸŽฏ Viral Engagement",
1454
  "๐Ÿ’ผ Professional Brand",
@@ -1460,10 +1496,13 @@ def create_gradio_app():
1460
  "๐Ÿ”ฅ Trending Culture"
1461
  ],
1462
  value="๐ŸŽฏ Viral Engagement",
1463
- label="๐ŸŽจ Caption Style"
 
 
1464
  )
1465
 
1466
  target_audience = gr.Dropdown(
 
1467
  choices=[
1468
  "๐ŸŒŸ General Audience",
1469
  "๐Ÿ’ผ Business Professionals",
@@ -1477,13 +1516,16 @@ def create_gradio_app():
1477
  "๐ŸŽต Music Fans"
1478
  ],
1479
  value="๐ŸŒŸ General Audience",
1480
- label="๐Ÿ‘ฅ Target Audience"
 
 
1481
  )
1482
 
1483
  custom_prompt = gr.Textbox(
1484
  label="๐Ÿ’ฌ Advanced Instructions",
1485
  placeholder="e.g., 'Focus on sustainability messaging', 'Include product launch details', 'Emphasize community building'...",
1486
- lines=3
 
1487
  )
1488
 
1489
  generate_btn = gr.Button(
@@ -1503,7 +1545,8 @@ def create_gradio_app():
1503
  lines=15,
1504
  max_lines=20,
1505
  show_copy_button=True,
1506
- placeholder="Upload images and generate your Instagram content..."
 
1507
  )
1508
 
1509
  with gr.Row():
@@ -1517,7 +1560,8 @@ def create_gradio_app():
1517
  label="โœจ Alternative Captions",
1518
  lines=15,
1519
  show_copy_button=True,
1520
- placeholder="Generate 3 different caption alternatives using Meta-Llama-3.2-3B-Instruct..."
 
1521
  )
1522
 
1523
  # Multi-Language Tab
@@ -1530,18 +1574,21 @@ def create_gradio_app():
1530
  base_caption_input = gr.Textbox(
1531
  label="๐Ÿ“ Base Caption",
1532
  placeholder="Paste your generated caption here...",
1533
- lines=5
 
1534
  )
1535
 
 
1536
  language_selector = gr.CheckboxGroup(
 
1537
  choices=[
1538
  "๐Ÿ‡ฉ๐Ÿ‡ช German",
1539
  "๐Ÿ‡จ๐Ÿ‡ณ Chinese",
1540
  "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi",
1541
  "๐Ÿ‡ธ๐Ÿ‡ฆ Arabic"
1542
  ],
1543
- label="๐ŸŒ Select Languages",
1544
- value=["๐Ÿ‡ฉ๐Ÿ‡ช German", "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi"]
1545
  )
1546
 
1547
  translate_btn = gr.Button(
@@ -1554,7 +1601,8 @@ def create_gradio_app():
1554
  label="๐Ÿ—บ๏ธ Multi-Language Captions",
1555
  lines=20,
1556
  show_copy_button=True,
1557
- placeholder="Culturally adapted captions for global audiences..."
 
1558
  )
1559
 
1560
  # SambaNova Features Tab
@@ -1674,8 +1722,7 @@ variations = client.chat.completions.create(
1674
  from huggingface_hub import InferenceClient
1675
 
1676
  client = InferenceClient(
1677
- provider="hf-inference",
1678
- api_key=os.environ["HF_TOKEN"],
1679
  )
1680
 
1681
  # German translation
@@ -1712,26 +1759,34 @@ arabic_result = client.translation(
1712
  label="๐Ÿ”ง Hugging Face Translation Code"
1713
  )
1714
 
1715
- # Event Handlers
 
 
 
1716
  generate_btn.click(
1717
  fn=generate_advanced_caption_interface,
1718
  inputs=[images, caption_style, target_audience, custom_prompt],
1719
- outputs=[output, base_caption_input]
 
1720
  )
1721
 
1722
  # Generate multiple alternatives
1723
  alternatives_btn.click(
1724
  fn=generate_multiple_captions_interface,
1725
  inputs=[images, caption_style, target_audience, custom_prompt],
1726
- outputs=alternatives_output
 
1727
  )
1728
 
1729
  # Multi-language translation
1730
  translate_btn.click(
1731
  fn=translate_caption_interface,
1732
  inputs=[base_caption_input, language_selector],
1733
- outputs=multilingual_output
 
1734
  )
 
 
1735
 
1736
  return app
1737
 
@@ -1745,6 +1800,7 @@ def main():
1745
  if not setup_success:
1746
  print(f"โŒ Setup failed: {setup_error}")
1747
  print("๐Ÿ’ก Please check your API configuration")
 
1748
 
1749
  # Status messages
1750
  sambanova_msg = "โœ… SambaNova ready!" if generator and generator.sambanova_client_working else "โš ๏ธ SambaNova fallback mode"
@@ -1757,7 +1813,20 @@ def main():
1757
 
1758
  # Create and launch the app
1759
  app = create_gradio_app()
1760
- app.launch(mcp_server=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
1761
 
1762
 
1763
  if __name__ == "__main__":
 
1
  """
2
+ ๐Ÿ“ฑ Instagram Caption Generator - Simplified Version (FIXED DROPDOWNS)
3
  ==================================================
4
 
5
  AI-Powered Instagram Content Creation Suite with SambaNova Integration
 
8
  ๐Ÿš€ Key Features:
9
  - SambaNova Llama-4-Maverick Integration
10
  - Multi-Language Support (German, Chinese, French, Arabic via Hugging Face)
11
+ - Advanced Gradio Interface with WORKING DROPDOWNS
12
  - Advanced Error Handling & Security
13
 
14
  Author: MCP Hackathon 2025 Participant
 
133
  print("โœ… AI models setup completed!")
134
 
135
  def setup_huggingface_client(self):
136
+ """Initialize Hugging Face client for translations - FIXED"""
137
  try:
138
+ # Initialize Hugging Face client - FIXED INITIALIZATION
139
  hf_token = os.environ.get("HF_TOKEN")
140
  if hf_token:
141
+ # FIXED: Use correct initialization method
142
  self.hf_client = InferenceClient(
143
+ token=hf_token, # Changed from provider and api_key
 
144
  )
145
  print("โœ… Hugging Face client initialized successfully!")
146
  self.hf_client_working = True
 
1026
  [Hashtags]"""
1027
 
1028
 
1029
+ # Global generator instance with caching - FIXED
1030
  @functools.lru_cache(maxsize=1)
1031
  def get_generator():
1032
  """Get cached generator instance"""
1033
  return AdvancedInstagramGenerator()
1034
 
1035
+ # FIXED: Initialize generator with proper error handling
1036
  try:
1037
  generator = get_generator()
1038
  setup_success = True
1039
  setup_error = ""
1040
+ print("โœ… Generator initialized successfully!")
1041
  except Exception as e:
1042
  generator = None
1043
  setup_success = False
 
1045
  print(f"โŒ Setup failed: {e}")
1046
 
1047
 
1048
+ # FIXED: Gradio Interface Functions with proper parameter handling
1049
+ def generate_advanced_caption_interface(uploaded_files, style, audience, custom_prompt):
1050
+ """Advanced interface function for caption generation - FIXED"""
 
1051
  if not setup_success:
1052
  return f"โŒ Setup Error: {setup_error}", ""
1053
 
1054
+ # FIXED: Debug dropdown values
1055
+ print(f"๐Ÿ” DEBUG - Style received: {style}")
1056
+ print(f"๐Ÿ” DEBUG - Audience received: {audience}")
1057
+ print(f"๐Ÿ” DEBUG - Custom prompt: {custom_prompt}")
1058
+
1059
  images = []
1060
  if uploaded_files:
1061
  for file in uploaded_files[:3]:
1062
  try:
1063
  image = Image.open(file.name)
1064
  images.append(image)
1065
+ print(f"โœ… Loaded image: {file.name}")
1066
  except Exception as e:
1067
  return f"โŒ Error processing file: {e}", ""
1068
 
1069
+ # FIXED: Use asyncio.run for async function
1070
+ try:
1071
+ import asyncio
1072
+ result = asyncio.run(generator.generate_advanced_caption(
1073
+ images, style, audience, custom_prompt
1074
+ ))
1075
+ except Exception as e:
1076
+ return f"โŒ Generation error: {str(e)}", ""
1077
 
1078
  # Extract clean caption for multi-language processing
1079
  caption_only = ""
 
1099
  return result, caption_only
1100
 
1101
 
1102
+ def generate_multiple_captions_interface(uploaded_files, style, audience, custom_prompt):
1103
+ """Generate multiple caption variations - FIXED"""
 
1104
  if not setup_success:
1105
  return f"โŒ Setup Error: {setup_error}"
1106
 
1107
+ # FIXED: Debug dropdown values
1108
+ print(f"๐Ÿ” DEBUG VARIATIONS - Style: {style}, Audience: {audience}")
1109
+
1110
  images = []
1111
  if uploaded_files:
1112
  for file in uploaded_files[:3]:
 
1119
  if not images:
1120
  return "โŒ Please upload at least one image to generate caption variations."
1121
 
1122
+ # FIXED: Use asyncio.run for async functions
1123
+ try:
1124
+ import asyncio
 
 
 
 
 
 
 
 
1125
 
1126
+ # First generate the main caption using Llama-4-Maverick
1127
+ main_result = asyncio.run(generator.generate_advanced_caption(
1128
+ images, style, audience, custom_prompt
1129
+ ))
 
 
 
 
1130
 
1131
+ # Extract just the caption text (without the header and footer)
1132
+ base_caption = ""
1133
+ if "โœจ AI-GENERATED INSTAGRAM CONTENT:" in main_result:
1134
+ lines = main_result.split('\n')
1135
+ caption_lines = []
1136
+ start_capturing = False
1137
+
1138
+ for line in lines:
1139
+ if "โœจ AI-GENERATED INSTAGRAM CONTENT:" in line:
1140
+ start_capturing = True
1141
+ continue
1142
+ elif "๐Ÿค– Powered by SambaNova" in line:
1143
+ break
1144
+ elif start_capturing and line.strip():
1145
+ caption_lines.append(line)
1146
+
1147
+ base_caption = '\n'.join(caption_lines).strip()
1148
+
1149
+ if not base_caption:
1150
+ return "โŒ Failed to generate base caption for variations"
1151
+
1152
+ # Generate 3 variations using Meta-Llama-3.2-3B-Instruct
1153
+ variations = asyncio.run(generator.generate_mistral_variations(base_caption, count=3))
1154
+
1155
+ # Format the results
1156
+ formatted_result = "โœจ ALTERNATIVE CAPTIONS:\n\n"
1157
  formatted_result += "=" * 60 + "\n\n"
1158
+
1159
+ for i, variation in enumerate(variations, 1):
1160
+ formatted_result += f"๐Ÿ“ ALTERNATIVE {i}:\n"
1161
+ formatted_result += f"{variation}\n"
1162
+ formatted_result += "=" * 60 + "\n\n"
1163
+
1164
+ return formatted_result
1165
+ except Exception as e:
1166
+ return f"โŒ Variation generation error: {str(e)}"
1167
 
1168
 
1169
+ def translate_caption_interface(base_caption, selected_languages):
1170
+ """Generate multi-language versions of captions - FIXED"""
1171
  if not base_caption.strip():
1172
  return "โŒ Please provide a caption to translate"
1173
 
1174
  if not selected_languages:
1175
  return "โŒ Please select at least one language"
1176
 
1177
+ # FIXED: Debug language selection
1178
+ print(f"๐Ÿ” DEBUG TRANSLATION - Languages: {selected_languages}")
1179
+
1180
  result = "๐ŸŒ MULTI-LANGUAGE CAPTION VERSIONS:\n\n"
1181
  result += "=" * 60 + "\n\n"
1182
 
1183
+ # FIXED: Use asyncio.run for async translation functions
1184
+ import asyncio
1185
+
1186
  for language in selected_languages:
1187
+ try:
1188
+ if language == "๐Ÿ‡ฉ๐Ÿ‡ช German":
1189
+ # Use Hugging Face for German translation
1190
+ if generator and generator.hf_client_working:
1191
+ try:
1192
+ german_translation = asyncio.run(generator.translate_to_german(base_caption))
1193
+ result += "๐Ÿ‡ฉ๐Ÿ‡ช GERMAN VERSION (Hugging Face T5):\n"
1194
+ result += f"{german_translation}\n\n"
1195
+ result += "=" * 60 + "\n\n"
1196
+ except Exception as e:
1197
+ fallback_german = generator.get_fallback_german_translation(base_caption)
1198
+ result += f"{fallback_german}\n\n"
1199
+ result += "=" * 60 + "\n\n"
1200
+ else:
1201
  fallback_german = generator.get_fallback_german_translation(base_caption)
1202
  result += f"{fallback_german}\n\n"
1203
  result += "=" * 60 + "\n\n"
1204
+
1205
+ elif language == "๐Ÿ‡จ๐Ÿ‡ณ Chinese":
1206
+ # Use Hugging Face for Chinese translation
1207
+ if generator and generator.hf_client_working:
1208
+ try:
1209
+ chinese_translation = asyncio.run(generator.translate_to_chinese(base_caption))
1210
+ result += "๐Ÿ‡จ๐Ÿ‡ณ CHINESE VERSION (Hugging Face MT5):\n"
1211
+ result += f"{chinese_translation}\n\n"
1212
+ result += "=" * 60 + "\n\n"
1213
+ except Exception as e:
1214
+ fallback_chinese = generator.get_fallback_chinese_translation(base_caption)
1215
+ result += f"{fallback_chinese}\n\n"
1216
+ result += "=" * 60 + "\n\n"
1217
+ else:
1218
  fallback_chinese = generator.get_fallback_chinese_translation(base_caption)
1219
  result += f"{fallback_chinese}\n\n"
1220
  result += "=" * 60 + "\n\n"
1221
+
1222
+ elif language == "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi":
1223
+ # Use Hugging Face for Hindi translation
1224
+ if generator and generator.hf_client_working:
1225
+ try:
1226
+ hindi_translation = asyncio.run(generator.translate_to_hindi(base_caption))
1227
+ result += "๐Ÿ‡ฎ๐Ÿ‡ณ HINDI VERSION (Hugging Face Helsinki-NLP):\n"
1228
+ result += f"{hindi_translation}\n\n"
1229
+ result += "=" * 60 + "\n\n"
1230
+ except Exception as e:
1231
+ fallback_hindi = generator.get_fallback_hindi_translation(base_caption)
1232
+ result += f"{fallback_hindi}\n\n"
1233
+ result += "=" * 60 + "\n\n"
1234
+ else:
1235
  fallback_hindi = generator.get_fallback_hindi_translation(base_caption)
1236
  result += f"{fallback_hindi}\n\n"
1237
  result += "=" * 60 + "\n\n"
1238
+
1239
+ elif language == "๐Ÿ‡ธ๐Ÿ‡ฆ Arabic":
1240
+ # Use Hugging Face for Arabic translation
1241
+ if generator and generator.hf_client_working:
1242
+ try:
1243
+ arabic_translation = asyncio.run(generator.translate_to_arabic(base_caption))
1244
+ result += "๐Ÿ‡ธ๐Ÿ‡ฆ ARABIC VERSION (Hugging Face Marefa):\n"
1245
+ result += f"{arabic_translation}\n\n"
1246
+ result += "=" * 60 + "\n\n"
1247
+ except Exception as e:
1248
+ fallback_arabic = generator.get_fallback_arabic_translation(base_caption)
1249
+ result += f"{fallback_arabic}\n\n"
1250
+ result += "=" * 60 + "\n\n"
1251
+ else:
1252
  fallback_arabic = generator.get_fallback_arabic_translation(base_caption)
1253
  result += f"{fallback_arabic}\n\n"
1254
  result += "=" * 60 + "\n\n"
1255
+ except Exception as e:
1256
+ result += f"โŒ Error translating to {language}: {str(e)}\n\n"
 
 
1257
 
1258
  if any(lang in selected_languages for lang in ["๐Ÿ‡ฉ๐Ÿ‡ช German", "๐Ÿ‡จ๐Ÿ‡ณ Chinese", "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi", "๐Ÿ‡ธ๐Ÿ‡ฆ Arabic"]):
1259
  hf_langs = []
 
1274
 
1275
 
1276
  def create_gradio_app():
1277
+ """Create the Gradio app with SambaNova and Hugging Face integration - FIXED DROPDOWNS"""
1278
 
1279
  # Championship-level CSS
1280
  css = """
 
1428
  }
1429
  """
1430
 
1431
+ # FIXED: Use specific theme and create proper block structure
1432
+ with gr.Blocks(
1433
+ css=css,
1434
+ title="๐Ÿ“ฑ Instagram Generator - MCP Hackathon 2025",
1435
+ theme=gr.themes.Soft() # Changed from Glass to Soft for better dropdown compatibility
1436
+ ) as app:
1437
 
1438
  # Main Header
1439
  gr.HTML("""
 
1482
  gr.Markdown("### โš™๏ธ AI Configuration")
1483
 
1484
  with gr.Row():
1485
+ # FIXED: Improved dropdown definition with explicit parameters
1486
  caption_style = gr.Dropdown(
1487
+ label="๐ŸŽจ Caption Style",
1488
  choices=[
1489
  "๐ŸŽฏ Viral Engagement",
1490
  "๐Ÿ’ผ Professional Brand",
 
1496
  "๐Ÿ”ฅ Trending Culture"
1497
  ],
1498
  value="๐ŸŽฏ Viral Engagement",
1499
+ interactive=True, # FIXED: Explicitly set interactive
1500
+ allow_custom_value=False, # FIXED: Prevent custom values
1501
+ multiselect=False # FIXED: Single selection only
1502
  )
1503
 
1504
  target_audience = gr.Dropdown(
1505
+ label="๐Ÿ‘ฅ Target Audience",
1506
  choices=[
1507
  "๐ŸŒŸ General Audience",
1508
  "๐Ÿ’ผ Business Professionals",
 
1516
  "๐ŸŽต Music Fans"
1517
  ],
1518
  value="๐ŸŒŸ General Audience",
1519
+ interactive=True, # FIXED: Explicitly set interactive
1520
+ allow_custom_value=False, # FIXED: Prevent custom values
1521
+ multiselect=False # FIXED: Single selection only
1522
  )
1523
 
1524
  custom_prompt = gr.Textbox(
1525
  label="๐Ÿ’ฌ Advanced Instructions",
1526
  placeholder="e.g., 'Focus on sustainability messaging', 'Include product launch details', 'Emphasize community building'...",
1527
+ lines=3,
1528
+ interactive=True # FIXED: Explicitly set interactive
1529
  )
1530
 
1531
  generate_btn = gr.Button(
 
1545
  lines=15,
1546
  max_lines=20,
1547
  show_copy_button=True,
1548
+ placeholder="Upload images and generate your Instagram content...",
1549
+ interactive=False # FIXED: Output should not be interactive
1550
  )
1551
 
1552
  with gr.Row():
 
1560
  label="โœจ Alternative Captions",
1561
  lines=15,
1562
  show_copy_button=True,
1563
+ placeholder="Generate 3 different caption alternatives using Meta-Llama-3.2-3B-Instruct...",
1564
+ interactive=False # FIXED: Output should not be interactive
1565
  )
1566
 
1567
  # Multi-Language Tab
 
1574
  base_caption_input = gr.Textbox(
1575
  label="๐Ÿ“ Base Caption",
1576
  placeholder="Paste your generated caption here...",
1577
+ lines=5,
1578
+ interactive=True # FIXED: Input should be interactive
1579
  )
1580
 
1581
+ # FIXED: Improved checkbox group definition
1582
  language_selector = gr.CheckboxGroup(
1583
+ label="๐ŸŒ Select Languages",
1584
  choices=[
1585
  "๐Ÿ‡ฉ๐Ÿ‡ช German",
1586
  "๐Ÿ‡จ๐Ÿ‡ณ Chinese",
1587
  "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi",
1588
  "๐Ÿ‡ธ๐Ÿ‡ฆ Arabic"
1589
  ],
1590
+ value=["๐Ÿ‡ฉ๐Ÿ‡ช German", "๐Ÿ‡ฎ๐Ÿ‡ณ Hindi"],
1591
+ interactive=True # FIXED: Explicitly set interactive
1592
  )
1593
 
1594
  translate_btn = gr.Button(
 
1601
  label="๐Ÿ—บ๏ธ Multi-Language Captions",
1602
  lines=20,
1603
  show_copy_button=True,
1604
+ placeholder="Culturally adapted captions for global audiences...",
1605
+ interactive=False # FIXED: Output should not be interactive
1606
  )
1607
 
1608
  # SambaNova Features Tab
 
1722
  from huggingface_hub import InferenceClient
1723
 
1724
  client = InferenceClient(
1725
+ token=os.environ["HF_TOKEN"], # FIXED: Use token parameter
 
1726
  )
1727
 
1728
  # German translation
 
1759
  label="๐Ÿ”ง Hugging Face Translation Code"
1760
  )
1761
 
1762
+ # FIXED: Event Handlers with proper error handling
1763
+ print("๐Ÿ”— Setting up event handlers...")
1764
+
1765
+ # Main caption generation
1766
  generate_btn.click(
1767
  fn=generate_advanced_caption_interface,
1768
  inputs=[images, caption_style, target_audience, custom_prompt],
1769
+ outputs=[output, base_caption_input],
1770
+ show_progress=True # FIXED: Show progress indicator
1771
  )
1772
 
1773
  # Generate multiple alternatives
1774
  alternatives_btn.click(
1775
  fn=generate_multiple_captions_interface,
1776
  inputs=[images, caption_style, target_audience, custom_prompt],
1777
+ outputs=alternatives_output,
1778
+ show_progress=True # FIXED: Show progress indicator
1779
  )
1780
 
1781
  # Multi-language translation
1782
  translate_btn.click(
1783
  fn=translate_caption_interface,
1784
  inputs=[base_caption_input, language_selector],
1785
+ outputs=multilingual_output,
1786
+ show_progress=True # FIXED: Show progress indicator
1787
  )
1788
+
1789
+ print("โœ… Event handlers configured successfully!")
1790
 
1791
  return app
1792
 
 
1800
  if not setup_success:
1801
  print(f"โŒ Setup failed: {setup_error}")
1802
  print("๐Ÿ’ก Please check your API configuration")
1803
+ return
1804
 
1805
  # Status messages
1806
  sambanova_msg = "โœ… SambaNova ready!" if generator and generator.sambanova_client_working else "โš ๏ธ SambaNova fallback mode"
 
1813
 
1814
  # Create and launch the app
1815
  app = create_gradio_app()
1816
+
1817
+ # FIXED: Launch configuration for better compatibility
1818
+ app.launch(
1819
+ server_name="0.0.0.0",
1820
+ server_port=7860,
1821
+ share=False,
1822
+ show_error=True,
1823
+ debug=True, # FIXED: Enable debug mode for troubleshooting
1824
+ show_api=True, # FIXED: Show API for debugging
1825
+ inbrowser=False,
1826
+ favicon_path=None,
1827
+ ssl_verify=False,
1828
+ quiet=False
1829
+ )
1830
 
1831
 
1832
  if __name__ == "__main__":