File size: 38,944 Bytes
32af06c
4c39362
 
32af06c
 
 
 
 
 
4c39362
32af06c
 
4002518
 
 
 
 
 
 
 
32af06c
 
 
 
ef6c101
a0442e9
ef6c101
 
 
 
 
 
 
 
 
ac94664
4c39362
4fc3dbd
32af06c
4c39362
32af06c
 
 
 
 
 
 
 
 
4c39362
f863884
 
 
 
 
 
 
4c39362
 
 
f863884
 
 
 
 
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fc3dbd
4c39362
 
 
 
 
 
 
 
 
4fc3dbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c39362
 
4fc3dbd
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32af06c
 
 
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32af06c
4c39362
32af06c
f85fde3
 
4f3337a
 
ef6c101
 
 
 
 
 
 
 
 
 
 
 
f85fde3
4c39362
ef6c101
ff6b185
4c39362
ef6c101
 
 
 
 
 
f85fde3
 
4c39362
 
ef6c101
 
 
 
 
 
4c39362
 
 
f85fde3
 
 
 
a0442e9
f85fde3
 
a0442e9
f85fde3
 
a0442e9
 
 
 
f85fde3
a0442e9
f85fde3
a0442e9
 
54aecf9
a0442e9
f85fde3
a0442e9
f85fde3
 
 
8bfde3b
4c39362
 
8bfde3b
 
 
4c39362
 
ac94664
4c39362
 
 
 
 
ac94664
4c39362
 
8bfde3b
 
4c39362
 
 
8bfde3b
4c39362
8bfde3b
4c39362
ac94664
4c39362
 
 
 
 
 
 
ac94664
4c39362
 
 
8bfde3b
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bfde3b
4c39362
 
 
 
 
 
8bfde3b
4c39362
 
 
8bfde3b
 
4c39362
 
 
 
 
 
 
 
8bfde3b
 
4c39362
 
 
 
8bfde3b
4c39362
8bfde3b
4c39362
 
 
 
8bfde3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c39362
 
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
4c39362
 
 
 
8bfde3b
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c39362
 
 
 
8bfde3b
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
4c39362
 
 
8bfde3b
 
4c39362
 
 
8bfde3b
 
 
4c39362
 
 
8bfde3b
 
 
4c39362
 
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
 
 
 
 
 
 
4c39362
 
 
8bfde3b
4c39362
 
 
8bfde3b
 
4c39362
 
 
8bfde3b
 
4c39362
 
 
 
8bfde3b
 
 
 
 
4c39362
32af06c
 
4c39362
 
 
 
 
 
32af06c
4c39362
 
 
 
 
 
 
ef6c101
 
 
4c39362
 
 
 
 
 
32af06c
4c39362
32af06c
 
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bfde3b
 
 
 
4c39362
 
 
 
 
4fc3dbd
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fc3dbd
7988087
4c39362
a0442e9
4c39362
 
 
 
a0442e9
4c39362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a0442e9
4c39362
 
 
f85fde3
4c39362
 
 
7988087
 
4c39362
 
 
 
 
 
 
 
7988087
4c39362
 
 
 
 
 
 
 
 
 
7988087
4c39362
 
 
 
 
 
 
 
 
ef6c101
4c39362
ef6c101
 
 
 
4c39362
 
 
 
 
 
 
 
ef6c101
4c39362
 
 
 
 
32af06c
4c39362
 
 
32af06c
 
 
 
7988087
 
 
 
 
 
 
 
 
 
 
 
 
 
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
"""
Sincc.on: Zamonaviy Hugging Face Spaces Boshqaruv Paneli, Interaktiv Veb Solver va Telegram Bot Launcher.
24/7 rejimida fonda Telegram botni ishlatadi, to'liq vizual EdTech interfeysini taqdim etadi.
"""

import sys
import pathlib
import threading
import os
import html
import gradio as gr

try:
    import spaces
    @spaces.GPU
    def _gpu_worker():
        return True
except Exception:
    pass

PROJECT_ROOT = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(PROJECT_ROOT))

from bot import run_bot
from app.db import get_statistics, get_cloud_sync_status
from app.pipeline import solve_problem, get_agent_configs, get_groq_key
from app.key_pool import (
    get_groq_keys,
    get_openrouter_keys,
    get_mistral_keys,
    get_sambanova_keys,
    get_cohere_keys,
    get_cloudflare_config,
    key_pool,
)
from app.geometry_drawer import try_draw_geometry
from app.vision import extract_problem_from_image
from app.pdf_generator import generate_math_pdf

# 1. Telegram botni orqa fonda 24/7 ishga tushirish
def start_bot_background():
    try:
        run_bot()
    except Exception as e:
        print(f"[Launcher] Telegram bot xatosi: {e}")

bot_thread = threading.Thread(target=start_bot_background, daemon=True)
bot_thread.start()

# 2. Self-Ping / Keep-Alive jarayoni: Space uyquga ketmasligi uchun har 6 daqiqada murojaat qiladi
def keep_alive_worker():
    import time
    import httpx
    public_url = "https://shaptoli-sinccon.hf.space"
    time.sleep(30)
    while True:
        try:
            httpx.get(public_url, timeout=20.0, follow_redirects=True)
        except Exception:
            pass
        time.sleep(360)

ping_thread = threading.Thread(target=keep_alive_worker, daemon=True)
ping_thread.start()

