File size: 16,327 Bytes
af7647d
 
 
 
 
 
3d7bbf9
af7647d
200b1a9
db4e1b2
af7647d
200b1a9
 
af7647d
3d7bbf9
af7647d
 
 
db4e1b2
af7647d
 
200b1a9
af7647d
da8eae7
af7647d
 
74b222d
eb337ce
 
3d7bbf9
eb337ce
 
 
 
3d7bbf9
 
 
 
eb337ce
3d7bbf9
 
 
 
eb337ce
 
af7647d
eb337ce
3d7bbf9
eb337ce
3d7bbf9
af7647d
 
da8eae7
af7647d
 
 
d17f949
3d7bbf9
 
 
 
af7647d
 
 
 
 
 
 
 
 
 
da8eae7
af7647d
eb337ce
af7647d
db4e1b2
af7647d
 
eb337ce
 
3d7bbf9
af7647d
eb337ce
3d7bbf9
f6fedbb
c045ef8
004bb8f
c045ef8
 
004bb8f
 
74b222d
 
f6fedbb
004bb8f
c045ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d17f949
 
 
 
 
 
 
 
 
 
 
 
c045ef8
004bb8f
 
d17f949
004bb8f
c045ef8
d17f949
c045ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
004bb8f
 
c045ef8
 
 
004bb8f
 
74b222d
004bb8f
 
d17f949
3d7bbf9
 
d17f949
3d7bbf9
 
 
004bb8f
 
 
3d7bbf9
004bb8f
d17f949
004bb8f
da8eae7
de27937
004bb8f
3d7bbf9
 
 
 
74b222d
da8eae7
74b222d
004bb8f
74b222d
004bb8f
 
3d7bbf9
74b222d
3d7bbf9
 
c045ef8
d17f949
 
 
 
 
c045ef8
d17f949
 
 
 
 
 
3d7bbf9
 
 
 
 
 
d17f949
004bb8f
3d7bbf9
c045ef8
3d7bbf9
c045ef8
3d7bbf9
 
 
 
 
 
74b222d
004bb8f
3d7bbf9
d17f949
74b222d
004bb8f
de27937
3d7bbf9
d17f949
004bb8f
eb337ce
d17f949
de27937
004bb8f
d17f949
004bb8f
3d7bbf9
d17f949
74b222d
004bb8f
74b222d
 
f6fedbb
 
da8eae7
d17f949
74b222d
 
3d7bbf9
 
 
 
74b222d
3d7bbf9
 
d17f949
 
3d7bbf9
da8eae7
 
 
 
eb337ce
da8eae7
3d7bbf9
d17f949
3d7bbf9
 
 
 
eb337ce
 
 
 
004bb8f
3d7bbf9
 
eb337ce
3d7bbf9
 
 
 
 
004bb8f
 
3d7bbf9
 
 
 
 
da8eae7
eb337ce
3d7bbf9
 
 
 
 
 
 
 
 
 
eb337ce
004bb8f
 
 
eb337ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
004bb8f
f6fedbb
3d7bbf9
c045ef8
 
 
d17f949
c045ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d17f949
 
 
c045ef8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d7bbf9
c045ef8
200b1a9
c045ef8
004bb8f
c045ef8
d17f949
 
 
 
c045ef8
d17f949
 
eb337ce
da8eae7
004bb8f
f6fedbb
 
3d7bbf9
eb337ce
3d7bbf9
 
 
 
eb337ce
3d7bbf9
 
 
 
eb337ce
 
da8eae7
3d7bbf9
 
 
 
eb337ce
 
 
 
d17f949
004bb8f
 
 
f6fedbb
c045ef8
 
 
3d7bbf9
d17f949
 
f6fedbb
af7647d
da8eae7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
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
        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 & ANIMATION ---

# SVG Cursor: Eye of Horus
cursor_url = "url('data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIzMiIgaGVpZ2h0PSIzMiIgdmlld0JveD0iMCAwIDMyIDMyIj4KICA8ZyBmaWxsPSJub25lIiBzdHJva2U9IiNkNGFmMzciIHN0cm9rZS13aWR0aD0iMS41Ij4KICAgIDxwYXRoIGQ9Ik0xNiw4IEM2LDIwIDI2LDIwIDE2LDggWiIgZmlsbD0icmdiYSgyMTIsIDE3NSwgNTUsIDAuMSkiLz4KICAgIDxjaXJjbGUgY3g9IjE2IiBjeT0iMTUiIHI9IjMiIGZpbGw9IiNkNGFmMzciLz4KICAgIDxwYXRoIGQ9Ik0xNiwyMiBMMTYsMjggTDEwLDI4Ii8+CiAgPC9nPgo8L3N2Zz4=')"

