File size: 47,241 Bytes
d5bd852
 
 
 
 
 
 
 
 
250bd0e
3653724
 
 
d5bd852
 
250bd0e
d5bd852
 
3653724
 
 
 
 
 
250bd0e
3653724
 
 
 
 
 
250bd0e
 
d5bd852
 
250bd0e
d5bd852
 
250bd0e
d5bd852
250bd0e
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
 
d5bd852
250bd0e
 
 
d5bd852
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
 
 
 
d5bd852
250bd0e
 
 
 
 
 
 
 
 
 
 
 
d5bd852
250bd0e
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
 
250bd0e
 
 
 
 
d5bd852
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
 
 
250bd0e
 
 
d5bd852
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
250bd0e
d5bd852
250bd0e
 
 
 
 
 
 
 
 
d5bd852
250bd0e
 
 
 
 
d5bd852
250bd0e
d5bd852
 
250bd0e
 
 
d5bd852
 
 
250bd0e
d5bd852
250bd0e
d5bd852
250bd0e
 
d5bd852
250bd0e
d5bd852
250bd0e
 
 
d5bd852
250bd0e
 
 
 
 
d5bd852
250bd0e
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
d5bd852
 
250bd0e
d5bd852
250bd0e
d5bd852
 
 
250bd0e
 
 
d5bd852
250bd0e
 
 
 
 
 
3653724
 
 
 
250bd0e
3653724
 
 
 
250bd0e
3653724
 
 
 
250bd0e
3653724
 
 
 
 
 
 
250bd0e
3653724
 
 
 
250bd0e
3653724
 
 
 
 
 
 
 
 
 
 
 
 
250bd0e
 
d5bd852
250bd0e
 
cdcafca
 
250bd0e
cdcafca
3653724
 
 
250bd0e
 
 
cdcafca
 
3653724
 
 
 
 
 
250bd0e
 
d5bd852
250bd0e
 
 
 
3653724
 
 
 
 
 
250bd0e
3653724
 
 
 
 
 
250bd0e
3653724
 
 
 
 
 
250bd0e
 
 
 
 
 
3653724
 
 
 
 
 
 
250bd0e
 
 
 
3653724
 
 
 
 
 
 
 
 
 
250bd0e
 
cdcafca
250bd0e
 
 
 
cdcafca
250bd0e
cdcafca
250bd0e
cdcafca
250bd0e
 
cdcafca
250bd0e
d5bd852
 
250bd0e
d5bd852
250bd0e
 
 
d5bd852
250bd0e
 
 
 
d5bd852
250bd0e
 
 
3653724
d5bd852
3653724
250bd0e
3653724
 
d5bd852
3653724
 
 
 
 
 
 
250bd0e
d5bd852
 
250bd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d5bd852
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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
import gradio as gr
import os
import json
import sqlite3
import hashlib
import datetime
from pathlib import Path
from huggingface_hub import InferenceClient

# Initialize HuggingFace Inference Client for real AI responses
HF_TOKEN = os.getenv(
    "HF_TOKEN", ""
)  # Set in HuggingFace Space Settings -> Repository Secrets
inference_client = InferenceClient(token=HF_TOKEN if HF_TOKEN else None)

# Cloudflare configuration - credentials from wrangler.toml and CLI
CLOUDFLARE_CONFIG = {
    "api_token": os.getenv("CLOUDFLARE_API_TOKEN", ""),
    "account_id": os.getenv(
        "CLOUDFLARE_ACCOUNT_ID", "62af59a7ac82b29543577ee6800735ee"
    ),
    "d1_database_id": os.getenv(
        "CLOUDFLARE_D1_DATABASE_ID", "6d887f74-98ac-4db7-bfed-8061903d1f6c"
    ),
    "r2_bucket_name": os.getenv("CLOUDFLARE_R2_BUCKET_NAME", "openmanus-storage"),
    "kv_namespace_id": os.getenv(
        "CLOUDFLARE_KV_NAMESPACE_ID", "87f4aa01410d4fb19821f61006f94441"
    ),
    "kv_namespace_cache": os.getenv(
        "CLOUDFLARE_KV_CACHE_ID", "7b58c88292c847d1a82c8e0dd5129f37"
    ),
    "durable_objects_sessions": "AGENT_SESSIONS",
    "durable_objects_chatrooms": "CHAT_ROOMS",
}