# 3. Yechimni zamonaviy HTML kartochkalari ko'rinishida formatlash
def render_solution_html(res: dict, ocr_text: str = "") -> str:
    ans_type = res.get("type", "solve")

    ocr_banner = ""
    if ocr_text:
        ocr_banner = f"""
        <div class="sincc-ocr-badge">
            <span class="badge-icon">๐Ÿ“ธ</span>
            <div>
                <strong>Rasmdan o'qilgan masala sharti:</strong><br>
                <span class="ocr-text">{html.escape(ocr_text)}</span>
            </div>
        </div>
        """

    if ans_type == "chat":
        reply = res.get("reply", "") or res.get("final_answer", "")
        return f"""
        {ocr_banner}
        <div class="sincc-card chat-card">
            <div class="card-header"><span class="header-icon">๐Ÿ’ฌ</span> <strong>AI Ustoz Javobi</strong></div>
            <div class="card-body">{html.escape(reply)}</div>
        </div>
        """

    if ans_type in ("theory", "incomplete"):
        reply = res.get("reply", "")
        if not reply:
            reply = "\n".join(res.get("steps", [])) or res.get("final_answer", "")
        return f"""
        {ocr_banner}
        <div class="sincc-card theory-card">
            <div class="card-header"><span class="header-icon">๐Ÿ“–</span> <strong>Nazariy Tushuncha & Formula</strong></div>
            <div class="card-body">{html.escape(reply)}</div>
        </div>
        """

    # ans_type == "solve"
    intro = res.get("intro", "")
    intro_html = f"<div class='sincc-intro'>๐Ÿง‘โ€๐Ÿซ {html.escape(intro)}</div>" if intro else ""

    steps_html = []
    for idx, s in enumerate(res.get("steps", []), 1):
        s_str = str(s).strip()
        steps_html.append(f"""
        <div class="sincc-step">
            <div class="step-num">{idx}</div>
            <div class="step-text">{html.escape(s_str)}</div>
        </div>
        """)
    steps_block = "\n".join(steps_html)

    formulas_html = ""
    if res.get("formulas_used"):
        f_chips = "".join(f"<span class='formula-chip'>๐Ÿ“ {html.escape(f)}</span>" for f in res["formulas_used"] if f)
        if f_chips:
            formulas_html = f"""
            <div class="sincc-card formula-card">
                <div class="card-header"><strong>Qo'llanilgan Qoidalar va Teoremalar:</strong></div>
                <div class="formula-chips">{f_chips}</div>
            </div>
            """

    final_ans = str(res.get("final_answer", "")).strip()
    verified = res.get("verified", False)
    badge_text = "โœ“ SymPy Sandbox: 100% Aniq Tasdiqlangan" if verified else "โ„น๏ธ Matematik Mantiq Asosida Hisoblandi"
    badge_class = "verified-badge" if verified else "unverified-badge"

    answer_html = ""
    if final_ans:
        answer_html = f"""
        <div class="sincc-card answer-card">
            <div class="answer-title">๐ŸŽฏ YAKUNIY ANIQ JAVOB</div>
            <div class="answer-value">{html.escape(final_ans)}</div>
            <div class="{badge_class}">{badge_text}</div>
        </div>
        """

    tip = res.get("explanation_tip", "")
    tip_html = f"<div class='sincc-tip'>๐Ÿ’ก <strong>Ustoz Layfxaki:</strong> {html.escape(tip)}</div>" if tip else ""

    return f"""
    <div class="sincc-solution">
        {ocr_banner}
        {intro_html}
        <div class="sincc-steps-wrapper">
            <h4 class="steps-heading">๐Ÿชœ Bosqichma-bosqich Yechilish:</h4>
            {steps_block}
        </div>
        {formulas_html}
        {answer_html}
        {tip_html}
    </div>
    """

# 4. Asosiy Masala Yechish Funksiyasi (Matn + Rasm OCR)
def solve_problem_web(problem_text: str, image_file):
    text = (problem_text or "").strip()
    extracted_ocr = ""

    # Agar rasm yuklangan bo'lsa -> Vision OCR
    if image_file:
        try:
            with open(image_file, "rb") as f:
                img_bytes = f.read()
            extracted_ocr = extract_problem_from_image(img_bytes, user_caption=text)
            if extracted_ocr:
                text = extracted_ocr
        except Exception as e:
            print(f"[Web Vision OCR xatosi]: {e}")

    if not text:
        return (
            "<div class='sincc-card warning-card'>โš ๏ธ Iltimos, masala shartini matn ko'rinishida yozing yoki uning rasmini yuklang.</div>",
            gr.update(value=None, visible=False),
            gr.update(value=None, visible=False),
            ""
        )

    try:
        res = solve_problem(text)
        html_output = render_solution_html(res, ocr_text=extracted_ocr)

        # Geometrik chizma tekshiruvi
        img_path = try_draw_geometry(text)
        has_img = bool(img_path and os.path.exists(img_path))

        # PDF Konspekt generatsiyasi
        pdf_path = None
        try:
            if res.get("type") == "solve" and (res.get("steps") or res.get("final_answer")):
                pdf_path = generate_math_pdf(text, res, img_path if has_img else None)
        except Exception as e_pdf:
            print(f"[Web PDF error]: {e_pdf}")

        has_pdf = bool(pdf_path and os.path.exists(pdf_path))

        return (
            html_output,
            gr.update(value=img_path if has_img else None, visible=has_img),
            gr.update(value=pdf_path if has_pdf else None, visible=has_pdf),
            text
        )
    except Exception as e:
        err_html = f"<div class='sincc-card error-card'>โŒ Yechish jarayonida kutilmagan xatolik: {html.escape(str(e))}</div>"
        return err_html, gr.update(value=None, visible=False), gr.update(value=None, visible=False), text

