import gradio as gr from ultralytics import YOLO from PIL import Image import os from huggingface_hub import hf_hub_download import numpy as np import tempfile # --- 1. SETUP & MODEL LOADING --- MODEL_REPO = "youkii-xr/hieroglyphic-detection" MODEL_FILENAME = "best.pt" os.environ["YOLO_CONFIG_DIR"] = "/tmp/Ultralytics" try: print("System: Initializing Rosetta Decoder Core...") model_path = hf_hub_download( repo_id=MODEL_REPO, filename=MODEL_FILENAME, token=os.environ.get("HF_TOKEN") ) model = YOLO(model_path) print("System: Model loaded successfully.") except Exception as e: print(f"Error: {e}") model = None # --- 2. LOGIC --- def generate_human_report(detections, counts): if not detections: return "Rosetta Decoder detects no identifiable Gardiner codes in this image." total = len(detections) sorted_counts = sorted(counts.items(), key=lambda item: item[1], reverse=True) report = f"🔓 DECODING SEQUENCE COMPLETE\n" report += f"===================================\n" report += f"Glyph Density: {total} Symbols Identified\n\n" report += "🔣 GARDINER CODE INVENTORY:\n" for code, count in sorted_counts: report += f"• Code [{code}]: {count} instance(s)\n" report += f"\n===================================\n" report += f"CONFIDENCE: High\n" report += f"STATUS: Digitized & Ready for Translation." return report def detect_hieroglyphs(image: Image.Image, conf_threshold: float = 0.25): if image is None: return None, None, "Input source required.", None if model is None: return None, {"error": "Model failed"}, "Critical Error: Weights not loaded.", None try: results = model.predict(source=image, conf=conf_threshold, iou=0.45, imgsz=640, verbose=False, device='cpu', max_det=300) annotated_array = results[0].plot() annotated_image = Image.fromarray(annotated_array[..., ::-1]) # Save for Download Button temp_dir = tempfile.gettempdir() save_path = os.path.join(temp_dir, "rosetta_decoded_result.jpg") annotated_image.save(save_path) detections = [] gardiner_counts = {} for box in results[0].boxes: if box.cls.numel() > 0: cls_id = int(box.cls[0]) if 0 <= cls_id < len(model.names): code = model.names[cls_id] conf = float(box.conf[0]) if code not in gardiner_counts: gardiner_counts[code] = 0 gardiner_counts[code] += 1 detections.append({"code": code, "confidence": round(conf, 2)}) summary_json = { "status": "success", "total_found": len(detections), "counts": gardiner_counts } text_report = generate_human_report(detections, gardiner_counts) return annotated_image, summary_json, text_report, save_path except Exception as e: return None, {"error": str(e)}, f"System Failure: {str(e)}", None # --- 3. UI STYLING (THE BLUE LAPIS THEME) --- cursor_url = "url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj4KICA8ZyBmaWxsPSJub25lIiBzdHJva2U9IiNkNGFmMzciIHN0cm9rZS13aWR0aD0iMS41Ij4KICAgIDxjaXJjbGUgY3g9IjE2IiBjeT0iMTYiIHI9IjgiIGZpbGw9InJnYmEoMjEyLCAxNzUsIDU1LCAwLjEpIi8+CiAgICA8cGF0aCBkPSZNMTYsNCBMMTYsOCIvPgogICAgPHBhdGggZD0iTTE2LDI0IEwxNiwyOCIvPgogICAgPHBhdGggZD0iTTQsMTYgTDgsMTYiLz4KICAgIDxwYXRoIGQ9Ik0yNCwxNiBMMjgsMTYiLz4KICAgIDxjaXJjbGUgY3g9IjE2IiBjeT0iMTYiIHI9IjIiIGZpbGw9IiNkNGFmMzciLz4KICA8L2c+Cjwvc3ZnPg==')" custom_css = f""" /* Import 'Cairo' font: Modern, readable, fits the region */ @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;600;700&display=swap'); @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap'); :root {{ /* --- LAPIS LAZULI NIGHT THEME --- */ --bg-gradient: radial-gradient(circle at 50% 0%, #0a0a2e 0%, #000000 100%); /* Deep Blue to Black */ --card-bg: rgba(15, 15, 35, 0.7); --text-primary: #e0e7ff; /* Soft Blue-White for comfortable reading */ --text-accent: #d4af37; /* Gold */ --border-color: #d4af37; --btn-grad: linear-gradient(135deg, #b8860b 0%, #d4af37 100%); --btn-text: #000; --glow-color: rgba(212, 175, 55, 0.4); /* Guide Box Colors */ --info-bg: rgba(212, 175, 55, 0.08); --info-border: #d4af37; }} /* --- GLOBAL SETTINGS --- */ body, .gradio-container {{ background: var(--bg-gradient) !important; font-family: 'Cairo', sans-serif !important; /* Replaced Cinzel with Cairo */ color: var(--text-primary) !important; cursor: {cursor_url} 16 16, auto !important; -webkit-font-smoothing: antialiased; /* Fixes pixelation */ -moz-osx-font-smoothing: grayscale; }} button, a, .cursor-pointer {{ cursor: {cursor_url} 16 16, pointer !important; }} /* --- CARDS --- */ .card {{ background: var(--card-bg) !important; border: 1px solid rgba(212, 175, 55, 0.2) !important; border-radius: 12px; padding: 24px; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3); backdrop-filter: blur(12px); margin-bottom: 24px; transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); }} .card:hover {{ transform: translateY(-4px); border-color: var(--border-color) !important; box-shadow: 0 10px 40px rgba(0,0,0,0.5), 0 0 20px var(--glow-color); }} /* --- BUTTONS --- */ button.primary-btn {{ background: var(--btn-grad) !important; border: 1px solid var(--border-color) !important; color: var(--btn-text) !important; font-weight: 700 !important; font-family: 'Cairo', sans-serif !important; text-transform: uppercase; letter-spacing: 1px; transition: all 0.3s ease; font-size: 16px !important; }} button.primary-btn:hover {{ transform: scale(1.02); box-shadow: 0 0 25px var(--glow-color); }} /* --- TYPOGRAPHY --- */ .card-title {{ font-family: 'Cairo', sans-serif; font-size: 18px; /* Larger for better reading */ font-weight: 700; color: var(--text-accent); text-transform: uppercase; letter-spacing: 2px; border-bottom: 1px solid rgba(212, 175, 55, 0.2); padding-bottom: 12px; margin-bottom: 18px; display: flex; align-items: center; gap: 8px; }} /* --- GOLDEN GUIDE BOXES --- */ .guide-step {{ background-color: var(--info-bg); border-left: 4px solid var(--info-border); padding: 16px; margin: 12px 0; border-radius: 0 8px 8px 0; font-family: 'Space Mono', monospace; /* Keep mono for technical instructions */ font-size: 13px; line-height: 1.6; color: #e0e7ff; }} .step-number {{ color: var(--text-accent); font-weight: bold; text-transform: uppercase; display: block; margin-bottom: 6px; font-size: 12px; letter-spacing: 1px; }} .path-highlight {{ background: rgba(212, 175, 55, 0.15); padding: 3px 8px; border-radius: 4px; color: var(--text-accent); font-weight: bold; border: 1px solid rgba(212, 175, 55, 0.3); }} /* UI CLEANUP */ .gradio-image, .gradio-json {{ background: transparent !important; border: none !important; }} .report-box textarea {{ background-color: rgba(10, 10, 20, 0.5) !important; border: 1px solid var(--border-color) !important; font-family: 'Space Mono', monospace !important; color: #a5b4fc !important; /* Lighter text for better contrast */ font-size: 14px !important; }} /* Override default gradio text color */ .block-title {{ color: var(--text-accent) !important; }} span {{ color: var(--text-primary); }} """ header_html = """