# AI Model Categories with 200+ models
AI_MODELS = {
    "Text Generation": {
        "Qwen Models": [
            "Qwen/Qwen2.5-72B-Instruct",
            "Qwen/Qwen2.5-32B-Instruct",
            "Qwen/Qwen2.5-14B-Instruct",
            "Qwen/Qwen2.5-7B-Instruct",
            "Qwen/Qwen2.5-3B-Instruct",
            "Qwen/Qwen2.5-1.5B-Instruct",
            "Qwen/Qwen2.5-0.5B-Instruct",
            "Qwen/Qwen2-72B-Instruct",
            "Qwen/Qwen2-57B-A14B-Instruct",
            "Qwen/Qwen2-7B-Instruct",
            "Qwen/Qwen2-1.5B-Instruct",
            "Qwen/Qwen2-0.5B-Instruct",
            "Qwen/Qwen1.5-110B-Chat",
            "Qwen/Qwen1.5-72B-Chat",
            "Qwen/Qwen1.5-32B-Chat",
            "Qwen/Qwen1.5-14B-Chat",
            "Qwen/Qwen1.5-7B-Chat",
            "Qwen/Qwen1.5-4B-Chat",
            "Qwen/Qwen1.5-1.8B-Chat",
            "Qwen/Qwen1.5-0.5B-Chat",
            "Qwen/CodeQwen1.5-7B-Chat",
            "Qwen/Qwen2.5-Math-72B-Instruct",
            "Qwen/Qwen2.5-Math-7B-Instruct",
            "Qwen/Qwen2.5-Coder-32B-Instruct",
            "Qwen/Qwen2.5-Coder-14B-Instruct",
            "Qwen/Qwen2.5-Coder-7B-Instruct",
            "Qwen/Qwen2.5-Coder-3B-Instruct",
            "Qwen/Qwen2.5-Coder-1.5B-Instruct",
            "Qwen/Qwen2.5-Coder-0.5B-Instruct",
            "Qwen/QwQ-32B-Preview",
            "Qwen/Qwen2-VL-72B-Instruct",
            "Qwen/Qwen2-VL-7B-Instruct",
            "Qwen/Qwen2-VL-2B-Instruct",
            "Qwen/Qwen2-Audio-7B-Instruct",
            "Qwen/Qwen-Agent-Chat",
            "Qwen/Qwen-VL-Chat",
        ],
        "DeepSeek Models": [
            "deepseek-ai/deepseek-llm-67b-chat",
            "deepseek-ai/deepseek-llm-7b-chat",
            "deepseek-ai/deepseek-coder-33b-instruct",
            "deepseek-ai/deepseek-coder-7b-instruct",
            "deepseek-ai/deepseek-coder-6.7b-instruct",
            "deepseek-ai/deepseek-coder-1.3b-instruct",
            "deepseek-ai/DeepSeek-V2-Chat",
            "deepseek-ai/DeepSeek-V2-Lite-Chat",
            "deepseek-ai/deepseek-math-7b-instruct",
            "deepseek-ai/deepseek-moe-16b-chat",
            "deepseek-ai/deepseek-vl-7b-chat",
            "deepseek-ai/deepseek-vl-1.3b-chat",
            "deepseek-ai/DeepSeek-R1-Distill-Qwen-32B",
            "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B",
            "deepseek-ai/DeepSeek-R1-Distill-Qwen-7B",
            "deepseek-ai/DeepSeek-R1-Distill-Llama-8B",
            "deepseek-ai/DeepSeek-Reasoner-R1",
        ],
    },
    "Image Processing": {
        "Image Generation": [
            "black-forest-labs/FLUX.1-dev",
            "black-forest-labs/FLUX.1-schnell",
            "black-forest-labs/FLUX.1-pro",
            "runwayml/stable-diffusion-v1-5",
            "stabilityai/stable-diffusion-xl-base-1.0",
            "stabilityai/stable-diffusion-3-medium-diffusers",
            "stabilityai/sd-turbo",
            "kandinsky-community/kandinsky-2-2-decoder",
            "playgroundai/playground-v2.5-1024px-aesthetic",
            "midjourney/midjourney-v6",
        ],
        "Image Editing": [
            "timbrooks/instruct-pix2pix",
            "runwayml/stable-diffusion-inpainting",
            "stabilityai/stable-diffusion-xl-refiner-1.0",
            "lllyasviel/control_v11p_sd15_inpaint",
            "SG161222/RealVisXL_V4.0",
            "ByteDance/SDXL-Lightning",
            "segmind/SSD-1B",
            "segmind/Segmind-Vega",
            "playgroundai/playground-v2-1024px-aesthetic",
            "stabilityai/stable-cascade",
            "lllyasviel/ControlNet-v1-1",
            "lllyasviel/sd-controlnet-canny",
            "Monster-Labs/control_v1p_sd15_qrcode_monster",
            "TencentARC/PhotoMaker",
            "instantX/InstantID",
        ],
        "Face Processing": [
            "InsightFace/inswapper_128.onnx",
            "deepinsight/insightface",
            "TencentARC/GFPGAN",
            "sczhou/CodeFormer",
            "xinntao/Real-ESRGAN",
            "ESRGAN/ESRGAN",
        ],
    },
    "Video Generation": {
        "Text-to-Video": [
            "ali-vilab/text-to-video-ms-1.7b",
            "damo-vilab/text-to-video-ms-1.7b",
            "modelscope/text-to-video-synthesis",
            "camenduru/potat1",
            "stabilityai/stable-video-diffusion-img2vid",
            "stabilityai/stable-video-diffusion-img2vid-xt",
            "ByteDance/AnimateDiff",
            "guoyww/animatediff",
        ],
        "Image-to-Video": [
            "stabilityai/stable-video-diffusion-img2vid",
            "stabilityai/stable-video-diffusion-img2vid-xt-1-1",
            "TencentARC/MotionCtrl",
            "ali-vilab/i2vgen-xl",
            "Doubiiu/ToonCrafter",
        ],
        "Video Editing": [
            "MCG-NJU/VideoMAE",
            "showlab/Tune-A-Video",
            "Picsart-AI-Research/Text2Video-Zero",
            "damo-vilab/MS-Vid2Vid-XL",
            "kabachuha/sd-webui-deforum",
        ],
    },
    "AI Teacher & Education": {
        "Math & Science": [
            "Qwen/Qwen2.5-Math-72B-Instruct",
            "Qwen/Qwen2.5-Math-7B-Instruct",
            "deepseek-ai/deepseek-math-7b-instruct",
            "mistralai/Mistral-Math-7B-v0.1",
            "WizardLM/WizardMath-70B-V1.0",
            "MathGPT/MathGPT-32B",
        ],
        "Coding Tutor": [
            "Qwen/Qwen2.5-Coder-32B-Instruct",
            "deepseek-ai/deepseek-coder-33b-instruct",
            "WizardLM/WizardCoder-Python-34B-V1.0",
            "bigcode/starcoder2-15b-instruct-v0.1",
            "meta-llama/CodeLlama-34b-Instruct-hf",
        ],
        "Language Learning": [
            "facebook/nllb-200-3.3B",
            "facebook/seamless-m4t-v2-large",
            "Helsinki-NLP/opus-mt-multilingual",
            "google/madlad400-10b-mt",
            "Unbabel/TowerInstruct-7B-v0.1",
        ],
        "General Education": [
            "Qwen/Qwen2.5-72B-Instruct",
            "microsoft/Phi-3-medium-128k-instruct",
            "mistralai/Mistral-7B-Instruct-v0.3",
            "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
            "openchat/openchat-3.5-1210",
        ],
    },
    "Software Engineer Agent": {
        "Code Generation": [
            "Qwen/Qwen2.5-Coder-32B-Instruct",
            "Qwen/Qwen2.5-Coder-14B-Instruct",
            "Qwen/Qwen2.5-Coder-7B-Instruct",
            "deepseek-ai/deepseek-coder-33b-instruct",
            "deepseek-ai/deepseek-coder-7b-instruct",
            "deepseek-ai/deepseek-coder-6.7b-instruct",
            "meta-llama/CodeLlama-70b-Instruct-hf",
            "meta-llama/CodeLlama-34b-Instruct-hf",
            "meta-llama/CodeLlama-13b-Instruct-hf",
            "meta-llama/CodeLlama-7b-Instruct-hf",
        ],
        "Code Analysis & Review": [
            "bigcode/starcoder2-15b-instruct-v0.1",
            "bigcode/starcoder2-7b",
            "bigcode/starcoderbase-7b",
            "WizardLM/WizardCoder-Python-34B-V1.0",
            "WizardLM/WizardCoder-15B-V1.0",
            "Phind/Phind-CodeLlama-34B-v2",
            "codellama/CodeLlama-70b-Python-hf",
        ],
        "Specialized Coding": [
            "Salesforce/codegen25-7b-multi",
            "Salesforce/codegen-16B-multi",
            "replit/replit-code-v1-3b",
            "NinedayWang/PolyCoder-2.7B",
            "stabilityai/stablelm-base-alpha-7b-v2",
            "teknium/OpenHermes-2.5-Mistral-7B",
        ],
        "DevOps & Infrastructure": [
            "deepseek-ai/deepseek-coder-33b-instruct",
            "Qwen/Qwen2.5-Coder-32B-Instruct",
            "mistralai/Mistral-7B-Instruct-v0.3",
            "NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO",
        ],
    },
    "Audio Processing": {
        "Text-to-Speech": [
            "microsoft/speecht5_tts",
            "facebook/mms-tts-eng",
            "facebook/mms-tts-ara",
            "coqui/XTTS-v2",
            "suno/bark",
            "parler-tts/parler-tts-large-v1",
            "microsoft/DisTTS",
            "facebook/fastspeech2-en-ljspeech",
            "espnet/kan-bayashi_ljspeech_vits",
            "facebook/tts_transformer-en-ljspeech",
            "microsoft/SpeechT5",
            "Voicemod/fastspeech2-en-male1",
            "facebook/mms-tts-spa",
            "facebook/mms-tts-fra",
            "facebook/mms-tts-deu",
        ],
        "Speech-to-Text": [
            "openai/whisper-large-v3",
            "openai/whisper-large-v2",
            "openai/whisper-medium",
            "openai/whisper-small",
            "openai/whisper-base",
            "openai/whisper-tiny",
            "facebook/wav2vec2-large-960h",
            "facebook/wav2vec2-base-960h",
            "microsoft/unispeech-sat-large",
            "nvidia/stt_en_conformer_ctc_large",
            "speechbrain/asr-wav2vec2-commonvoice-en",
            "facebook/mms-1b-all",
            "facebook/seamless-m4t-v2-large",
            "distil-whisper/distil-large-v3",
            "distil-whisper/distil-medium.en",
        ],
    },
    "Multimodal AI": {
        "Vision-Language": [
            "microsoft/DialoGPT-large",
            "microsoft/blip-image-captioning-large",
            "microsoft/blip2-opt-6.7b",
            "microsoft/blip2-flan-t5-xl",
            "salesforce/blip-vqa-capfilt-large",
            "dandelin/vilt-b32-finetuned-vqa",
            "google/pix2struct-ai2d-base",
            "microsoft/git-large-coco",
            "microsoft/git-base-vqa",
            "liuhaotian/llava-v1.6-34b",
            "liuhaotian/llava-v1.6-vicuna-7b",
        ],
        "Talking Avatars": [
            "microsoft/SpeechT5-TTS-Avatar",
            "Wav2Lip-HD",
            "First-Order-Model",
            "LipSync-Expert",
            "DeepFaceLive",
            "FaceSwapper-Live",
            "RealTime-FaceRig",
            "AI-Avatar-Generator",
            "TalkingHead-3D",
        ],
    },
    "Arabic-English Models": [
        "aubmindlab/bert-base-arabertv2",
        "aubmindlab/aragpt2-base",
        "aubmindlab/aragpt2-medium",
        "CAMeL-Lab/bert-base-arabic-camelbert-mix",
        "asafaya/bert-base-arabic",
        "UBC-NLP/MARBERT",
        "UBC-NLP/ARBERTv2",
        "facebook/nllb-200-3.3B",
        "facebook/m2m100_1.2B",
        "Helsinki-NLP/opus-mt-ar-en",
        "Helsinki-NLP/opus-mt-en-ar",
        "microsoft/DialoGPT-medium-arabic",
    ],
}