# 5. Geometriya Laboratoriyasi Funksiyasi
def generate_geometry_lab(shape_type: str, p1: float, p2: float, p3: float):
    p1 = float(p1 or 0)
    p2 = float(p2 or 0)
    p3 = float(p3 or 0)

    query_str = ""
    info_md = ""

    if "To'g'ri burchakli uchburchak" in shape_type:
        a = p1 if p1 > 0 else 6
        b = p2 if p2 > 0 else 8
        c = (a**2 + b**2)**0.5
        query_str = f"katetlari {int(a) if a.is_integer() else a} va {int(b) if b.is_integer() else b}"
        info_md = f"**Katet a:** {a} | **Katet b:** {b} | **Gipotenuza c:** {round(c, 2)}\n\n**Yuza S:** {round(0.5*a*b, 2)} | **Perimetr P:** {round(a+b+c, 2)}"

    elif "Aylana" in shape_type:
        r = p1 if p1 > 0 else 5
        import math
        query_str = f"radius {int(r) if r.is_integer() else r} aylana"
        info_md = f"**Radius R:** {r} | **Diametr D:** {2*r}\n\n**Yuza S:** {round(math.pi * r**2, 2)} | **Uzunlik L:** {round(2 * math.pi * r, 2)}"

    elif "To'g'ri to'rtburchak" in shape_type:
        w = p1 if p1 > 0 else 8
        h = p2 if p2 > 0 else 5
        query_str = f"to'g'ri to'rtburchak {int(w) if w.is_integer() else w} va {int(h) if h.is_integer() else h}"
        info_md = f"**Bo'yi a:** {w} | **Eni b:** {h}\n\n**Yuza S:** {w*h} | **Perimetr P:** {2*(w+h)}"

    elif "Kvadrat" in shape_type:
        a = p1 if p1 > 0 else 6
        query_str = f"kvadrat {int(a) if a.is_integer() else a}"
        info_md = f"**Tomon a:** {a}\n\n**Yuza S:** {a**2} | **Perimetr P:** {4*a} | **Diagonal d:** {round(a*(2**0.5), 2)}"

    elif "Teng tomonli uchburchak" in shape_type:
        a = p1 if p1 > 0 else 6
        h = a * (3**0.5) / 2.0
        query_str = f"teng tomonli uchburchak {int(a) if a.is_integer() else a}"
        info_md = f"**Tomon a:** {a} | **Balandlik h:** {round(h, 2)}\n\n**Yuza S:** {round((3**0.5 / 4.0)*a**2, 2)} | **Perimetr P:** {3*a}"

    elif "Teng yonli uchburchak" in shape_type:
        b = p1 if p1 > 0 else 8 # Asos
        a = p2 if p2 > 0 else 5 # Yon tomon
        query_str = f"teng yonli uchburchak asosi {int(b) if b.is_integer() else b} yon tomoni {int(a) if a.is_integer() else a}"
        h = (a**2 - (b/2.0)**2)**0.5 if a > b/2.0 else 0
        info_md = f"**Asos b:** {b} | **Yon tomon a:** {a} | **Balandlik h:** {round(h, 2)}\n\n**Yuza S:** {round(0.5*b*h, 2)} | **Perimetr P:** {round(b+2*a, 2)}"

    elif "Trapetsiya" in shape_type:
        b1 = p1 if p1 > 0 else 6
        b2 = p2 if p2 > 0 else 10
        h = p3 if p3 > 0 else 4
        query_str = f"trapetsiya {int(b1) if b1.is_integer() else b1} {int(b2) if b2.is_integer() else b2} balandlik {int(h) if h.is_integer() else h}"
        info_md = f"**Kichik asos:** {min(b1, b2)} | **Katta asos:** {max(b1, b2)} | **Balandlik h:** {h}\n\n**Yuza S:** {round(0.5*(b1+b2)*h, 2)}"

    elif "Romb" in shape_type:
        d1 = p1 if p1 > 0 else 8
        d2 = p2 if p2 > 0 else 6
        query_str = f"romb diagonal {int(d1) if d1.is_integer() else d1} {int(d2) if d2.is_integer() else d2}"
        info_md = f"**Diagonal 1 (d1):** {d1} | **Diagonal 2 (d2):** {d2}\n\n**Yuza S:** {round(0.5*d1*d2, 2)}"

    elif "Parallelogramm" in shape_type:
        a = p1 if p1 > 0 else 10
        h = p2 if p2 > 0 else 6
        query_str = f"parallelogramm {int(a) if a.is_integer() else a} {int(h) if h.is_integer() else h}"
        info_md = f"**Asos a:** {a} | **Balandlik h:** {h}\n\n**Yuza S:** {round(a*h, 2)}"

    else:
        a = p1 if p1 > 0 else 10
        h = p2 if p2 > 0 else 6
        query_str = f"asosi {int(a) if a.is_integer() else a} balandlik {int(h) if h.is_integer() else h}"
        info_md = f"**Asos a:** {a} | **Balandlik h:** {h}\n\n**Yuza S:** {round(0.5*a*h, 2)}"

    img_path = try_draw_geometry(query_str)
    return img_path, info_md