custom_css = f"""
@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 {{
    /* --- DEFAULT: NIGHT MODE (Since your system is dark) --- */
    --bg-gradient: radial-gradient(circle at 50% 0%, #0a0a2e 0%, #000000 100%);
    --card-bg: rgba(15, 15, 35, 0.7);
    --text-primary: #e0e7ff; 
    --text-accent: #d4af37;  /* Gold */
    --border-color: #d4af37;
    --btn-grad: linear-gradient(135deg, #b8860b 0%, #d4af37 100%);
    --btn-text: #000;
    --info-bg: rgba(212, 175, 55, 0.08); 
    --info-border: #d4af37;
    --glow-color: rgba(212, 175, 55, 0.4);
}}

/* --- LIGHT MODE OVERRIDE CLASS --- */
body.light-mode {{
    --bg-gradient: linear-gradient(135deg, #f0e6d2 0%, #e6dcc3 100%);
    --card-bg: rgba(255, 255, 255, 0.6);
    --text-primary: #3d342b;
    --text-accent: #8b4513; 
    --border-color: #8b4513;
    --btn-grad: linear-gradient(135deg, #cd853f 0%, #8b4513 100%);
    --btn-text: #fff;
    --info-bg: rgba(139, 69, 19, 0.05); 
    --info-border: #8b4513;
    --glow-color: rgba(139, 69, 19, 0.3);
}}

/* --- GLOBAL SETTINGS --- */
body, .gradio-container {{
    background: var(--bg-gradient) !important;
    font-family: 'Cairo', sans-serif !important;
    color: var(--text-primary) !important;
    cursor: {cursor_url} 16 16, auto !important; 
    -webkit-font-smoothing: antialiased;
    transition: background 0.5s ease; /* Smooth Theme Switch */
}}

button, a, .cursor-pointer {{
    cursor: {cursor_url} 16 16, pointer !important;
}}

/* --- CURSOR TRAIL PARTICLES --- */
.gold-dust {{
    position: fixed;
    width: 6px;
    height: 6px;
    background: var(--text-accent);
    border-radius: 50%;
    pointer-events: none;
    z-index: 9999;
    animation: fadeDust 0.6s linear forwards;
    box-shadow: 0 0 5px var(--text-accent);
}}

@keyframes fadeDust {{
    0% {{ opacity: 1; transform: scale(1); }}
    100% {{ opacity: 0; transform: scale(0); }}
}}

/* --- CARDS --- */
.card {{
    background: var(--card-bg) !important;
    border: 1px solid rgba(128, 128, 128, 0.2) !important;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    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.2), 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);
}}

/* Toggle Button */
button.toggle-btn {{
    background: transparent !important;
    border: 1px solid var(--border-color) !important;
    color: var(--text-accent) !important;
    padding: 5px 15px !important;
    font-family: 'Space Mono', monospace;
}}
button.toggle-btn:hover {{
    background: var(--info-bg) !important;
}}

/* --- 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;
    font-size: 13px;
    line-height: 1.6;
    color: var(--text-primary);
}}

.step-number {{
    color: var(--text-accent);
    font-weight: bold;
    text-transform: uppercase;
    display: block;
    margin-bottom: 6px;
    font-size: 12px;
}}
.path-highlight {{
    background: rgba(128,128,128,0.2);
    padding: 3px 8px;
    border-radius: 4px;
    color: var(--text-accent);
    font-weight: bold;
    border: 1px solid var(--border-color);
}}

/* CLEANUP */
.gradio-image, .gradio-json {{ background: transparent !important; border: none !important; }}
.report-box textarea {{
    background-color: rgba(0,0,0,0.2) !important;
    border: 1px solid var(--border-color) !important;
    font-family: 'Space Mono', monospace !important;
    color: var(--text-primary) !important;
    font-size: 14px !important;
}}
.block-title {{ color: var(--text-accent) !important; }}
span {{ color: var(--text-primary); }}
"""

header_html = """
<div style="padding: 20px 0; border-bottom: 1px solid rgba(128,128,128,0.2); margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
    <div style="display: flex; align-items: center; gap: 20px;">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#d4af37" stroke-width="2">
            <rect x="3" y="3" width="18" height="18" rx="2" />
            <path d="M7 7h10" />
            <path d="M7 12h10" />
            <path d="M7 17h10" />
            <circle cx="12" cy="12" r="3" stroke="#d4af37" fill="none"/>
        </svg>
        <div>
            <h1 style="margin: 0; font-size: 36px; font-weight: 700; color: var(--text-primary); text-shadow: 0 0 10px rgba(212, 175, 55, 0.3);">ROSETTA DECODER</h1>
            <p style="margin: 0; font-size: 14px; color: var(--text-accent); letter-spacing: 3px; font-weight: 600;">AI HIEROGLYPHIC TRANSLATION SYSTEM</p>
        </div>
    </div>
</div>
"""