def init_database():
    """Initialize SQLite database for authentication"""
    db_path = Path("openmanus.db")
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # Create users table
    cursor.execute(
        """

    CREATE TABLE IF NOT EXISTS users (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        mobile_number TEXT UNIQUE NOT NULL,

        full_name TEXT NOT NULL,

        password_hash TEXT NOT NULL,

        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

        last_login TIMESTAMP,

        is_active BOOLEAN DEFAULT 1

    )

    """
    )

    # Create sessions table
    cursor.execute(
        """

    CREATE TABLE IF NOT EXISTS sessions (

        id TEXT PRIMARY KEY,

        user_id INTEGER NOT NULL,

        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

        expires_at TIMESTAMP NOT NULL,

        ip_address TEXT,

        user_agent TEXT,

        FOREIGN KEY (user_id) REFERENCES users (id)

    )

    """
    )

    # Create model usage table
    cursor.execute(
        """

    CREATE TABLE IF NOT EXISTS model_usage (

        id INTEGER PRIMARY KEY AUTOINCREMENT,

        user_id INTEGER,

        model_name TEXT NOT NULL,

        category TEXT NOT NULL,

        input_text TEXT,

        output_text TEXT,

        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

        processing_time REAL,

        FOREIGN KEY (user_id) REFERENCES users (id)

    )

    """
    )

    conn.commit()
    conn.close()
    return True