# 6. Statistika va Diagnostika ma'lumotlari
def get_stats_html():
    try:
        stats = get_statistics()
        return f"""
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">๐Ÿ‘ฅ</div>
                <div class="stat-val">{stats.get('total_users', 0)}</div>
                <div class="stat-label">Jami Foydalanuvchilar</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">๐Ÿ“…</div>
                <div class="stat-val">{stats.get('active_today', 0)}</div>
                <div class="stat-label">Bugungi Faollar</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">โšก</div>
                <div class="stat-val">{stats.get('total_queries', 0)}</div>
                <div class="stat-label">Yechilgan Masalalar</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">๐Ÿ“ธ</div>
                <div class="stat-val">{stats.get('photo_queries', 0)}</div>
                <div class="stat-label">Rasmli Masalalar (OCR)</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">๐ŸŽ™</div>
                <div class="stat-val">{stats.get('voice_queries', 0)}</div>
                <div class="stat-label">Ovozli Xabarlar (STT)</div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">๐Ÿ›ก</div>
                <div class="stat-val">{stats.get('total_banned', 0)}</div>
                <div class="stat-label">To'xtatilgan Hujumlar</div>
            </div>
        </div>
        """
    except Exception as e:
        return f"<div class='sincc-card error-card'>Statistikani yuklashda xatolik: {e}</div>"

def check_secrets_status():
    bot_token = (os.getenv("TELEGRAM_BOT_TOKEN") or os.getenv("BOT_TOKEN") or "").strip().strip("\"'")
    groq_keys = get_groq_keys()
    or_keys = get_openrouter_keys()
    cohere_keys = get_cohere_keys()
    mistral_keys = get_mistral_keys()
    samba_keys = get_sambanova_keys()
    cf_acc, cf_tokens = get_cloudflare_config()

    def _pool_badge(pool_name: str, keys: list[str], required: bool = False) -> str:
        if keys:
            ready, total = key_pool.status_summary(pool_name, keys)
            return f"<span class='status-ok'>โœ… {ready}/{total} kalit faol (...{keys[0][-4:]})</span>"
        if required:
            return "<span class='status-err'>โŒ Kiritilmagan</span>"
        return "<span style='color:#94a3b8; font-weight:600;'>โšช Zaxira kiritilmagan</span>"

    t_status = f"<span class='status-ok'>โœ… Ulangan (...{bot_token[-4:]})</span>" if bot_token and len(bot_token) > 10 else "<span class='status-err'>โŒ Kiritilmagan</span>"
    cf_status = _pool_badge("cloudflare_text", cf_tokens, required=False) if (cf_acc and cf_tokens) else "<span style='color:#94a3b8; font-weight:600;'>โšช Zaxira kiritilmagan</span>"
    admin_id = str(os.getenv("ADMIN_ID") or "").strip().strip("\"'").strip()
    a_status = f"<span class='status-ok'>โœ… Ulangan ({admin_id})</span>" if admin_id else "<span class='status-ok'>โœ… Standart (7759713314)</span>"
    db_status = html.escape(get_cloud_sync_status())
    db_badge = (
        f"<span style='color:#94a3b8; font-weight:600;'>{db_status}</span>"
        if db_status.startswith("โšช")
        else f"<span class='status-ok'>{db_status}</span>"
    )

    return f"""
    <div class="secrets-list">
        <div class="secret-item"><span>๐Ÿค– <b>Telegram Bot Token:</b></span> {t_status}</div>
        <div class="secret-item"><span>โšก <b>Groq AI (120B, 27B & Whisper):</b></span> {_pool_badge("groq_llm", groq_keys, required=True)}</div>
        <div class="secret-item"><span>๐Ÿ“ธ <b>OpenRouter (Vision OCR & LLM):</b></span> {_pool_badge("openrouter_vision", or_keys, required=False)}</div>
        <div class="secret-item"><span>๐Ÿ›ก <b>Cohere (Vision & Matn zaxira):</b></span> {_pool_badge("cohere_text", cohere_keys, required=False)}</div>
        <div class="secret-item"><span>๐ŸŒ€ <b>Mistral / SambaNova (Zaxira):</b></span> {_pool_badge("mistral_text", mistral_keys, required=False)} / {_pool_badge("sambanova_text", samba_keys, required=False)}</div>
        <div class="secret-item"><span>โ˜๏ธ <b>Cloudflare Workers AI (Zaxira):</b></span> {cf_status}</div>
        <div class="secret-item"><span>๐Ÿ’พ <b>Bulutli Baza (HF Dataset):</b></span> {db_badge}</div>
        <div class="secret-item"><span>๐Ÿ‘‘ <b>Admin Telegram ID:</b></span> {a_status}</div>
    </div>
    """

def test_ai_connection():
    agent1_cfg, _ = get_agent_configs()
    if not agent1_cfg["api_key"] or agent1_cfg["api_key"] == "no-key":
        return "โŒ XATO: AI kaliti (AGENT1_API_KEY yoki GROQ_API_KEY) topilmadi! Space Settings -> Secrets bo'limiga kiriting."
    try:
        import httpx
        url = agent1_cfg["base_url"].rstrip("/") + "/chat/completions"
        headers = {"Authorization": f"Bearer {agent1_cfg['api_key']}", "Content-Type": "application/json"}
        payload = {
            "model": agent1_cfg["model"],
            "messages": [{"role": "user", "content": "2+2 nechiga teng? Faqat bitta son yozing."}],
            "max_tokens": 150,
            "temperature": 0.1
        }
        r = httpx.post(url, headers=headers, json=payload, timeout=20.0)
        if r.status_code == 200:
            msg_obj = r.json()["choices"][0]["message"]
            res_content = (msg_obj.get("content") or "").strip()
            ans_short = res_content[:80] if res_content else "Aloqa o'rnatildi"
            return f"โœ… AI Aloqasi A'lo darajada ({agent1_cfg['model']})!\nJavob: {ans_short}"
        else:
            return f"โŒ AI Server xatosi (HTTP {r.status_code}): {r.text[:180]}"
    except Exception as e:
        return f"โŒ Ulanish xatosi: {e}"