ROSETTA DECODER

AI HIEROGLYPHIC TRANSLATION SYSTEM

""" mission_html = """
📡 VISION STATEMENT

Bridging the Ancient and the Digital.
The Rosetta Decoder project utilizes advanced computer vision to identify and catalog Ancient Egyptian hieroglyphs. By automating the detection of Gardiner codes, we are creating a digital bridge that will eventually allow for instant, context-aware translation of Pharaonic wisdom, making the voices of the past accessible to everyone.

""" guide_instructions_html = """
🤖 CLAUDE DESKTOP SETUP GUIDE
STEP 1: PREPARE WORKSPACE Claude is sandboxed. It cannot see your Desktop. You must create a bridge.
1. Create this EXACT folder on your PC: C:\\Claude_Work
2. Move your hieroglyph images INSIDE this folder.
STEP 2: VERIFY PYTHON The code below assumes Python is at: C:\\Python313\\python.exe
Check your path: Open CMD and type where python.
Note: If your path is different, replace the path in the JSON code block below before copying.
STEP 3: CONFIGURE CLAUDE 1. Open Config: %APPDATA%\\Claude\\claude_desktop_config.json
2. Paste the JSON below into the "mcpServers" section.
3. IMPORTANT: Close Claude from the System Tray (near the clock) and restart it.
STEP 4: USAGE Prompt Claude: "Analyze the image at C:\\Claude_Work\\my_tablet.jpg"
""" 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" ] } } }""" # --- 4. MAIN APP ASSEMBLY --- with gr.Blocks(title="Rosetta Decoder") as demo: # Inject Styles gr.HTML(f"") # Top Section gr.HTML(header_html) gr.HTML(mission_html) # Workspace with gr.Row(): # INPUT COLUMN with gr.Column(scale=1): gr.HTML('
INPUT IMAGE
') with gr.Tabs(): with gr.TabItem("📜 Upload File"): img_upload = gr.Image(type="pil", sources=["upload", "clipboard"], label="Upload", height=320) slider_upload = gr.Slider(0.1, 1.0, 0.25, label="Scan Sensitivity") btn_upload = gr.Button("🔍 START DECODING", elem_classes="primary-btn") with gr.TabItem("🎥 Live Camera"): img_cam = gr.Image(type="pil", sources=["webcam"], label="Camera", height=320) slider_cam = gr.Slider(0.1, 1.0, 0.25, label="Scan Sensitivity") btn_cam = gr.Button("🔍 LIVE DECODE", elem_classes="primary-btn") gr.HTML('
') # OUTPUT COLUMN with gr.Column(scale=1): gr.HTML('
AI ANALYSIS RESULTS
') out_image = gr.Image(label="Decoded Result", interactive=False) # Download Button btn_download = gr.DownloadButton("💾 DOWNLOAD RESULT", visible=True) out_report = gr.Textbox(label="Analysis Log", lines=6, elem_classes="report-box", placeholder="Waiting for data stream...") with gr.Accordion("Raw Glyph Data (JSON)", open=False): out_json = gr.JSON(label="JSON Data") gr.HTML('
') # Footer Section gr.HTML(guide_instructions_html) gr.Code(value=claude_json_content, language="json", label="claude_desktop_config.json", interactive=False, lines=15) gr.HTML("
") # Event Wiring btn_upload.click( fn=detect_hieroglyphs, inputs=[img_upload, slider_upload], outputs=[out_image, out_json, out_report, btn_download] ) btn_cam.click( fn=detect_hieroglyphs, inputs=[img_cam, slider_cam], outputs=[out_image, out_json, out_report, btn_download] ) if __name__ == "__main__": demo.launch(mcp_server=True, ssr_mode=False, allowed_paths=["/tmp"])