mission_html = """
<div class="card">
    <div class="card-title">πŸ“‘ VISION STATEMENT</div>
    <p style="opacity: 0.9; font-size: 16px; line-height: 1.8; color: var(--text-primary);">
        <b>Bridging the Ancient and the Digital.</b><br>
        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.
    </p>
</div>
"""

guide_instructions_html = """
<div class="card" style="border-color: var(--info-border) !important;">
    <div class="card-title" style="color: var(--info-border) !important;">πŸ€– CLAUDE DESKTOP SETUP GUIDE</div>
    
    <div class="guide-step">
        <span class="step-number">STEP 1: PREPARE WORKSPACE</span>
        Claude is sandboxed. It cannot see your Desktop. You must create a bridge.<br>
        1. Create this EXACT folder on your PC: <span class="path-highlight">C:\\Claude_Work</span><br>
        2. Move your hieroglyph images <b>INSIDE</b> this folder.
    </div>

    <div class="guide-step">
        <span class="step-number">STEP 2: VERIFY PYTHON</span>
        The code below assumes Python is at: <code>C:\\Python313\\python.exe</code><br>
        <b>Check your path:</b> Open CMD and type <code>where python</code>.<br>
        <i>Note: If your path is different, replace the path in the JSON code block below before copying.</i>
    </div>

    <div class="guide-step">
        <span class="step-number">STEP 3: CONFIGURE CLAUDE</span>
        1. Open Config: <code>%APPDATA%\\Claude\\claude_desktop_config.json</code><br>
        2. Paste the JSON below into the <code>"mcpServers"</code> section.<br>
        3. <b>IMPORTANT:</b> Close Claude from the System Tray (near the clock) and restart it.
    </div>

    <div class="guide-step">
        <span class="step-number">STEP 4: USAGE</span>
        Prompt Claude: <i>"Analyze the image at C:\\Claude_Work\\my_tablet.jpg"</i>
    </div>
"""

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 ---

# JS: Toggle Theme AND Add Mouse Trail
js_code = """
() => {
    // 1. Toggle Logic
    const toggleTheme = () => {
        document.body.classList.toggle('light-mode');
        const container = document.querySelector('.gradio-container');
        if (container) container.classList.toggle('light-mode');
    }

    // 2. Mouse Trail Logic
    const addTrail = () => {
        document.addEventListener('mousemove', function(e) {
            // Rate limit to prevent too many elements
            if (Math.random() > 0.5) 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);
            
            // Remove after animation
            setTimeout(() => {
                dust.remove();
            }, 600);
        });
    }

    // Initialize
    addTrail();
    
    // Return the toggle function for the button click
    return toggleTheme;
}
"""

# We need to run the trail logic on load, but Gradio JS usually runs on events.
# We will attach the trail logic to the body load via an HTML script injection.
trail_script = """
<script>
document.addEventListener('DOMContentLoaded', () => {
    document.addEventListener('mousemove', (e) => {
        if (Math.random() > 0.7) return; // limit density
        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>
"""

with gr.Blocks(title="Rosetta Decoder") as demo:
    # Inject CSS & Trail Script
    gr.HTML(f"<style>{custom_css}</style>")
    gr.HTML(trail_script)
    
    # Top Section
    with gr.Row(elem_classes="header-row"):
        with gr.Column(scale=4):
            gr.HTML(header_html)
        with gr.Column(scale=1):
            # JS-based Toggle
            btn_toggle = gr.Button("πŸŒ— Day / Night", elem_classes="toggle-btn")

    gr.HTML(mission_html)
    
    # Workspace
    with gr.Row():
        with gr.Column(scale=1):
            gr.HTML('<div class="card"><div class="card-title">INPUT IMAGE</div>')
            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('</div>')

        with gr.Column(scale=1):
            gr.HTML('<div class="card"><div class="card-title">AI ANALYSIS RESULTS</div>')
            out_image = gr.Image(label="Decoded Result", interactive=False)
            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('</div>')

    # Footer
    gr.HTML(guide_instructions_html)
    gr.Code(value=claude_json_content, language="json", label="claude_desktop_config.json", interactive=False, lines=15)
    gr.HTML("</div>")

    # Wiring
    # The toggle button triggers a JS function that adds the 'light-mode' class
    btn_toggle.click(None, None, None, js="() => { document.body.classList.toggle('light-mode'); document.querySelector('.gradio-container').classList.toggle('light-mode'); }")
    
    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"])