youkii-xr commited on
Commit
6383950
Β·
verified Β·
1 Parent(s): 2c4f22a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -62
app.py CHANGED
@@ -98,7 +98,7 @@ except Exception as e:
98
  print(f"Error loading model: {e}")
99
  model = None
100
 
101
- # --- 5. CORE LOGIC ---
102
 
103
  def clean_ai_text(text):
104
  text = re.sub(r'^\d+[\.\)]\s*', '', text)
@@ -146,28 +146,61 @@ def generate_analytics_plots(detections, img_width, img_height):
146
  plt.tight_layout(pad=4.0)
147
  return fig
148
 
149
- def get_ai_translation_all_styles(keywords_list):
150
- if not GOOGLE_API_KEY:
151
- return "⚠️ Error: Google API Key not found in Secrets.", "Error"
152
- if not keywords_list:
153
- return "No hieroglyphs detected.", "No data."
154
-
155
- keywords_str = ", ".join(keywords_list)
156
- prompt = f"""
157
- You are an expert Egyptologist AI. I have detected these symbols: [{keywords_str}].
158
- Please provide 2 distinct outputs separated by "|||SEPARATOR|||".
159
- 1. A Mystical Story: Highly atmospheric, sounding like an ancient prophecy.
160
- Do NOT number this section. Use HTML tags <b> for bolding keywords and <br> for new lines.
161
- 2. An Academic Translation: Direct, linguistic, focusing on grammar. Use standard text.
162
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
  try:
164
  client = genai.Client(api_key=GOOGLE_API_KEY)
165
- response = client.models.generate_content(model="gemini-2.5-flash", contents=prompt)
166
- parts = response.text.split("|||SEPARATOR|||")
167
- if len(parts) < 2: return clean_ai_text(response.text), "Could not parse academic style."
168
- return clean_ai_text(parts[0].strip()), clean_ai_text(parts[1].strip())
169
- except Exception as e:
170
- return f"Error: {str(e)}", "Error"
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  def process_pipeline(image, conf_threshold):
173
  if image is None: return None, "", "", None, "", None, []
@@ -196,10 +229,30 @@ def process_pipeline(image, conf_threshold):
196
  crops.append((crop_img, f"{code}\n({int(conf*100)}%)"))
197
 
198
  mapped_words = [gardiner_map.get(code, f"[{code}]") for code in unique_codes]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  analytics_plot = generate_analytics_plots(detections, img_w, img_h)
200
- mystical, academic = get_ai_translation_all_styles(mapped_words)
201
  text_report = f"Total Symbols: {len(detections)}\nUnique Codes: {', '.join(unique_codes)}"
202
-
203
  formatted_mystical = f"""<div class="mystical-container"><h3>✨ THE ANCIENT WHISPER</h3><p>{mystical}</p></div>"""
204
  json_output = {"count": len(detections), "detections": detections}
205
 
@@ -208,7 +261,7 @@ def process_pipeline(image, conf_threshold):
208
  except Exception as e:
209
  return None, f"System Failure: {str(e)}", "", None, str(e), None, []
210
 
211
- # --- 6. UI STYLING & ASSETS ---
212
 
213
  cursor_url = "url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj4KICA8ZyBmaWxsPSJub25lIiBzdHJva2U9IiNkNGFmMzciIHN0cm9rZS13aWR0aD0iMS41Ij4KICAgIDxwYXRoIGQ9Ik0xNiw4IEM2LDIwIDI2LDIwIDE2LDggWiIgZmlsbD0icmdiYSgyMTIsIDE3NSwgNTUsIDAuMSkiLz4KICAgIDxjaXJjbGUgY3g9IjE2IiBjeT0iMTUiIHI9IjMiIGZpbGw9IiNkNGFmMzciLz4KICAgIDxwYXRoIGQ9Ik0xNiwyMiBMMTYsMjggTDEwLDI4Ii8+CiAgPC9nPgo8L3N2Zz4=')"
214
 
@@ -279,18 +332,18 @@ code {{ font-family: 'Space Mono', monospace; background: rgba(0,0,0,0.3); paddi
279
  button.primary-btn {{ background: var(--btn-grad) !important; border: 1px solid var(--border-color) !important; color: #000 !important; font-weight: 700 !important; font-size: 16px !important; }}
280
  .gradio-image, .gradio-json {{ background: transparent !important; border: none !important; }}
281
 
282
- /* UPDATED TOGGLE BUTTON CSS */
283
- button.toggle-btn {
284
- background: #0a0a2e !important; /* Matches dark blue background */
285
- border: 1px solid var(--border-color) !important;
286
- color: var(--text-accent) !important;
287
- padding: 5px 15px !important;
288
- font-family: 'Space Mono', monospace;
289
  box-shadow: none !important;
290
- }
291
- button.toggle-btn:hover {
292
  background: var(--info-bg) !important;
293
- }
294
  """