# 7. Zamonaviy, Elegant Dark/Midnight CSS Dizayni (HF Spaces va Dark/Light mosligi bilan)
custom_css = """
/* Asosiy konteyner va fon */
body, .gradio-container, gradio-app {
    background-color: #0b0f19 !important;
    color: #f8fafc !important;
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important;
}

.sincc-main-container {
    max-width: 1050px !important;
    margin: 0 auto !important;
    padding: 10px 15px !important;
}

/* Header & Hero Card */
.hero-header {
    background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #4338ca 100%) !important;
    color: #ffffff !important;
    padding: 30px 25px;
    border-radius: 20px;
    text-align: center;
    box-shadow: 0 12px 30px -8px rgba(49, 46, 129, 0.5) !important;
    margin-bottom: 25px;
    border: 1px solid rgba(255, 255, 255, 0.15) !important;
}

.hero-title {
    font-size: 32px;
    font-weight: 800;
    letter-spacing: -0.5px;
    margin-bottom: 8px;
    color: #ffffff !important;
}

.hero-subtitle {
    font-size: 16px;
    color: #c7d2fe !important;
    max-width: 680px;
    margin: 0 auto 16px auto;
    line-height: 1.5;
}

.hero-badges {
    display: flex;
    justify-content: center;
    gap: 12px;
    flex-wrap: wrap;
    margin-top: 15px;
}

.pill-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: rgba(255, 255, 255, 0.12) !important;
    backdrop-filter: blur(8px);
    color: #ffffff !important;
    padding: 6px 14px;
    border-radius: 30px;
    font-size: 13px;
    font-weight: 600;
    border: 1px solid rgba(255, 255, 255, 0.25) !important;
}

.pill-badge.live {
    background: rgba(16, 185, 129, 0.25) !important;
    border-color: #10b981 !important;
    color: #a7f3d0 !important;
}

/* Telegram CTA tugmasi */
.tg-hero-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    background: #0284c7 !important;
    color: #ffffff !important;
    padding: 10px 22px;
    border-radius: 30px;
    font-weight: 700;
    text-decoration: none;
    box-shadow: 0 4px 15px rgba(2, 132, 199, 0.4) !important;
    transition: all 0.2s ease;
    margin-top: 14px;
}

.tg-hero-btn:hover {
    transform: translateY(-2px);
    background: #0369a1 !important;
    box-shadow: 0 6px 20px rgba(2, 132, 199, 0.5) !important;
}

/* Gradio Vkladkalari (Tabs) - 100% Aniq va O'qilishi Qulay */
div[role="tablist"], .tab-nav {
    background: #1e293b !important;
    border: 1px solid #334155 !important;
    border-radius: 14px !important;
    padding: 6px !important;
    gap: 6px !important;
    display: flex !important;
    flex-wrap: wrap !important;
    margin-bottom: 20px !important;
}

div[role="tablist"] button, .tab-nav button {
    background: transparent !important;
    color: #cbd5e1 !important;
    font-weight: 600 !important;
    font-size: 14px !important;
    padding: 10px 18px !important;
    border-radius: 10px !important;
    border: none !important;
    transition: all 0.2s ease !important;
}

div[role="tablist"] button:hover, .tab-nav button:hover {
    background: rgba(255, 255, 255, 0.08) !important;
    color: #ffffff !important;
}

div[role="tablist"] button.selected, .tab-nav button.selected,
div[role="tablist"] button[aria-selected="true"], .tab-nav button[aria-selected="true"] {
    background: #4f46e5 !important;
    color: #ffffff !important;
    font-weight: 700 !important;
    box-shadow: 0 4px 14px rgba(79, 70, 229, 0.45) !important;
}

/* Asosiy Yechish Tugmasi (Primary Button) */
button.primary, button.variant-primary, .primary {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    color: #ffffff !important;
    font-weight: 700 !important;
    font-size: 16px !important;
    border-radius: 12px !important;
    border: none !important;
    padding: 14px 24px !important;
    box-shadow: 0 4px 16px rgba(79, 70, 229, 0.4) !important;
    cursor: pointer !important;
    transition: all 0.2s ease !important;
    width: 100% !important;
}

button.primary:hover, button.variant-primary:hover {
    transform: translateY(-2px) !important;
    box-shadow: 0 6px 22px rgba(79, 70, 229, 0.6) !important;
}

/* Yechim va Natijalar Kartalari */
.sincc-card {
    background: #1e293b !important;
    border-radius: 16px !important;
    padding: 22px !important;
    border: 1px solid #334155 !important;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25) !important;
    margin-bottom: 18px !important;
    color: #f8fafc !important;
}

.sincc-intro {
    background: #1e293b !important;
    border-left: 4px solid #6366f1 !important;
    border: 1px solid #334155 !important;
    border-left-width: 4px !important;
    padding: 14px 18px !important;
    border-radius: 10px !important;
    font-size: 15px !important;
    color: #f1f5f9 !important;
    font-weight: 500 !important;
    margin-bottom: 20px !important;
}

.sincc-steps-wrapper {
    background: #1e293b !important;
    border-radius: 16px !important;
    padding: 22px !important;
    border: 1px solid #334155 !important;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25) !important;
    margin-bottom: 20px !important;
}

.steps-heading {
    font-size: 18px !important;
    font-weight: 700 !important;
    color: #f8fafc !important;
    margin-top: 0 !important;
    margin-bottom: 16px !important;
    border-bottom: 1px solid #334155 !important;
    padding-bottom: 10px !important;
}

.sincc-step {
    display: flex !important;
    align-items: flex-start !important;
    gap: 14px !important;
    padding: 14px 16px !important;
    background: #0f172a !important;
    border-radius: 12px !important;
    margin-bottom: 12px !important;
    border: 1px solid #334155 !important;
}

.step-num {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    color: #ffffff !important;
    width: 30px !important;
    height: 30px !important;
    border-radius: 50% !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    font-weight: 700 !important;
    font-size: 13px !important;
    flex-shrink: 0 !important;
}

.step-text {
    font-size: 15px !important;
    color: #f1f5f9 !important;
    line-height: 1.6 !important;
    padding-top: 2px !important;
}

/* Formulalar qutisi */
.formula-chips {
    display: flex !important;
    flex-wrap: wrap !important;
    gap: 8px !important;
    margin-top: 10px !important;
}

.formula-chip {
    background: rgba(79, 70, 229, 0.18) !important;
    color: #a5b4fc !important;
    padding: 6px 14px !important;
    border-radius: 8px !important;
    font-size: 13px !important;
    font-weight: 600 !important;
    border: 1px solid rgba(165, 180, 252, 0.3) !important;
}

/* Yakuniy Javob Kartasi */
.answer-card {
    background: linear-gradient(135deg, rgba(6, 78, 59, 0.45) 0%, rgba(6, 95, 70, 0.25) 100%) !important;
    border: 2px solid #10b981 !important;
    border-radius: 16px !important;
    padding: 24px !important;
    text-align: center !important;
    margin-bottom: 18px !important;
    box-shadow: 0 8px 24px -4px rgba(16, 185, 129, 0.3) !important;
}

.answer-title {
    font-size: 13px !important;
    font-weight: 800 !important;
    letter-spacing: 1.5px !important;
    color: #34d399 !important;
    margin-bottom: 6px !important;
}

.answer-value {
    font-size: 32px !important;
    font-weight: 800 !important;
    color: #ffffff !important;
    margin-bottom: 10px !important;
}

.verified-badge {
    display: inline-block !important;
    background: #059669 !important;
    color: #ffffff !important;
    font-size: 12px !important;
    font-weight: 700 !important;
    padding: 6px 16px !important;
    border-radius: 20px !important;
}

.unverified-badge {
    display: inline-block !important;
    background: #475569 !important;
    color: #ffffff !important;
    font-size: 12px !important;
    font-weight: 600 !important;
    padding: 6px 16px !important;
    border-radius: 20px !important;
}

.sincc-tip {
    background: rgba(245, 158, 11, 0.12) !important;
    border-left: 4px solid #f59e0b !important;
    border: 1px solid rgba(245, 158, 11, 0.3) !important;
    border-left-width: 4px !important;
    color: #fde68a !important;
    padding: 14px 18px !important;
    border-radius: 10px !important;
    font-size: 14px !important;
    margin-bottom: 16px !important;
}

.sincc-ocr-badge {
    display: flex !important;
    align-items: flex-start !important;
    gap: 10px !important;
    background: rgba(16, 185, 129, 0.15) !important;
    border: 1px solid #10b981 !important;
    color: #a7f3d0 !important;
    padding: 14px 18px !important;
    border-radius: 12px !important;
    margin-bottom: 18px !important;
    font-size: 14px !important;
}

.ocr-text {
    color: #ffffff !important;
    font-weight: 600 !important;
}

/* Stats Grid */
.stats-grid {
    display: grid !important;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)) !important;
    gap: 14px !important;
    margin-bottom: 20px !important;
}

.stat-card {
    background: #1e293b !important;
    border-radius: 14px !important;
    padding: 18px 14px !important;
    text-align: center !important;
    border: 1px solid #334155 !important;
}

.stat-icon {
    font-size: 28px !important;
    margin-bottom: 6px !important;
}

.stat-val {
    font-size: 26px !important;
    font-weight: 800 !important;
    color: #f8fafc !important;
}

.stat-label {
    font-size: 12px !important;
    color: #94a3b8 !important;
    font-weight: 600 !important;
}

/* Secrets List */
.secrets-list {
    background: #1e293b !important;
    border-radius: 14px !important;
    padding: 18px 22px !important;
    border: 1px solid #334155 !important;
    display: flex !important;
    flex-direction: column !important;
    gap: 12px !important;
}

.secret-item {
    display: flex !important;
    justify-content: space-between !important;
    align-items: center !important;
    padding: 10px 0 !important;
    border-bottom: 1px solid #334155 !important;
    font-size: 14px !important;
    color: #f1f5f9 !important;
}

.secret-item:last-child {
    border-bottom: none !important;
}

.status-ok {
    color: #34d399 !important;
    font-weight: 700 !important;
}

.status-err {
    color: #f87171 !important;
    font-weight: 700 !important;
}

/* Lab Card */
.lab-card {
    background: #1e293b !important;
    border-radius: 16px !important;
    padding: 22px !important;
    border: 1px solid #334155 !important;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.25) !important;
}
"""