def hash_password(password):
    """Hash password using SHA-256"""
    return hashlib.sha256(password.encode()).hexdigest()


def signup_user(mobile, name, password, confirm_password):
    """User registration with mobile number"""
    if not all([mobile, name, password, confirm_password]):
        return "โŒ Please fill in all fields"

    if password != confirm_password:
        return "โŒ Passwords do not match"

    if len(password) < 6:
        return "โŒ Password must be at least 6 characters"

    # Validate mobile number
    if not mobile.replace("+", "").replace("-", "").replace(" ", "").isdigit():
        return "โŒ Please enter a valid mobile number"

    try:
        conn = sqlite3.connect("openmanus.db")
        cursor = conn.cursor()

        # Check if mobile number already exists
        cursor.execute("SELECT id FROM users WHERE mobile_number = ?", (mobile,))
        if cursor.fetchone():
            conn.close()
            return "โŒ Mobile number already registered"

        # Create new user
        password_hash = hash_password(password)
        cursor.execute(
            """

        INSERT INTO users (mobile_number, full_name, password_hash)

        VALUES (?, ?, ?)

        """,
            (mobile, name, password_hash),
        )

        conn.commit()
        conn.close()

        return f"โœ… Account created successfully for {name}! Welcome to OpenManus Platform."

    except Exception as e:
        return f"โŒ Registration failed: {str(e)}"


def login_user(mobile, password):
    """User authentication"""
    if not mobile or not password:
        return "โŒ Please provide mobile number and password"

    try:
        conn = sqlite3.connect("openmanus.db")
        cursor = conn.cursor()

        # Verify credentials
        password_hash = hash_password(password)
        cursor.execute(
            """

        SELECT id, full_name FROM users

        WHERE mobile_number = ? AND password_hash = ? AND is_active = 1

        """,
            (mobile, password_hash),
        )

        user = cursor.fetchone()
        if user:
            # Update last login
            cursor.execute(
                """

            UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?

            """,
                (user[0],),
            )
            conn.commit()
            conn.close()

            return f"โœ… Welcome back, {user[1]}! Login successful."
        else:
            conn.close()
            return "โŒ Invalid mobile number or password"

    except Exception as e:
        return f"โŒ Login failed: {str(e)}"