295
 
296
  header_html = """
@@ -326,34 +379,11 @@ guide_html = """
326
  </div>
327
  """
328
 
329
- claude_json_content = """{
330
- "mcpServers": {
331
- "gradio": {
332
- "command": "npx",
333
- "args": [
334
- "mcp-remote",
335
- "https://youkii-xr-hieroglyph-mcp-server.hf.space/gradio_api/mcp/",
336
- "--transport",
337
- "streamable-http"
338
- ]
339
- },
340
- "upload_helper": {
341
- "command": "C:\\\\Python313\\\\python.exe",
342
- "args": [
343
- "-m",
344
- "gradio",
345
- "upload-mcp",
346
- "https://youkii-xr-hieroglyph-mcp-server.hf.space/",
347
- "C:\\\\Claude_Work"
348
- ]
349
- }
350
- }
351
- }"""
352
 
353
- # JS for Gold Dust Trail
354
  trail_script = """<script>document.addEventListener('DOMContentLoaded', () => { document.addEventListener('mousemove', (e) => { if (Math.random() > 0.7) return; const dust = document.createElement('div'); dust.classList.add('gold-dust'); dust.style.left = e.clientX + 'px'; dust.style.top = e.clientY + 'px'; document.body.appendChild(dust); setTimeout(() => dust.remove(), 600); }); });</script>"""
355
 
356
- # --- 7. MAIN APP ASSEMBLY ---
357
 
358
  with gr.Blocks(title="Rosetta Decoder Ultimate") as demo:
359
  gr.HTML(f"<style>{custom_css}</style>")
@@ -397,13 +427,12 @@ with gr.Blocks(title="Rosetta Decoder Ultimate") as demo:
397
  # TAB 2: ABOUT
398
  with gr.TabItem("πŸ“œ VISION & ABOUT"): gr.HTML(mission_html)
399
 
400
- # TAB 3: SETUP (Reordered)
401
  with gr.TabItem("πŸ€– SYSTEM SETUP"):
402
  gr.HTML(guide_html)
403
- # Updated to show 25 lines so code box is expanded
404
  gr.Code(value=claude_json_content, language="json", label="claude_desktop_config.json", interactive=False, lines=25, container=True)
405
 
406
- # TAB 4: GARDINER CODES (Reordered)
407
  with gr.TabItem("π“€€ GARDINER CODES"):
408
  gr.HTML(f"""<div class="card"><div class="card-title">πŸ“œ SUPPORTED GARDINER CODES</div><div style="overflow-x: auto; max-height: 600px; overflow-y: auto;"><table class="gardiner-table"><thead><tr><th>Code</th><th>Description</th><th>Transliteration</th><th>Type</th></tr></thead><tbody>{GARDINER_TABLE_CONTENT}</tbody></table></div></div>""")
409
 
 
98
  print(f"Error loading model: {e}")
99
  model = None
100
 
101
+ # --- 5. CORE LOGIC (Helpers) ---
102
 
103
  def clean_ai_text(text):
104
  text = re.sub(r'^\d+[\.\)]\s*', '', text)
 
146
  plt.tight_layout(pad=4.0)
147
  return fig
148
 
149
+ # --- 6. MCP EXPOSED FUNCTIONS ---
150
+
151
+ @gr.tool
152
+ def detect_hieroglyphs_mcp(image_path: str, conf_threshold: float = 0.25):
153
+ """Detects hieroglyphs in an image file. Returns JSON data."""
154
+ if model is None: return {"error": "Model not loaded"}
155
+ try:
156
+ image = Image.open(image_path)
157
+ img_w, img_h = image.size
158
+ results = model.predict(source=image, conf=conf_threshold, iou=0.45, imgsz=640, verbose=False, device='cpu', max_det=300)
159
+ detections = []
160
+ unique_codes = set()
161
+ for box in results[0].boxes:
162
+ if box.cls.numel() > 0:
163
+ cls_id = int(box.cls[0])
164
+ if 0 <= cls_id < len(model.names):
165
+ code = model.names[cls_id]
166
+ conf = float(box.conf[0])
167
+ unique_codes.add(code)
168
+ xyxy = box.xyxy[0].tolist()
169
+ meaning = gardiner_map.get(code, "Unknown")
170
+ detections.append({"code": code, "meaning": meaning, "confidence": round(conf, 2), "box": xyxy})
171
+ return {"status": "success", "image_size": [img_w, img_h], "total_detected": len(detections), "unique_codes": list(unique_codes), "detections": detections}
172
+ except Exception as e: return {"error": str(e)}
173
+
174
+ @gr.tool
175
+ def translate_hieroglyphs_mcp(keywords: list[str], style: str = "Academic Literal"):
176
+ """Translates a list of meanings using Gemini."""
177
+ if not GOOGLE_API_KEY: return "Error: Google API Key not configured."
178
+ keywords_str = ", ".join(keywords)
179
+ prompts = {
180
+ "Mystical Story": f"Create a coherent, mystical, and atmospheric short story using these ancient Egyptian concepts: [{keywords_str}]. Make it sound like a prophecy.",
181
+ "Academic Literal": f"Provide a direct, grammatical translation of these concepts: [{keywords_str}]. Focus on linguistic structure and sentence formation used in Egyptology.",
182
+ "Modern Interpretation": f"Translate the essence of these symbols: [{keywords_str}] into a modern, relatable piece of advice or horoscopic reading."
183
+ }
184
+ prompt = prompts.get(style, prompts["Academic Literal"])
185
  try:
186
  client = genai.Client(api_key=GOOGLE_API_KEY)
187
+ response = client.models.generate_content(model="gemini-2.5-flash", contents=f"You are an expert Egyptologist AI. {prompt}")
188
+ return response.text
189
+ except Exception as e: return f"Translation Error: {str(e)}"
190
+
191
+ @gr.tool
192
+ def get_gardiner_info_mcp(code: str):
193
+ """Retrieves detailed info about a specific code."""
194
+ info = gardiner_data.get(code)
195
+ if info: return info
196
+ return {"error": f"Code {code} not found in database."}
197
+
198
+ @gr.tool
199
+ def get_supported_codes_mcp():
200
+ """Returns list of supported codes."""
201
+ return list(gardiner_data.keys())
202
+
203
+ # --- 7. UI PROCESSING PIPELINE ---
204
 
205
  def process_pipeline(image, conf_threshold):
206
  if image is None: return None, "", "", None, "", None, []
 
229
  crops.append((crop_img, f"{code}\n({int(conf*100)}%)"))
230
 
231
  mapped_words = [gardiner_map.get(code, f"[{code}]") for code in unique_codes]
232
+
233
+ # Translation
234
+ if not GOOGLE_API_KEY:
235
+ mystical, academic = "API Key Missing", "API Key Missing"
236
+ else:
237
+ keywords_str = ", ".join(mapped_words)
238
+ prompt = f"""
239
+ You are an expert Egyptologist AI. I have detected these symbols: [{keywords_str}].
240
+ Please provide 2 distinct outputs separated by "|||SEPARATOR|||".
241
+ 1. A Mystical Story: Highly atmospheric, sounding like an ancient prophecy.
242
+ Do NOT number this section. Use HTML tags <b> for bolding keywords and <br> for new lines.
243
+ 2. An Academic Translation: Direct, linguistic, focusing on grammar. Use standard text.
244
+ """
245
+ try:
246
+ client = genai.Client(api_key=GOOGLE_API_KEY)
247
+ response = client.models.generate_content(model="gemini-2.5-flash", contents=prompt)
248
+ parts = response.text.split("|||SEPARATOR|||")
249
+ if len(parts) < 2: mystical, academic = clean_ai_text(response.text), "Could not parse academic style."
250
+ else: mystical, academic = clean_ai_text(parts[0].strip()), clean_ai_text(parts[1].strip())
251
+ except Exception as e:
252
+ mystical, academic = f"Error: {str(e)}", f"Error: {str(e)}"
253
+
254
  analytics_plot = generate_analytics_plots(detections, img_w, img_h)
 
255
  text_report = f"Total Symbols: {len(detections)}\nUnique Codes: {', '.join(unique_codes)}"
 
256
  formatted_mystical = f"""<div class="mystical-container"><h3>✨ THE ANCIENT WHISPER</h3><p>{mystical}</p></div>"""
257
  json_output = {"count": len(detections), "detections": detections}
258
 
 
261
  except Exception as e:
262
  return None, f"System Failure: {str(e)}", "", None, str(e), None, []
263
 
264
+ # --- 8. UI STYLING & ASSETS ---
265
 
266
  cursor_url = "url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj4KICA8ZyBmaWxsPSJub25lIiBzdHJva2U9IiNkNGFmMzciIHN0cm9rZS13aWR0aD0iMS41Ij4KICAgIDxwYXRoIGQ9Ik0xNiw4IEM2LDIwIDI2LDIwIDE2LDggWiIgZmlsbD0icmdiYSgyMTIsIDE3NSwgNTUsIDAuMSkiLz4KICAgIDxjaXJjbGUgY3g9IjE2IiBjeT0iMTUiIHI9IjMiIGZpbGw9IiNkNGFmMzciLz4KICAgIDxwYXRoIGQ9Ik0xNiwyMiBMMTYsMjggTDEwLDI4Ii8+CiAgPC9nPgo8L3N2Zz4=')"
267
 
 
332
  button.primary-btn {{ background: var(--btn-grad) !important; border: 1px solid var(--border-color) !important; color: #000 !important; font-weight: 700 !important; font-size: 16px !important; }}
333
  .gradio-image, .gradio-json {{ background: transparent !important; border: none !important; }}
334
 
335
+ /* FIXED TOGGLE BUTTON */
336
+ button.toggle-btn {{
337
+ background: #0a0a2e !important;
338
+ border: 1px solid var(--border-color) !important;
339
+ color: var(--text-accent) !important;
340
+ padding: 5px 15px !important;
341
+ font-family: 'Space Mono', monospace;
342
  box-shadow: none !important;
343
+ }}
344
+ button.toggle-btn:hover {{
345
  background: var(--info-bg) !important;
346
+ }}
347
  """