with gr.Blocks(title="Sincc.on โ€” Milliy Matematika & Geometriya AI") as demo:
    gr.HTML(f"<style>{custom_css}</style>")
    with gr.Column(elem_classes=["sincc-main-container"]):
        
        # 1. Hero Header
        gr.HTML(
            """
            <div class="hero-header">
                <div class="hero-title">๐Ÿ“ Sincc.on โ€” Milliy Matematika & Geometriya AI</div>
                <div class="hero-subtitle">
                    O'zbek tilidagi algebra, geometriya va mantiq masalalarini ikkita mustaqil AI konsensusi va SymPy ramziy aniqlik yadrosi orqali 100% arifmetik xatolarsiz yechuvchi milliy platforma.
                </div>
                <div class="hero-badges">
                    <span class="pill-badge live">๐ŸŸข Telegramda 24/7 Faol</span>
                    <span class="pill-badge">โšก Multi-Tier AI + 6 Provayder</span>
                    <span class="pill-badge">๐Ÿ“ธ Vision OCR & ๐ŸŽ™ Whisper</span>
                    <span class="pill-badge">๐Ÿ“ Geometriya & A4 PDF</span>
                </div>
                <div>
                    <a href="https://t.me/sincconbot" target="_blank" class="tg-hero-btn">
                        ๐Ÿš€ Telegram Botni Ochish (@sincconbot)
                    </a>
                </div>
            </div>
            """
        )

        # 2. Asosiy Navigatsiya Vkladkalari (Tabs)
        with gr.Tabs():

            # ---------------- TAB 1: MASALA YECHUVCHI (UNIVERSAL SOLVER) ----------------
            with gr.Tab("๐Ÿงฎ Masala Yechuvchi (AI Solver)", id="tab_solver"):
                with gr.Row():
                    with gr.Column(scale=3):
                        input_problem = gr.Textbox(
                            label="๐Ÿ“ Matematik masala sharti",
                            placeholder="Masalan: x^2 - 5x + 6 = 0 tenglamani yeching yoki To'g'ri burchakli uchburchakning katetlari 9 va 12...",
                            lines=3
                        )
                    with gr.Column(scale=2):
                        input_image = gr.Image(
                            label="๐Ÿ“ธ Rasm yuklash (Daftar yoki Kitobdagi masalani Vision OCR orqali o'qish)",
                            type="filepath"
                        )

                with gr.Row():
                    btn_solve = gr.Button("โšก Masalani Yechish va Tahlil Qilish", variant="primary", size="lg")

                # Natijalar ko'rinishi
                with gr.Row():
                    with gr.Column(scale=3):
                        output_html = gr.HTML(
                            value="""
                            <div class="sincc-card" style="text-align: center; padding: 40px 20px;">
                                <div style="font-size: 44px; margin-bottom: 12px;">๐Ÿ“</div>
                                <h3 style="margin: 0; color: #f8fafc; font-size: 20px; font-weight: 700;">Yechim maydoni tayyor</h3>
                                <p style="margin-top: 8px; font-size: 14px; color: #94a3b8;">Yuqoriga masala shartini yozing yoki rasmini yuklab <b>ยซMasalani Yechishยป</b> tugmasini bosing.</p>
                            </div>
                            """
                        )
                    with gr.Column(scale=2):
                        output_diagram = gr.Image(label="๐Ÿ“ Geometrik Chizma", visible=False)
                        output_pdf = gr.File(label="๐Ÿ“ฅ Tayyor A4 PDF Konspekt", visible=False)

                gr.Markdown("#### ๐Ÿ’ก Tezkor Misollar (bosing va sinab ko'ring):")
                gr.Examples(
                    examples=[
                        ["x^2 - 7x + 12 = 0 tenglamaning ildizlarini toping"],
                        ["To'g'ri burchakli uchburchakning katetlari 9 va 12 ga teng. Gipotenuzasini toping"],
                        ["(x + 3)^2 - (x - 3)^2 ifodani soddalashtiring"],
                        ["Hovuzni 1-quvur 3 soatda, 2-quvur 6 soatda to'ldiradi. Ikkalasi birgalikda necha soatda to'ldiradi?"],
                        ["Tengsizlikni yeching: (2x - 4)/(x + 3) > 0"],
                        ["Pifagor teoremasi nima va uning formulasi qanday?"]
                    ],
                    inputs=input_problem
                )

                # Solver ulanishi
                btn_solve.click(
                    fn=solve_problem_web,
                    inputs=[input_problem, input_image],
                    outputs=[output_html, output_diagram, output_pdf, input_problem],
                    api_name=False
                )

            # ---------------- TAB 2: GEOMETRIYA LABORATORIYASI ----------------
            with gr.Tab("๐Ÿ“ Geometriya Laboratoriyasi", id="tab_geo"):
                gr.Markdown("### ๐Ÿ“ Geometrik Shakllarni Chizish va Hisoblash Ustaxonasi")
                gr.Markdown("Quyidagi ro'yxatdan shakl turini tanlang, o'lchamlarini kiriting va bir soniyada chizmasi va hisob-kitoblarini oling:")

                with gr.Row():
                    with gr.Column(scale=2):
                        with gr.Group():
                            shape_selector = gr.Dropdown(
                                label="Shakl turini tanlang",
                                choices=[
                                    "To'g'ri burchakli uchburchak (Katetlar a va b)",
                                    "Aylana / Doira (Radius R)",
                                    "To'g'ri to'rtburchak (Tomonlari a va b)",
                                    "Kvadrat (Tomoni a)",
                                    "Teng tomonli uchburchak (Tomoni a)",
                                    "Teng yonli uchburchak (Asos b va Yon tomon a)",
                                    "Trapetsiya (Asoslar b1, b2 va Balandlik h)",
                                    "Romb (Diagonallar d1 va d2)",
                                    "Parallelogramm (Asos a va Balandlik h)",
                                    "Uchburchak (Asos a va Balandlik h)"
                                ],
                                value="To'g'ri burchakli uchburchak (Katetlar a va b)"
                            )
                            param1 = gr.Number(label="1-O'lcham (a / R / Asos)", value=6)
                            param2 = gr.Number(label="2-O'lcham (b / h / Yon tomon / d2)", value=8)
                            param3 = gr.Number(label="3-O'lcham (Trapetsiya uchun balandlik h)", value=0)
                            btn_draw_geo = gr.Button("๐ŸŽจ Chizmani Chizish va Hisoblash", variant="primary")

                    with gr.Column(scale=3):
                        lab_img = gr.Image(label="๐Ÿ“ Natijaviy Geometrik Chizma")
                        lab_info = gr.Markdown(label="Hisob-kitoblar")

                btn_draw_geo.click(
                    fn=generate_geometry_lab,
                    inputs=[shape_selector, param1, param2, param3],
                    outputs=[lab_img, lab_info],
                    api_name=False
                )

            # ---------------- TAB 3: TIZIM VA STATISTIKA (DASHBOARD) ----------------
            with gr.Tab("๐Ÿ“Š Tizim & Jonli Statistika", id="tab_stats"):
                gr.Markdown("### ๐Ÿ“Š Sincc.on Jonli Ko'rsatkichlari va Tizim Holati")
                
                stats_display = gr.HTML(value=get_stats_html())
                btn_refresh_stats = gr.Button("๐Ÿ”„ Statistikani Yangilash", size="sm", variant="secondary")
                btn_refresh_stats.click(fn=get_stats_html, outputs=stats_display, api_name=False)

                gr.Markdown("---")
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("#### ๐Ÿ” API Kalitlari (Secrets) Diagnostikasi:")
                        secrets_display = gr.HTML(value=check_secrets_status())
                    with gr.Column(scale=1):
                        gr.Markdown("#### ๐Ÿงช AI Bog'lanishini Sinash:")
                        btn_test_ai = gr.Button("โšก AI Dvigatelini Tekshirish (Groq 120B)", variant="primary")
                        test_ai_output = gr.Markdown(value="*AI aloqasini tekshirish uchun tugmani bosing.*")
                        btn_test_ai.click(fn=test_ai_connection, outputs=test_ai_output, api_name=False)

            # ---------------- TAB 4: LOYIHA HAQIDA (ABOUT) ----------------
            with gr.Tab("โ„น๏ธ Loyiha Haqida", id="tab_about"):
                gr.Markdown(
                    """
                    ### ๐Ÿ› Sincc.on Ekotizimi Qanday Ishlaydi?
                    
                    **Sincc.on** โ€” o'zbek tilidagi matematika va geometriya ta'limida sun'iy intellekt gallutsinatsiyalarini yo'qotish uchun yaratilgan milliy tizim:
                    
                    1. **โšก Adaptive Multi-Tier & Dual-Agent Consensus:** `Tier 0` (Lokal SymPy `0.005s`), `Tier 1` (Flagman `GPT-OSS-120B`), `Tier 2` (Dual-Agent `GPT-OSS-120B` + `Qwen-3.8-27B` kross-bahslashuvi) va limitga tushmaslik uchun 6 ta bepul provayderli `KeyPool` zanjiri (`Groq`, `OpenRouter`, `Cohere`, `Mistral`, `SambaNova`, `Cloudflare Workers AI`).
                    2. **โš™๏ธ Program-of-Thought (SymPy Sandbox):** Modellar yechim mantiqini Python/SymPy kodiga aylantiradi. AST tahlilidan o'tgan xavfsiz izolyatsiyada hisoblash amalga oshirilib, algebraik aniqlik 100% tasdiqlanadi.
                    3. **๐Ÿ“ธ Multimodal Vision OCR:** `Gemma-4-31B`, `Nemotron-3.5-VL` va zaxira `Cohere Vision` orqali daftardagi yoki kitobdagi rasm hamda chizmalar masalaga aylantiriladi.
                    4. **๐ŸŽ™ Whisper STT:** O'zbek tilidagi ovozli xabarlar (`whisper-large-v3` / `turbo`) bir necha soniyada matnga o'girilib yechiladi.
                    5. **๐Ÿ“ Visual Geometry & A4 PDF Konspekt:** `matplotlib` orqali ko'rgazmali chizma (PNG) va `reportlab` orqali tayyor A4 PDF konspekt yaratiladi.
                    6. **๐Ÿ’พ Doimiy Bulutli Baza:** SQLite ma'lumotlari yopiq Hugging Face Dataset bilan avtomatik sinxronizatsiya qilinadi.

                    ---
                    
                    ### ๐Ÿ‘จโ€๐Ÿ’ป Muallif Haqida:
                    Ushbu loyiha O'zbekiston yoshlarining matematika, mantiq va sun'iy intellekt sohalaridagi bilimini yuksaltirish, ta'limda mutlaq aniqlikni ta'minlash maqsadida 14 yoshli yosh dasturchi **Shahbozxon (Sh. Abbosov)** tomonidan yaratildi.
                    
                    * ๐Ÿ“ฌ **Muallif bilan bog'lanish (Telegram):** [@sh_abbosov](https://t.me/sh_abbosov)
                    * ๐Ÿค– **Telegram Bot:** [@sincconbot](https://t.me/sincconbot)
                    * โ˜๏ธ **Bulut:** Hugging Face Spaces (`Shaptoli/Sinccon`) 24/7
                    """
                )

        # Footer
        gr.HTML(
            """
            <div style="text-align: center; color: #94a3b8; font-size: 13px; margin-top: 30px; padding-top: 15px; border-top: 1px solid #e2e8f0;">
                Sincc.on ยฉ 2026 โ€” Milliy O'zbek Matematika & Geometriya AI Ekotizimi. Barcha huquqlar himoyalangan.
            </div>
            """
        )

if __name__ == "__main__":
    launch_kwargs = {
        "server_name": "0.0.0.0",
        "server_port": 7860,
    }
    import inspect
    sig = inspect.signature(demo.launch).parameters
    if "ssr" in sig:
        launch_kwargs["ssr"] = False
    if "ssr_mode" in sig:
        launch_kwargs["ssr_mode"] = False
    if "show_api" in sig:
        launch_kwargs["show_api"] = False

    demo.queue().launch(**launch_kwargs)