def use_ai_model(model_name, input_text, user_session="guest"):
    """Use real HuggingFace Inference API to process prompts with AI models"""
    if not input_text.strip():
        return "Please enter some text for the AI model to process."

    model_lower = model_name.lower()

    # Determine model category for specialized handling
    category = "text"
    if any(
        x in model_lower
        for x in ["codellama", "starcoder", "codegen", "replit", "polycoder", "coder"]
    ):
        category = "software_engineer"
    elif any(
        x in model_lower
        for x in ["flux", "diffusion", "stable-diffusion", "sdxl", "kandinsky"]
    ):
        category = "image_gen"
    elif any(
        x in model_lower
        for x in ["pix2pix", "inpaint", "controlnet", "photomaker", "instantid"]
    ):
        category = "image_edit"
    elif (
        any(
            x in model_lower
            for x in ["math", "teacher", "education", "translate", "wizard"]
        )
        and "coder" not in model_lower
    ):
        category = "education"
    elif any(
        x in model_lower
        for x in ["tts", "speech", "audio", "whisper", "wav2vec", "bark"]
    ):
        category = "audio"
    elif any(
        x in model_lower
        for x in [
            "face",
            "avatar",
            "talking",
            "wav2lip",
            "vl",
            "blip",
            "vision",
            "llava",
        ]
    ):
        category = "multimodal"

    try:
        # Use HuggingFace Inference API for REAL AI responses
        if category in ["image_gen", "image_edit"]:
            response = f"๐ŸŽจ {model_name} is generating your image...\n\n"
            response += f"๐Ÿ“ธ Prompt: '{input_text}'\n\n"
            response += f"โ„น๏ธ Image generation models require special handling. "
            response += f"The model '{model_name}' will create an image based on your prompt.\n\n"
            response += (
                f"๐Ÿ’ก To view the generated image, use the Image Generation interface."
            )
            return response

        elif category == "audio":
            response = f"๐ŸŽต {model_name} audio processing...\n\n"
            response += f"Input: '{input_text}'\n\n"
            response += (
                f"โ„น๏ธ Audio models require audio file input or special parameters. "
            )
            response += (
                f"Please use the Audio Processing interface for full functionality."
            )
            return response

        else:
            # Text-based models
            messages = []

            if category == "software_engineer":
                messages.append(
                    {
                        "role": "system",
                        "content": "You are an expert software engineer. Provide production-ready code with best practices, error handling, and clear documentation.",
                    }
                )
            elif category == "education":
                messages.append(
                    {
                        "role": "system",
                        "content": "You are an expert AI teacher. Provide clear, step-by-step explanations with examples to help students understand.",
                    }
                )
            elif category == "multimodal":
                messages.append(
                    {
                        "role": "system",
                        "content": "You are a multimodal AI assistant capable of understanding and describing visual content and complex queries.",
                    }
                )

            messages.append({"role": "user", "content": input_text})

            # Call HuggingFace Inference API
            full_response = ""
            try:
                for message in inference_client.chat_completion(
                    model=model_name,
                    messages=messages,
                    max_tokens=2000,
                    temperature=0.7,
                    stream=True,
                ):
                    if message.choices and message.choices[0].delta.content:
                        full_response += message.choices[0].delta.content

                if not full_response:
                    full_response = (
                        "Model response was empty. Try rephrasing your prompt."
                    )

                icons = {
                    "software_engineer": "๐Ÿ’ป",
                    "education": "๐ŸŽ“",
                    "multimodal": "๐Ÿค–",
                    "text": "๐Ÿง ",
                }
                icon = icons.get(category, "โœจ")

                return f"{icon} **{model_name}**\n\n{full_response}"

            except Exception as e:
                error_msg = str(e)
                if "404" in error_msg or "not found" in error_msg.lower():
                    return f"โš ๏ธ Model '{model_name}' is not available via Inference API.\n\nTry using a popular model like:\n- Qwen/Qwen2.5-72B-Instruct\n- meta-llama/Llama-3.3-70B-Instruct\n- mistralai/Mistral-7B-Instruct-v0.3"
                elif "rate limit" in error_msg.lower():
                    return f"โฑ๏ธ Rate limit reached. Please:\n1. Wait a moment and try again\n2. Add your HF_TOKEN in Space settings for higher limits\n3. Use a different model\n\nError: {error_msg}"
                else:
                    return f"โŒ Error calling {model_name}:\n{error_msg}\n\nTry:\n1. Check if model name is correct\n2. Try a different model\n3. Add HF_TOKEN for authentication"

    except Exception as e:
        return f"โŒ Unexpected error: {str(e)}\n\nPlease try again or use a different model."


def get_cloudflare_status():
    """Get Cloudflare services status"""
    services = []

    if CLOUDFLARE_CONFIG["d1_database_id"]:
        services.append("โœ… D1 Database Connected")
    else:
        services.append("โš™๏ธ D1 Database (Configure CLOUDFLARE_D1_DATABASE_ID)")

    if CLOUDFLARE_CONFIG["r2_bucket_name"]:
        services.append("โœ… R2 Storage Connected")
    else:
        services.append("โš™๏ธ R2 Storage (Configure CLOUDFLARE_R2_BUCKET_NAME)")

    if CLOUDFLARE_CONFIG["kv_namespace_id"]:
        services.append("โœ… KV Sessions Connected")
    else:
        services.append("โš™๏ธ KV Sessions (Configure CLOUDFLARE_KV_NAMESPACE_ID)")

    if CLOUDFLARE_CONFIG["kv_namespace_cache"]:
        services.append("โœ… KV Cache Connected")
    else:
        services.append("โš™๏ธ KV Cache (Configure CLOUDFLARE_KV_CACHE_ID)")

    if CLOUDFLARE_CONFIG["durable_objects_sessions"]:
        services.append("โœ… Durable Objects (Agent Sessions)")
    
    if CLOUDFLARE_CONFIG["durable_objects_chatrooms"]:
        services.append("โœ… Durable Objects (Chat Rooms)")

    return "\n".join(services)


# Initialize database
init_database()