348
 
349
  header_html = """
 
379
  </div>
380
  """
381
 
382
+ claude_json_content = """{ "mcpServers": { "gradio": { "command": "npx", "args": [ "mcp-remote", "https://youkii-xr-hieroglyph-mcp-server.hf.space/gradio_api/mcp/", "--transport", "streamable-http" ] }, "upload_helper": { "command": "C:\\\\Python313\\\\python.exe", "args": [ "-m", "gradio", "upload-mcp", "https://youkii-xr-hieroglyph-mcp-server.hf.space/", "C:\\\\Claude_Work" ] } } }"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
 
384
  trail_script = """<script>document.addEventListener('DOMContentLoaded', () => { document.addEventListener('mousemove', (e) => { if (Math.random() > 0.7) return; const dust = document.createElement('div'); dust.classList.add('gold-dust'); dust.style.left = e.clientX + 'px'; dust.style.top = e.clientY + 'px'; document.body.appendChild(dust); setTimeout(() => dust.remove(), 600); }); });</script>"""
385
 
386
+ # --- 8. MAIN APP ASSEMBLY ---
387
 
388
  with gr.Blocks(title="Rosetta Decoder Ultimate") as demo:
389
  gr.HTML(f"<style>{custom_css}</style>")
 
427
  # TAB 2: ABOUT
428
  with gr.TabItem("πŸ“œ VISION & ABOUT"): gr.HTML(mission_html)
429
 
430
+ # TAB 3: SETUP
431
  with gr.TabItem("πŸ€– SYSTEM SETUP"):
432
  gr.HTML(guide_html)
 
433
  gr.Code(value=claude_json_content, language="json", label="claude_desktop_config.json", interactive=False, lines=25, container=True)
434
 
435
+ # TAB 4: GARDINER CODES
436
  with gr.TabItem("π“€€ GARDINER CODES"):
437
  gr.HTML(f"""<div class="card"><div class="card-title">πŸ“œ SUPPORTED GARDINER CODES</div><div style="overflow-x: auto; max-height: 600px; overflow-y: auto;"><table class="gardiner-table"><thead><tr><th>Code</th><th>Description</th><th>Transliteration</th><th>Type</th></tr></thead><tbody>{GARDINER_TABLE_CONTENT}</tbody></table></div></div>""")
438