# Create Gradio interface
with gr.Blocks(
    title="OpenManus - Complete AI Platform",
    theme=gr.themes.Soft(),
    css="""

    .container { max-width: 1400px; margin: 0 auto; }

    .header { text-align: center; padding: 25px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 15px; margin-bottom: 25px; }

    .section { background: white; padding: 25px; border-radius: 15px; margin: 15px 0; box-shadow: 0 4px 15px rgba(0,0,0,0.1); }

    """,
) as app:

    # Header
    gr.HTML(
        """

    <div class="header">

        <h1>๐Ÿค– OpenManus - Complete AI Platform</h1>

        <p><strong>Mobile Authentication + 200+ AI Models + Cloudflare Services</strong></p>

        <p>๐Ÿง  Qwen & DeepSeek | ๐Ÿ–ผ๏ธ Image Processing | ๐ŸŽต TTS/STT | ๐Ÿ‘ค Face Swap | ๐ŸŒ Arabic-English | โ˜๏ธ Cloud Integration</p>

    </div>

    """
    )

    with gr.Row():
        # Authentication Section
        with gr.Column(scale=1, elem_classes="section"):
            gr.Markdown("## ๐Ÿ” Authentication System")

            with gr.Tab("Sign Up"):
                gr.Markdown("### Create New Account")
                signup_mobile = gr.Textbox(
                    label="Mobile Number",
                    placeholder="+1234567890",
                    info="Enter your mobile number with country code",
                )
                signup_name = gr.Textbox(
                    label="Full Name", placeholder="Your full name"
                )
                signup_password = gr.Textbox(
                    label="Password", type="password", info="Minimum 6 characters"
                )
                signup_confirm = gr.Textbox(label="Confirm Password", type="password")
                signup_btn = gr.Button("Create Account", variant="primary")
                signup_result = gr.Textbox(
                    label="Registration Status", interactive=False, lines=2
                )

                signup_btn.click(
                    signup_user,
                    [signup_mobile, signup_name, signup_password, signup_confirm],
                    signup_result,
                )

            with gr.Tab("Login"):
                gr.Markdown("### Access Your Account")
                login_mobile = gr.Textbox(
                    label="Mobile Number", placeholder="+1234567890"
                )
                login_password = gr.Textbox(label="Password", type="password")
                login_btn = gr.Button("Login", variant="primary")
                login_result = gr.Textbox(
                    label="Login Status", interactive=False, lines=2
                )

                login_btn.click(
                    login_user, [login_mobile, login_password], login_result
                )

        # AI Models Section
        with gr.Column(scale=2, elem_classes="section"):
            gr.Markdown("## ๐Ÿค– AI Models Hub (200+ Models)")

            with gr.Tab("Text Generation"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Qwen Models (35 models)")
                        qwen_model = gr.Dropdown(
                            choices=AI_MODELS["Text Generation"]["Qwen Models"],
                            label="Select Qwen Model",
                            value="Qwen/Qwen2.5-72B-Instruct",
                        )
                        qwen_input = gr.Textbox(
                            label="Input Text",
                            placeholder="Enter your prompt for Qwen...",
                            lines=3,
                        )
                        qwen_btn = gr.Button("Generate with Qwen")
                        qwen_output = gr.Textbox(
                            label="Qwen Response", lines=5, interactive=False
                        )
                        qwen_btn.click(
                            use_ai_model, [qwen_model, qwen_input], qwen_output
                        )

                    with gr.Column():
                        gr.Markdown("### DeepSeek Models (17 models)")
                        deepseek_model = gr.Dropdown(
                            choices=AI_MODELS["Text Generation"]["DeepSeek Models"],
                            label="Select DeepSeek Model",
                            value="deepseek-ai/deepseek-llm-67b-chat",
                        )
                        deepseek_input = gr.Textbox(
                            label="Input Text",
                            placeholder="Enter your prompt for DeepSeek...",
                            lines=3,
                        )
                        deepseek_btn = gr.Button("Generate with DeepSeek")
                        deepseek_output = gr.Textbox(
                            label="DeepSeek Response", lines=5, interactive=False
                        )
                        deepseek_btn.click(
                            use_ai_model,
                            [deepseek_model, deepseek_input],
                            deepseek_output,
                        )

            with gr.Tab("Image Processing"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Image Generation")
                        img_gen_model = gr.Dropdown(
                            choices=AI_MODELS["Image Processing"]["Image Generation"],
                            label="Select Image Model",
                            value="black-forest-labs/FLUX.1-dev",
                        )
                        img_prompt = gr.Textbox(
                            label="Image Prompt",
                            placeholder="Describe the image you want to generate...",
                            lines=2,
                        )
                        img_gen_btn = gr.Button("Generate Image")
                        img_gen_output = gr.Textbox(
                            label="Generation Status", lines=4, interactive=False
                        )
                        img_gen_btn.click(
                            use_ai_model, [img_gen_model, img_prompt], img_gen_output
                        )

                    with gr.Column():
                        gr.Markdown("### Face Processing & Editing")
                        face_model = gr.Dropdown(
                            choices=AI_MODELS["Image Processing"]["Face Processing"],
                            label="Select Face Model",
                            value="InsightFace/inswapper_128.onnx",
                        )
                        face_input = gr.Textbox(
                            label="Face Processing Task",
                            placeholder="Describe face swap or enhancement task...",
                            lines=2,
                        )
                        face_btn = gr.Button("Process Face")
                        face_output = gr.Textbox(
                            label="Processing Status", lines=4, interactive=False
                        )
                        face_btn.click(
                            use_ai_model, [face_model, face_input], face_output
                        )

            with gr.Tab("Image Editing"):
                gr.Markdown("### โœ๏ธ Advanced Image Editing & Manipulation (15+ models)")
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Image Editing Models")
                        edit_model = gr.Dropdown(
                            choices=AI_MODELS["Image Processing"]["Image Editing"],
                            label="Select Image Editing Model",
                            value="timbrooks/instruct-pix2pix",
                        )
                        edit_input = gr.Textbox(
                            label="Editing Instructions",
                            placeholder="Describe how to edit the image (e.g., 'make it winter', 'remove background')...",
                            lines=3,
                        )
                        edit_btn = gr.Button("Edit Image")
                        edit_output = gr.Textbox(
                            label="Editing Status", lines=4, interactive=False
                        )
                        edit_btn.click(
                            use_ai_model, [edit_model, edit_input], edit_output
                        )

            with gr.Tab("Video Generation"):
                gr.Markdown("### ๐ŸŽฌ Video Generation & Editing (18+ models)")
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Text-to-Video")
                        video_text_model = gr.Dropdown(
                            choices=AI_MODELS["Video Generation"]["Text-to-Video"],
                            label="Select Text-to-Video Model",
                            value="ali-vilab/text-to-video-ms-1.7b",
                        )
                        video_text_input = gr.Textbox(
                            label="Video Description",
                            placeholder="Describe the video you want to generate...",
                            lines=3,
                        )
                        video_text_btn = gr.Button("Generate Video from Text")
                        video_text_output = gr.Textbox(
                            label="Video Generation Status", lines=4, interactive=False
                        )
                        video_text_btn.click(
                            use_ai_model,
                            [video_text_model, video_text_input],
                            video_text_output,
                        )

                    with gr.Column():
                        gr.Markdown("### Image-to-Video & Video Editing")
                        video_img_model = gr.Dropdown(
                            choices=AI_MODELS["Video Generation"]["Image-to-Video"],
                            label="Select Image-to-Video Model",
                            value="stabilityai/stable-video-diffusion-img2vid",
                        )
                        video_img_input = gr.Textbox(
                            label="Animation Instructions",
                            placeholder="Describe how to animate the image or edit video...",
                            lines=3,
                        )
                        video_img_btn = gr.Button("Animate Image")
                        video_img_output = gr.Textbox(
                            label="Video Processing Status", lines=4, interactive=False
                        )
                        video_img_btn.click(
                            use_ai_model,
                            [video_img_model, video_img_input],
                            video_img_output,
                        )

            with gr.Tab("AI Teacher & Education"):
                gr.Markdown(
                    "### ๐ŸŽ“ AI Teacher - Math, Coding, Languages & More (20+ models)"
                )
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Math & Science Tutor")
                        math_model = gr.Dropdown(
                            choices=AI_MODELS["AI Teacher & Education"][
                                "Math & Science"
                            ],
                            label="Select Math/Science Model",
                            value="Qwen/Qwen2.5-Math-72B-Instruct",
                        )
                        math_input = gr.Textbox(
                            label="Math/Science Question",
                            placeholder="Ask a math or science question...",
                            lines=3,
                        )
                        math_btn = gr.Button("Solve with AI Teacher")
                        math_output = gr.Textbox(
                            label="Solution & Explanation", lines=6, interactive=False
                        )
                        math_btn.click(
                            use_ai_model, [math_model, math_input], math_output
                        )

                    with gr.Column():
                        gr.Markdown("### Coding Tutor & Language Learning")
                        edu_model = gr.Dropdown(
                            choices=AI_MODELS["AI Teacher & Education"]["Coding Tutor"],
                            label="Select Educational Model",
                            value="Qwen/Qwen2.5-Coder-32B-Instruct",
                        )
                        edu_input = gr.Textbox(
                            label="Learning Request",
                            placeholder="Ask for coding help or language learning...",
                            lines=3,
                        )
                        edu_btn = gr.Button("Learn with AI")
                        edu_output = gr.Textbox(
                            label="Educational Response", lines=6, interactive=False
                        )
                        edu_btn.click(use_ai_model, [edu_model, edu_input], edu_output)

            with gr.Tab("Software Engineer Agent"):
                gr.Markdown(
                    "### ๐Ÿ’ป Software Engineer Agent - Production Code, Architecture & DevOps (27+ models)"
                )
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Code Generation & Development")
                        code_gen_model = gr.Dropdown(
                            choices=AI_MODELS["Software Engineer Agent"][
                                "Code Generation"
                            ],
                            label="Select Code Generation Model",
                            value="Qwen/Qwen2.5-Coder-32B-Instruct",
                        )
                        code_gen_input = gr.Textbox(
                            label="Coding Task",
                            placeholder="Describe the code you need (e.g., 'Create a REST API', 'Build a database schema')...",
                            lines=4,
                        )
                        code_gen_btn = gr.Button("Generate Production Code")
                        code_gen_output = gr.Textbox(
                            label="Generated Code & Documentation",
                            lines=8,
                            interactive=False,
                        )
                        code_gen_btn.click(
                            use_ai_model,
                            [code_gen_model, code_gen_input],
                            code_gen_output,
                        )

                    with gr.Column():
                        gr.Markdown("### Code Review & Analysis")
                        code_review_model = gr.Dropdown(
                            choices=AI_MODELS["Software Engineer Agent"][
                                "Code Analysis & Review"
                            ],
                            label="Select Code Review Model",
                            value="bigcode/starcoder2-15b-instruct-v0.1",
                        )
                        code_review_input = gr.Textbox(
                            label="Code to Review",
                            placeholder="Paste your code for review, optimization, or debugging...",
                            lines=4,
                        )
                        code_review_btn = gr.Button("Review Code")
                        code_review_output = gr.Textbox(
                            label="Code Review & Suggestions",
                            lines=8,
                            interactive=False,
                        )
                        code_review_btn.click(
                            use_ai_model,
                            [code_review_model, code_review_input],
                            code_review_output,
                        )

            with gr.Tab("Audio Processing"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Text-to-Speech (15 models)")
                        tts_model = gr.Dropdown(
                            choices=AI_MODELS["Audio Processing"]["Text-to-Speech"],
                            label="Select TTS Model",
                            value="microsoft/speecht5_tts",
                        )
                        tts_text = gr.Textbox(
                            label="Text to Speak",
                            placeholder="Enter text to convert to speech...",
                            lines=3,
                        )
                        tts_btn = gr.Button("Generate Speech")
                        tts_output = gr.Textbox(
                            label="TTS Status", lines=4, interactive=False
                        )
                        tts_btn.click(use_ai_model, [tts_model, tts_text], tts_output)

                    with gr.Column():
                        gr.Markdown("### Speech-to-Text (15 models)")
                        stt_model = gr.Dropdown(
                            choices=AI_MODELS["Audio Processing"]["Speech-to-Text"],
                            label="Select STT Model",
                            value="openai/whisper-large-v3",
                        )
                        stt_input = gr.Textbox(
                            label="Audio Description",
                            placeholder="Describe audio file to transcribe...",
                            lines=3,
                        )
                        stt_btn = gr.Button("Transcribe Audio")
                        stt_output = gr.Textbox(
                            label="STT Status", lines=4, interactive=False
                        )
                        stt_btn.click(use_ai_model, [stt_model, stt_input], stt_output)

            with gr.Tab("Multimodal & Avatars"):
                with gr.Row():
                    with gr.Column():
                        gr.Markdown("### Vision-Language Models")
                        vl_model = gr.Dropdown(
                            choices=AI_MODELS["Multimodal AI"]["Vision-Language"],
                            label="Select VL Model",
                            value="liuhaotian/llava-v1.6-34b",
                        )
                        vl_input = gr.Textbox(
                            label="Vision-Language Task",
                            placeholder="Describe image analysis or VQA task...",
                            lines=3,
                        )
                        vl_btn = gr.Button("Process with VL Model")
                        vl_output = gr.Textbox(
                            label="VL Response", lines=4, interactive=False
                        )
                        vl_btn.click(use_ai_model, [vl_model, vl_input], vl_output)

                    with gr.Column():
                        gr.Markdown("### Talking Avatars")
                        avatar_model = gr.Dropdown(
                            choices=AI_MODELS["Multimodal AI"]["Talking Avatars"],
                            label="Select Avatar Model",
                            value="Wav2Lip-HD",
                        )
                        avatar_input = gr.Textbox(
                            label="Avatar Generation Task",
                            placeholder="Describe talking avatar or lip-sync task...",
                            lines=3,
                        )
                        avatar_btn = gr.Button("Generate Avatar")
                        avatar_output = gr.Textbox(
                            label="Avatar Status", lines=4, interactive=False
                        )
                        avatar_btn.click(
                            use_ai_model, [avatar_model, avatar_input], avatar_output
                        )

            with gr.Tab("Arabic-English"):
                gr.Markdown("### Arabic-English Interactive Models (12 models)")
                arabic_model = gr.Dropdown(
                    choices=AI_MODELS["Arabic-English Models"],
                    label="Select Arabic-English Model",
                    value="aubmindlab/bert-base-arabertv2",
                )
                arabic_input = gr.Textbox(
                    label="Text (Arabic or English)",
                    placeholder="ุฃุฏุฎู„ ุงู„ู†ุต ุจุงู„ู„ุบุฉ ุงู„ุนุฑุจูŠุฉ ุฃูˆ ุงู„ุฅู†ุฌู„ูŠุฒูŠุฉ / Enter text in Arabic or English...",
                    lines=4,
                )
                arabic_btn = gr.Button("Process Arabic-English")
                arabic_output = gr.Textbox(
                    label="Processing Result", lines=6, interactive=False
                )
                arabic_btn.click(
                    use_ai_model, [arabic_model, arabic_input], arabic_output
                )

    # Services Status Section
    with gr.Row():
        with gr.Column(elem_classes="section"):
            gr.Markdown("## โ˜๏ธ Cloudflare Services Integration")

            with gr.Row():
                with gr.Column():
                    gr.Markdown("### Services Status")
                    services_status = gr.Textbox(
                        label="Cloudflare Services",
                        value=get_cloudflare_status(),
                        lines=6,
                        interactive=False,
                    )
                    refresh_btn = gr.Button("Refresh Status")
                    refresh_btn.click(
                        lambda: get_cloudflare_status(), outputs=services_status
                    )

                with gr.Column():
                    gr.Markdown("### Configuration")
                    gr.HTML(
                        """

                    <div style="background: #f0f8ff; padding: 15px; border-radius: 10px;">

                        <h4>Environment Variables:</h4>

                        <ul>

                            <li><code>CLOUDFLARE_API_TOKEN</code> - API authentication</li>

                            <li><code>CLOUDFLARE_ACCOUNT_ID</code> - Account identifier</li>

                            <li><code>CLOUDFLARE_D1_DATABASE_ID</code> - D1 database</li>

                            <li><code>CLOUDFLARE_R2_BUCKET_NAME</code> - R2 storage</li>

                            <li><code>CLOUDFLARE_KV_NAMESPACE_ID</code> - KV cache</li>

                            <li><code>CLOUDFLARE_DURABLE_OBJECTS_ID</code> - Durable objects</li>

                        </ul>

                    </div>

                    """
                    )

    # Footer Status
    gr.HTML(
        """

    <div style="background: linear-gradient(45deg, #f0f8ff 0%, #e6f3ff 100%); padding: 20px; border-radius: 15px; margin-top: 25px; text-align: center;">

        <h3>๐Ÿ“Š Platform Status</h3>

        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin: 15px 0;">

            <div>โœ… <strong>Authentication:</strong> Active</div>

            <div>๐Ÿง  <strong>AI Models:</strong> 200+ Ready</div>

            <div>๐Ÿ–ผ๏ธ <strong>Image Processing:</strong> Available</div>

            <div>๐ŸŽต <strong>Audio AI:</strong> Enabled</div>

            <div>๐Ÿ‘ค <strong>Face/Avatar:</strong> Ready</div>

            <div>๐ŸŒ <strong>Arabic-English:</strong> Supported</div>

            <div>โ˜๏ธ <strong>Cloudflare:</strong> Configurable</div>

            <div>๐Ÿš€ <strong>Platform:</strong> Production Ready</div>

        </div>

        <p><em>Complete AI Platform successfully deployed on HuggingFace Spaces!</em></p>

    </div>

    """
    )

# Launch the app
app.launch()