File size: 111,336 Bytes
dac7f95
550cbd3
 
 
dac7f95
 
da53044
 
 
 
dac7f95
da53044
dac7f95
da53044
 
 
c340d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac7f95
da53044
 
 
 
 
fc7e1b3
dac7f95
da53044
 
dac7f95
fc7e1b3
 
dac7f95
fc7e1b3
 
 
 
 
 
 
 
 
 
 
da53044
 
fc7e1b3
da53044
 
fc7e1b3
da53044
 
fc7e1b3
da53044
 
fc7e1b3
da53044
 
fc7e1b3
da53044
 
 
 
 
fc7e1b3
 
da53044
 
fc7e1b3
 
 
 
 
 
dac7f95
da53044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
 
 
 
 
 
 
c22fb35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
 
 
c22fb35
75eface
 
c22fb35
75eface
 
 
c22fb35
75eface
 
c22fb35
75eface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac7f95
c22fb35
 
da53044
c22fb35
 
 
 
 
da53044
c22fb35
 
 
 
 
da53044
 
dac7f95
da53044
 
 
 
 
 
 
 
dac7f95
da53044
 
 
 
 
 
 
 
 
 
dac7f95
da53044
 
 
 
 
 
 
dac7f95
da53044
 
 
c22fb35
 
da53044
 
c22fb35
da53044
c22fb35
da53044
 
c22fb35
 
 
 
 
da53044
 
 
 
 
 
 
 
 
c340d5b
 
da53044
 
 
 
 
c22fb35
da53044
c22fb35
 
 
da53044
 
 
c340d5b
da53044
c22fb35
 
 
 
 
da53044
 
 
 
c22fb35
 
 
c340d5b
da53044
 
 
 
 
 
 
 
 
 
 
 
c22fb35
 
da53044
 
 
c22fb35
 
da53044
dac7f95
fc7e1b3
da53044
c340d5b
fc7e1b3
c22fb35
fc7e1b3
da53044
c340d5b
fc7e1b3
c22fb35
fc7e1b3
da53044
c340d5b
fc7e1b3
c22fb35
fc7e1b3
da53044
c340d5b
fc7e1b3
c22fb35
fc7e1b3
da53044
c340d5b
fc7e1b3
c340d5b
fc7e1b3
da53044
c340d5b
da53044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc7e1b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac7f95
da53044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac7f95
da53044
 
 
 
 
 
 
 
 
dac7f95
da53044
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dac7f95
c22fb35
c340d5b
c22fb35
 
c340d5b
 
 
 
 
 
 
 
 
 
 
 
c22fb35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22fb35
4961714
 
 
 
 
 
 
 
 
 
 
c22fb35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eca0010
 
c22fb35
 
 
 
 
 
 
 
 
 
 
35bafdf
a381baf
75eface
35bafdf
75eface
 
35bafdf
75eface
 
 
 
 
35bafdf
d18906c
35bafdf
 
 
d18906c
75eface
35bafdf
 
 
 
a381baf
35bafdf
 
 
 
 
 
 
d18906c
35bafdf
a381baf
35bafdf
 
 
 
 
 
 
d18906c
35bafdf
a381baf
35bafdf
 
 
 
 
 
 
 
a381baf
 
 
35bafdf
 
a381baf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bde9fd4
a381baf
 
bde9fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a381baf
bde9fd4
a381baf
 
 
 
 
bde9fd4
a381baf
 
 
 
 
 
bde9fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a381baf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35bafdf
 
 
 
 
 
 
 
bde9fd4
 
35bafdf
 
4961714
a381baf
 
 
 
 
 
531f1a3
a381baf
 
531f1a3
d18906c
 
a381baf
 
d18906c
 
531f1a3
a381baf
531f1a3
 
a381baf
 
 
 
 
 
 
 
bde9fd4
a381baf
 
 
bde9fd4
a381baf
 
 
bde9fd4
a381baf
 
 
 
bde9fd4
 
 
 
 
 
9577eaa
 
bde9fd4
 
a381baf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be9e986
a381baf
 
 
 
 
 
 
 
 
 
 
 
 
 
9577eaa
a381baf
 
 
 
 
 
 
 
 
 
9577eaa
be9e986
 
a381baf
 
9577eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a381baf
 
 
 
 
 
 
 
 
 
 
 
 
bde9fd4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9577eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35bafdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d18906c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
531f1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
 
 
 
531f1a3
 
75eface
 
 
531f1a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4961714
531f1a3
 
 
 
 
4961714
531f1a3
 
 
 
 
 
 
 
 
4961714
 
531f1a3
 
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22fb35
4961714
 
 
 
c22fb35
4961714
 
c22fb35
4961714
 
 
 
 
 
c22fb35
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22fb35
 
 
4961714
c22fb35
4961714
c22fb35
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22fb35
4961714
c22fb35
 
75eface
4961714
 
 
 
 
 
 
 
 
 
eca0010
4961714
 
 
 
eca0010
4961714
 
 
 
 
 
 
 
 
eca0010
4961714
 
 
 
eca0010
4961714
 
 
 
 
 
eca0010
 
75eface
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
 
4961714
 
 
 
75eface
4961714
 
 
75eface
4961714
 
75eface
4961714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
 
 
 
 
550cbd3
75eface
 
 
550cbd3
 
75eface
550cbd3
 
75eface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22fb35
 
9577eaa
75eface
 
 
 
 
9577eaa
75eface
 
9f4649d
 
 
 
c340d5b
 
 
 
 
9f4649d
a381baf
9f4649d
 
75eface
 
9f4649d
 
75eface
 
35bafdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75eface
 
 
 
8d6823b
 
 
75eface
35bafdf
75eface
 
9f4649d
35bafdf
75eface
 
 
9577eaa
35bafdf
 
 
 
 
75eface
 
8d6823b
75eface
8d6823b
 
 
75eface
 
 
8d6823b
 
 
75eface
 
 
8d6823b
 
 
75eface
 
dac7f95
 
c557e31
 
 
 
 
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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
"""
AdGuardian - AI-Powered Advertising Compliance Agent
Multi-Country · Multi-Language · Three-Stage Analysis · AI-Driven Version
Real AI advertising compliance analysis with professional visualization
"""
import gradio as gr
import asyncio
import aiohttp
import json
import os
import datetime
from typing import Dict, List

# AI Client for content analysis
class AIContentAnalyzer:
    def __init__(self):
        # SiliconFlow (测试用)
        self.siliconflow_api_key = os.getenv("SILICONFLOW_API_KEY", "sk-your-api-key-here")
        self.siliconflow_base_url = "https://api.siliconflow.cn/v1/chat/completions"

        # Nebius (付费,效果更强)
        self.nebius_api_key = os.getenv("NEBIUS_API_KEY", "your-nebius-api-key")
        self.nebius_base_url = "https://api.studio.nebius.com/v1/chat/completions"

        # 默认使用SiliconFlow的免费模型
        self.model = "Qwen/Qwen3-8B"
        self.api_key = self.siliconflow_api_key
        self.base_url = self.siliconflow_base_url

    def set_model(self, model: str):
        """设置模型并选择对应的API"""
        self.model = model

        # SiliconFlow模型
        siliconflow_models = ["Qwen/Qwen3-8B"]

        # Nebius模型
        nebius_models = [
            "deepseek-ai/DeepSeek-V3-0324",
            "deepseek-ai/DeepSeek-R1-0528",
            "Qwen/Qwen3-235B-A22B",
            "google/gemma-3-27b-it"
        ]

        if model in siliconflow_models:
            self.api_key = self.siliconflow_api_key
            self.base_url = self.siliconflow_base_url
        elif model in nebius_models:
            self.api_key = self.nebius_api_key
            self.base_url = self.nebius_base_url
        else:
            # 默认使用SiliconFlow
            self.api_key = self.siliconflow_api_key
            self.base_url = self.siliconflow_base_url
    
    async def analyze_content(self, text: str, keywords: List[str] = None) -> Dict:
        """AI-powered content analysis"""
        keywords_str = ", ".join(keywords) if keywords else "无"
        
        prompt = f"""
你是专业的内容审核专家,请对以下文本进行全面审核分析。

文本内容:{text}
关键词:{keywords_str}

参考示例案例的分析方式:
原始文本:生活需要妆,美丽不打烊!但凡精制的女生,都不会放弃自我管理。脸蛋只有一张,精制一点又何妨?用了这款特效面霜,我的肌肤就像剥了壳的鸡蛋一样立刻变白,色斑色块全部消失,仿佛皮肤吃了仙丹一样,一夜见效,完全无副作用,效果简直绝绝子!

分析结果:
- 错别字标注:"精制" 应为 "精致"(2处)
- 违规内容标注:1处违规(使用了"仙丹"这一封建迷信类用语,属于违反公序良俗类违规)
- 虚假内容标注:4处虚假,夸大及绝对化表述
  1. "色斑全部消失" 表述过于绝对,不符合实际护肤效果
  2. "一夜见效"属于夸大描述,不符合护肤效果
  3. "立刻变白"使用过于夸张的比喻,且"立刻"一词使美白效果的描述过于绝对
  4. "完全无副作用"不符合实际情况,任何护肤品都不能保证绝对无副作用
- 不当广告用语:绝绝子等网络用语不适合正式广告

请按照这个详细程度分析给定文本,以JSON格式返回:
{{
    "typos": [
        {{"original": "错误词", "correct": "正确词", "position": 位置, "reason": "详细错误原因"}}
    ],
    "violations": [
        {{"content": "具体违规内容", "type": "违规类型", "position": 位置, "reason": "详细违规原因", "suggestion": "具体修改建议"}}
    ],
    "fake_content": [
        {{"content": "具体虚假内容", "type": "虚假类型", "position": 位置, "reason": "详细分析原因", "suggestion": "具体修改建议"}}
    ],
    "inappropriate_ads": [
        {{"word": "不当用词", "position": 位置, "reason": "详细违规原因", "suggestion": "具体替代建议"}}
    ],
    "keywords_analysis": [
        {{"keyword": "关键词", "frequency": 次数, "positions": [位置列表], "context": "使用语境分析", "assessment": "使用评价"}}
    ],
    "overall_assessment": {{
        "risk_level": "低/中/高",
        "total_issues": 问题总数,
        "main_concerns": ["主要问题1", "主要问题2"],
        "recommendations": ["具体建议1", "具体建议2"],
        "revised_text": "修改后的文本建议"
    }}
}}

要求:
1. 每个问题都要给出具体位置和详细分析
2. 建议要具体可操作
3. 分析要深入,不能只是简单列举
4. 必须包含修改后的文本建议
"""
        
        try:
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }
            
            data = {
                "model": self.model,
                "messages": [
                    {"role": "system", "content": "你是专业的内容审核专家,擅长识别各类内容问题并提供专业建议。"},
                    {"role": "user", "content": prompt}
                ],
                "temperature": 0.1,
                "max_tokens": 2000
            }
            
            async with aiohttp.ClientSession() as session:
                async with session.post(self.base_url, headers=headers, json=data) as response:
                    if response.status == 200:
                        result = await response.json()
                        ai_response = result["choices"][0]["message"]["content"]
                        
                        # 尝试解析JSON
                        try:
                            # 清理AI返回的内容
                            if "```json" in ai_response:
                                ai_response = ai_response.split("```json")[1].split("```")[0]
                            elif "```" in ai_response:
                                ai_response = ai_response.split("```")[1].split("```")[0]
                            
                            analysis_result = json.loads(ai_response.strip())
                            return analysis_result
                        except json.JSONDecodeError:
                            # 如果JSON解析失败,返回基础分析
                            return self._create_fallback_analysis(text, keywords)
                    else:
                        return self._create_fallback_analysis(text, keywords)
                        
        except Exception as e:
            print(f"AI analysis error: {e}")
            return self._create_fallback_analysis(text, keywords)

    async def analyze_content_with_options(self, text: str, keywords: List[str] = None, country: str = "中国", language: str = "简体中文") -> Dict:
        """带国家和语言选项的AI内容分析"""
        keywords_str = ", ".join(keywords) if keywords else "无"

        # 根据国家调整审核标准
        country_standards = {
            "China": "中国广告法和相关法规",
            "USA": "美国FTC广告标准",
            "UK": "英国ASA广告标准",
            "Japan": "日本景品表示法",
            "Korea": "韩国公正交易委员会标准",
            "Singapore": "新加坡CCCS标准",
            "Malaysia": "马来西亚广告标准",
            "Other": "国际通用广告标准"
        }

        country_names = {
            "China": "中国",
            "USA": "美国",
            "UK": "英国",
            "Japan": "日本",
            "Korea": "韩国",
            "Singapore": "新加坡",
            "Malaysia": "马来西亚",
            "Other": "其他地区"
        }

        standard = country_standards.get(country, "国际通用广告标准")
        country_cn = country_names.get(country, country)

        prompt = f"""
你是专业的内容审核专家,请根据{country_cn}{standard}对以下文本进行全面审核分析。

文本内容:{text}
关键词:{keywords_str}
审核地区:{country_cn}
回答语言:{language}

请按照{country_cn}的法规标准进行分析,并用{language}回答。

参考示例案例的分析方式:
原始文本:生活需要妆,美丽不打烊!但凡精制的女生,都不会放弃自我管理。脸蛋只有一张,精制一点又何妨?用了这款特效面霜,我的肌肤就像剥了壳的鸡蛋一样立刻变白,色斑色块全部消失,仿佛皮肤吃了仙丹一样,一夜见效,完全无副作用,效果简直绝绝子!

分析结果:
- 错别字标注:"精制" 应为 "精致"(2处)
- 违规内容标注:1处违规(使用了"仙丹"这一封建迷信类用语,属于违反公序良俗类违规)
- 虚假内容标注:4处虚假,夸大及绝对化表述
  1. "色斑全部消失" 表述过于绝对,不符合实际护肤效果
  2. "一夜见效"属于夸大描述,不符合护肤效果
  3. "立刻变白"使用过于夸张的比喻,且"立刻"一词使美白效果的描述过于绝对
  4. "完全无副作用"不符合实际情况,任何护肤品都不能保证绝对无副作用
- 不当广告用语:绝绝子等网络用语不适合正式广告

请按照这个详细程度分析给定文本,以JSON格式返回:
{{
    "typos": [
        {{"original": "错误词", "correct": "正确词", "position": 位置, "reason": "详细错误原因"}}
    ],
    "violations": [
        {{"content": "具体违规内容", "type": "违规类型", "position": 位置, "reason": "详细违规原因", "suggestion": "具体修改建议"}}
    ],
    "fake_content": [
        {{"content": "具体虚假内容", "type": "虚假类型", "position": 位置, "reason": "详细分析原因", "suggestion": "具体修改建议"}}
    ],
    "inappropriate_ads": [
        {{"word": "不当用词", "position": 位置, "reason": "详细违规原因", "suggestion": "具体替代建议"}}
    ],
    "keywords_analysis": [
        {{"keyword": "关键词", "frequency": 次数, "positions": [位置列表], "context": "使用语境分析", "assessment": "使用评价"}}
    ],
    "overall_assessment": {{
        "risk_level": "低/中/高",
        "total_issues": 问题总数,
        "main_concerns": ["主要问题1", "主要问题2"],
        "recommendations": ["具体建议1", "具体建议2"],
        "revised_text": "修改后的文本建议",
        "country_specific_notes": "针对{country}的特殊说明"
    }}
}}

要求:
1. 每个问题都要给出具体位置和详细分析
2. 建议要具体可操作
3. 分析要深入,不能只是简单列举
4. 必须包含修改后的文本建议
5. 考虑{country}的特殊法规要求
6. 使用{language}回答
"""

        try:
            headers = {
                "Authorization": f"Bearer {self.api_key}",
                "Content-Type": "application/json"
            }

            data = {
                "model": self.model,
                "messages": [
                    {"role": "system", "content": f"你是专业的内容审核专家,擅长识别各类内容问题并提供专业建议。请根据{country}的法规标准进行分析,并用{language}回答。"},
                    {"role": "user", "content": prompt}
                ],
                "temperature": 0.1,
                "max_tokens": 3000
            }

            async with aiohttp.ClientSession() as session:
                async with session.post(self.base_url, headers=headers, json=data) as response:
                    if response.status == 200:
                        result = await response.json()
                        ai_response = result["choices"][0]["message"]["content"]

                        # 尝试解析JSON
                        try:
                            # 清理AI返回的内容
                            if "```json" in ai_response:
                                ai_response = ai_response.split("```json")[1].split("```")[0]
                            elif "```" in ai_response:
                                ai_response = ai_response.split("```")[1].split("```")[0]

                            analysis_result = json.loads(ai_response.strip())
                            return analysis_result
                        except json.JSONDecodeError:
                            # 如果JSON解析失败,返回基础分析
                            return self._create_fallback_analysis(text, keywords, country, language)
                    else:
                        return self._create_fallback_analysis(text, keywords, country, language)

        except Exception as e:
            print(f"AI analysis error: {e}")
            return self._create_fallback_analysis(text, keywords, country, language)
    
    def _create_fallback_analysis(self, text: str, keywords: List[str] = None, country: str = "China", language: str = "简体中文") -> Dict:
        """备用分析方法 - 简单返回无法分析的提示"""
        return {
            "typos": [],
            "violations": [],
            "fake_content": [],
            "inappropriate_ads": [],
            "keywords_analysis": [],
            "overall_assessment": {
                "risk_level": "未知",
                "total_issues": 0,
                "main_concerns": ["AI分析服务暂时不可用"],
                "recommendations": ["请稍后重试或检查网络连接"],
                "revised_text": text
            }
        }

# 全局AI分析器
ai_analyzer = AIContentAnalyzer()

def generate_hanyu_xinxie_cards(analysis_result: Dict, original_text: str) -> str:
    """生成汉语新解风格的SVG卡片"""
    overall = analysis_result.get("overall_assessment", {})
    total_issues = overall.get("total_issues", 0)
    risk_level = overall.get("risk_level", "低")
    
    # 莫兰迪色系配色
    colors = {
        "primary": "#B6B5A7",      # 莫兰迪灰褐色
        "secondary": "#9A8F8F",    # 莫兰迪灰棕色  
        "accent": "#C5B4A0",       # 莫兰迪淡棕色
        "background": "#F2EDE9",   # 莫兰迪浅米色
        "text": "#5B5B5B",         # 莫兰迪深灰色
        "light_text": "#8C8C8C",   # 莫兰迪中灰色
        "divider": "#D1CBC3"       # 莫兰迪浅灰色
    }
    
    # 根据风险等级调整颜色
    if risk_level == "高":
        colors["secondary"] = "#B85450"  # 深红色
        colors["accent"] = "#D4776B"     # 浅红色
    elif risk_level == "中":
        colors["secondary"] = "#C4965A"  # 橙色
        colors["accent"] = "#D4A574"     # 浅橙色
    
    # 生成主要摘要卡片
    main_card = f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 20px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            width: 100%;
            background-color: {colors['background']};
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            position: relative;
        ">
            <!-- 标题区域 -->
            <div style="
                background-color: {colors['secondary']}; 
                color: {colors['background']}; 
                padding: 20px; 
                text-align: left;
            ">
                <h1 style="font-size: 28px; margin: 0; font-weight: 700;">🛡️ AI Content Audit Report</h1>
                <p style="font-size: 16px; margin: 8px 0 0 0; opacity: 0.9;">China · Simplified Chinese · Hanyu Xinxie Style</p>
            </div>
            
            <!-- 内容区域 -->
            <div style="padding: 25px 20px;">
                <!-- 主要统计 -->
                <div style="text-align: left; margin-bottom: 25px;">
                    <div style="
                        font-size: 48px;
                        color: {colors['text']};
                        margin-bottom: 12px;
                        font-weight: bold;
                        position: relative;
                    ">
                        {total_issues} Issues Found
                        <div style="
                            position: absolute;
                            left: 0;
                            bottom: -6px;
                            width: 80px;
                            height: 4px;
                            background-color: {colors['accent']};
                        "></div>
                    </div>
                    <div style="
                        font-size: 20px;
                        color: {colors['light_text']};
                        margin: 15px 0;
                    ">Risk Level: {risk_level}</div>
                </div>
                
                <!-- 分隔线 -->
                <div style="
                    width: 100%; 
                    height: 1px; 
                    background-color: {colors['divider']}; 
                    margin: 20px 0;
                "></div>
                
                <!-- AI分析结果 -->
                <div style="
                    font-size: 18px;
                    line-height: 1.8;
                    text-align: left;
                ">
                    <div style="
                        padding-left: 20px;
                        border-left: 4px solid {colors['accent']};
                    ">"""
    
    # 添加具体问题类型和详细信息
    if analysis_result.get("typos"):
        main_card += f'<p style="margin: 12px 0; color: {colors["text"]}; font-weight: bold; font-size: 18px;">📝 Typos: {len(analysis_result["typos"])} found</p>'
        for typo in analysis_result["typos"][:2]:  # 显示前2个
            main_card += f'<p style="margin: 8px 0 8px 20px; color: {colors["light_text"]}; font-size: 16px;">"{typo.get("original", "")}" → "{typo.get("correct", "")}"</p>'

    if analysis_result.get("violations"):
        main_card += f'<p style="margin: 12px 0; color: {colors["text"]}; font-weight: bold; font-size: 18px;">⚠️ Violations: {len(analysis_result["violations"])} found</p>'
        for violation in analysis_result["violations"][:2]:  # 显示前2个
            main_card += f'<p style="margin: 8px 0 8px 20px; color: {colors["light_text"]}; font-size: 16px;">"{violation.get("content", "")}" - {violation.get("type", "")}</p>'

    if analysis_result.get("fake_content"):
        main_card += f'<p style="margin: 12px 0; color: {colors["text"]}; font-weight: bold; font-size: 18px;">🚫 Fake Content: {len(analysis_result["fake_content"])} found</p>'
        for fake in analysis_result["fake_content"][:2]:  # 显示前2个
            main_card += f'<p style="margin: 8px 0 8px 20px; color: {colors["light_text"]}; font-size: 16px;">"{fake.get("content", "")}" - {fake.get("type", "")}</p>'

    if analysis_result.get("inappropriate_ads"):
        main_card += f'<p style="margin: 12px 0; color: {colors["text"]}; font-weight: bold; font-size: 18px;">📢 Inappropriate Ads: {len(analysis_result["inappropriate_ads"])} found</p>'
        for ad in analysis_result["inappropriate_ads"][:2]:  # 显示前2个
            main_card += f'<p style="margin: 8px 0 8px 20px; color: {colors["light_text"]}; font-size: 16px;">"{ad.get("word", "")}" - {ad.get("reason", "")}</p>'

    if analysis_result.get("keywords_analysis"):
        main_card += f'<p style="margin: 12px 0; color: {colors["text"]}; font-weight: bold; font-size: 18px;">🔍 Keywords: {len(analysis_result["keywords_analysis"])} analyzed</p>'
        for kw in analysis_result["keywords_analysis"][:2]:  # 显示前2个
            main_card += f'<p style="margin: 8px 0 8px 20px; color: {colors["light_text"]}; font-size: 16px;">"{kw.get("keyword", "")}" - appears {kw.get("frequency", 0)} times</p>'

    if total_issues == 0:
        main_card += f'<p style="margin: 12px 0; color: {colors["light_text"]}; font-size: 18px;">✅ No obvious issues found</p>'
    
    main_card += f"""
                    </div>
                </div>
                
                <!-- AI建议 -->
                <div style="
                    margin-top: 20px; 
                    padding: 15px; 
                    background-color: rgba(255,255,255,0.5); 
                    border-radius: 10px;
                    border-left: 4px solid {colors['accent']};
                ">
                    <h4 style="margin: 0 0 10px 0; color: {colors['text']}; font-size: 14px;">🤖 AI建议</h4>"""
    
    recommendations = overall.get("recommendations", ["内容表述规范"])
    for rec in recommendations[:2]:  # 最多显示2个建议
        main_card += f'<p style="margin: 5px 0; color: {colors["light_text"]}; font-size: 13px;">• {rec}</p>'
    
    main_card += f"""
                </div>
                
                <!-- 中式印章风格装饰 -->
                <div style="
                    text-align: center; 
                    margin-top: 25px; 
                    padding: 10px; 
                    border: 2px solid {colors['accent']}; 
                    border-radius: 50%; 
                    width: 70px; 
                    height: 70px; 
                    margin-left: auto; 
                    margin-right: auto;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                ">
                    <span style="
                        font-size: 18px; 
                        color: {colors['secondary']}; 
                        font-weight: bold;
                    ">AI审核</span>
                </div>
            </div>
            
            <!-- 背景装饰文字 -->
            <div style="
                position: absolute; 
                font-size: 120px; 
                color: rgba(182, 181, 167, 0.05); 
                top: 50%; 
                left: 50%; 
                transform: translate(-50%, -50%); 
                font-weight: bold;
                pointer-events: none;
                z-index: 0;
            ">AI</div>
        </div>
    </div>
    """

    # 生成详细分析卡片
    detail_card = ""
    if total_issues > 0:
        detail_card = generate_detail_analysis_card(analysis_result, colors)

    # 生成修改建议卡片
    revision_card = ""
    overall = analysis_result.get("overall_assessment", {})
    if overall.get("revised_text"):
        revision_card = generate_revision_card(analysis_result, colors)

    return main_card + detail_card + revision_card

def generate_detail_analysis_card(analysis_result: Dict, colors: Dict) -> str:
    """生成详细分析卡片"""
    detail_card = f"""
    <div style="
        display: flex;
        justify-content: center;
        padding: 20px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 15px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 20px;
    ">
        <div style="
            width: 500px;
            background-color: {colors['background']};
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            position: relative;
        ">
            <!-- 标题区域 -->
            <div style="
                background-color: {colors['secondary']};
                color: {colors['background']};
                padding: 20px;
                text-align: left;
            ">
                <h2 style="font-size: 18px; margin: 0; font-weight: 700;">📋 详细分析报告</h2>
                <p style="font-size: 12px; margin: 5px 0 0 0; opacity: 0.9;">Detailed Analysis Report</p>
            </div>

            <!-- 内容区域 -->
            <div style="padding: 25px 20px;">
    """

    # 错别字详细分析
    if analysis_result.get("typos"):
        detail_card += f"""
                <div style="margin-bottom: 20px;">
                    <h3 style="color: {colors['text']}; margin-bottom: 10px; font-size: 16px;">📝 错别字检测</h3>
        """
        for i, typo in enumerate(analysis_result["typos"], 1):
            detail_card += f"""
                    <div style="
                        background-color: rgba(255,255,255,0.5);
                        padding: 12px;
                        border-radius: 8px;
                        margin-bottom: 8px;
                        border-left: 4px solid {colors['accent']};
                    ">
                        <p style="margin: 0; color: {colors['text']}; font-size: 14px;">
                            <strong>{i}. "{typo.get('original', '')}" → "{typo.get('correct', '')}"</strong>
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['light_text']}; font-size: 12px;">
                            位置: {typo.get('position', '未知')} | 原因: {typo.get('reason', '')}
                        </p>
                    </div>
            """
        detail_card += "</div>"

    # 违规内容详细分析
    if analysis_result.get("violations"):
        detail_card += f"""
                <div style="margin-bottom: 20px;">
                    <h3 style="color: {colors['text']}; margin-bottom: 10px; font-size: 16px;">⚠️ 违规内容检测</h3>
        """
        for i, violation in enumerate(analysis_result["violations"], 1):
            detail_card += f"""
                    <div style="
                        background-color: rgba(255,255,255,0.5);
                        padding: 12px;
                        border-radius: 8px;
                        margin-bottom: 8px;
                        border-left: 4px solid #B85450;
                    ">
                        <p style="margin: 0; color: {colors['text']}; font-size: 14px;">
                            <strong>{i}. "{violation.get('content', '')}"</strong>
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['light_text']}; font-size: 12px;">
                            类型: {violation.get('type', '')} | 位置: {violation.get('position', '未知')}
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['light_text']}; font-size: 12px;">
                            原因: {violation.get('reason', '')}
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['text']}; font-size: 12px;">
                            建议: {violation.get('suggestion', '')}
                        </p>
                    </div>
            """
        detail_card += "</div>"

    # 虚假内容详细分析
    if analysis_result.get("fake_content"):
        detail_card += f"""
                <div style="margin-bottom: 20px;">
                    <h3 style="color: {colors['text']}; margin-bottom: 10px; font-size: 16px;">🚫 虚假内容检测</h3>
        """
        for i, fake in enumerate(analysis_result["fake_content"], 1):
            detail_card += f"""
                    <div style="
                        background-color: rgba(255,255,255,0.5);
                        padding: 12px;
                        border-radius: 8px;
                        margin-bottom: 8px;
                        border-left: 4px solid #D4776B;
                    ">
                        <p style="margin: 0; color: {colors['text']}; font-size: 14px;">
                            <strong>{i}. "{fake.get('content', '')}"</strong>
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['light_text']}; font-size: 12px;">
                            类型: {fake.get('type', '')} | 位置: {fake.get('position', '未知')}
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['light_text']}; font-size: 12px;">
                            原因: {fake.get('reason', '')}
                        </p>
                        <p style="margin: 5px 0 0 0; color: {colors['text']}; font-size: 12px;">
                            建议: {fake.get('suggestion', '')}
                        </p>
                    </div>
            """
        detail_card += "</div>"

    detail_card += """
            </div>
        </div>
    </div>
    """

    return detail_card

def generate_revision_card(analysis_result: Dict, colors: Dict) -> str:
    """生成修改建议卡片"""
    overall = analysis_result.get("overall_assessment", {})
    revised_text = overall.get("revised_text", "")

    revision_card = f"""
    <div style="
        display: flex;
        justify-content: center;
        padding: 20px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 15px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 20px;
    ">
        <div style="
            width: 500px;
            background-color: {colors['background']};
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
            position: relative;
        ">
            <!-- 标题区域 -->
            <div style="
                background-color: #4A7C59;
                color: {colors['background']};
                padding: 20px;
                text-align: left;
            ">
                <h2 style="font-size: 18px; margin: 0; font-weight: 700;">✨ 修改建议</h2>
                <p style="font-size: 12px; margin: 5px 0 0 0; opacity: 0.9;">Revision Suggestions</p>
            </div>

            <!-- 内容区域 -->
            <div style="padding: 25px 20px;">
                <div style="
                    background-color: rgba(74, 124, 89, 0.1);
                    padding: 15px;
                    border-radius: 10px;
                    border-left: 4px solid #4A7C59;
                ">
                    <h4 style="margin: 0 0 10px 0; color: {colors['text']}; font-size: 14px;">📝 修改后文本:</h4>
                    <p style="margin: 0; color: {colors['text']}; font-size: 14px; line-height: 1.6;">
                        {revised_text}
                    </p>
                </div>
            </div>
        </div>
    </div>
    """

    return revision_card

def generate_error_card(error_msg: str) -> str:
    """生成错误信息卡片"""
    return f"""
    <div style="
        display: flex; 
        justify-content: center; 
        padding: 20px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 15px;
        font-family: 'Microsoft YaHei', sans-serif;
    ">
        <div style="
            width: 350px; 
            background-color: #F2EDE9; 
            border-radius: 20px; 
            box-shadow: 0 20px 40px rgba(0,0,0,0.1); 
            padding: 30px;
            text-align: center;
        ">
            <h2 style="color: #B85450; margin-bottom: 15px;">⚠️ 分析出错</h2>
            <p style="color: #5B5B5B; margin-bottom: 20px;">AI分析过程中遇到问题:</p>
            <div style="
                background-color: rgba(184, 84, 80, 0.1); 
                padding: 15px; 
                border-radius: 10px; 
                border-left: 4px solid #B85450;
                text-align: left;
            ">
                <code style="color: #B85450; font-size: 12px;">{error_msg}</code>
            </div>
            <p style="color: #8C8C8C; margin-top: 15px; font-size: 14px;">请稍后重试或检查网络连接</p>
        </div>
    </div>
    """

def comprehensive_text_audit(text, keywords=""):
    """
    AI-powered comprehensive text audit with SVG visualization
    """
    if not text.strip():
        return "❌ Please enter text content"
    
    # Parse keywords
    keyword_list = [k.strip() for k in keywords.split(",") if k.strip()] if keywords else []
    
    try:
        # 使用异步事件循环进行AI分析
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        
        try:
            # 执行AI分析
            analysis_result = loop.run_until_complete(
                ai_analyzer.analyze_content(text, keyword_list)
            )
        finally:
            loop.close()
        
        # 生成汉语新解风格的SVG卡片
        svg_cards = generate_hanyu_xinxie_cards(analysis_result, text)
        
        return svg_cards
        
    except Exception as e:
        print(f"Analysis error: {e}")
        # 返回错误信息的SVG卡片
        return generate_error_card(str(e))

# 真正的流式输出AI分析
async def streaming_ai_analysis(text: str, keywords: List[str], country: str, language: str, model: str = "Qwen/Qwen3-8B (Free - SiliconFlow)"):
    """流式AI分析生成器"""
    ai = AIContentAnalyzer()

    # 解析模型名称
    model_mapping = {
        "Qwen/Qwen3-8B (Free - SiliconFlow)": "Qwen/Qwen3-8B",
        "deepseek-ai/DeepSeek-V3-0324 (Paid - Nebius)": "deepseek-ai/DeepSeek-V3-0324",
        "deepseek-ai/DeepSeek-R1-0528 (Paid - Nebius)": "deepseek-ai/DeepSeek-R1-0528",
        "Qwen/Qwen3-235B-A22B (Paid - Nebius)": "Qwen/Qwen3-235B-A22B",
        "google/gemma-3-27b-it (Paid - Nebius, Vision)": "google/gemma-3-27b-it"
    }

    actual_model = model_mapping.get(model, "Qwen/Qwen3-8B")
    ai.set_model(actual_model)  # 设置选择的模型

    # 构建prompt
    country_standards = {
        "China": "中国广告法和相关法规",
        "USA": "美国FTC广告标准",
        "UK": "英国ASA广告标准",
        "Japan": "日本景品表示法",
        "Korea": "韩国公正交易委员会标准",
        "Singapore": "新加坡CCCS标准",
        "Malaysia": "马来西亚广告标准",
        "Other": "国际通用广告标准"
    }

    country_names = {
        "China": "中国",
        "USA": "美国",
        "UK": "英国",
        "Japan": "日本",
        "Korea": "韩国",
        "Singapore": "新加坡",
        "Malaysia": "马来西亚",
        "Other": "其他地区"
    }

    standard = country_standards.get(country, "国际通用广告标准")
    country_cn = country_names.get(country, country)
    keywords_str = ", ".join(keywords) if keywords else "无"

    prompt = f"""
你是专业的内容审核专家,请根据{country_cn}{standard}对以下文本进行全面审核分析。

文本内容:{text}
关键词:{keywords_str}
审核地区:{country_cn}
回答语言:{language}

请按照以下JSON格式返回分析结果:
{{
    "reasoning_content": "详细的推理过程和分析思路",
    "sentence_analysis": [
        {{
            "sentence": "具体句子内容",
            "risk_level": "green/yellow/orange/red",
            "issues": ["具体问题1", "具体问题2"],
            "explanation": "为什么认为有问题的详细解释"
        }}
    ],
    "revised_text": "修改后的完整文本",
    "summary": {{
        "total_issues": 问题总数,
        "risk_level": "整体风险等级",
        "main_concerns": ["主要问题1", "主要问题2"]
    }}
}}

风险等级说明:
- green: 无问题,表述规范
- yellow: 轻微问题,建议优化
- orange: 中等问题,需要修改
- red: 严重问题,必须修改

请确保:
1. 每个句子都要分析并标注风险等级
2. 问题解释要具体明确
3. 修改后的文本要保持原意但符合法规
4. 返回标准的JSON格式
"""

    try:
        headers = {
            "Authorization": f"Bearer {ai.api_key}",
            "Content-Type": "application/json"
        }

        data = {
            "model": ai.model,
            "messages": [
                {"role": "system", "content": f"你是专业的内容审核专家,请根据{country_cn}的法规标准进行分析,并用{language}回答。"},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.1,
            "max_tokens": 3000,
            "stream": True  # 启用流式输出
        }

        async with aiohttp.ClientSession() as session:
            async with session.post(ai.base_url, headers=headers, json=data) as response:
                if response.status == 200:
                    async for line in response.content:
                        if line:
                            line_str = line.decode('utf-8').strip()
                            if line_str.startswith('data: '):
                                data_str = line_str[6:]
                                if data_str == '[DONE]':
                                    break
                                try:
                                    chunk = json.loads(data_str)
                                    if 'choices' in chunk and len(chunk['choices']) > 0:
                                        delta = chunk['choices'][0].get('delta', {})
                                        if 'content' in delta and delta['content']:
                                            yield str(delta['content'])
                                except json.JSONDecodeError:
                                    continue
                else:
                    yield "API调用失败,使用备用分析..."
                    # 返回备用分析
                    fallback = ai._create_fallback_analysis(text, keywords, country, language)
                    yield f"分析完成:发现{fallback['overall_assessment']['total_issues']}个问题"

    except Exception as e:
        yield f"分析出错:{str(e)}"

# 三次渐进式输出的审核函数 - 缓存结果并支持切换
def comprehensive_text_audit_streaming(text, keywords="", country="China", language="简体中文", model="Qwen/Qwen3-8B (Free - SiliconFlow)"):
    """
    三次渐进式输出的AI内容审核 - 缓存所有阶段结果
    """
    if not text.strip():
        yield ("❌ Please enter text content", "", "", "")
        return

    # Parse keywords
    keyword_list = [k.strip() for k in keywords.split(",") if k.strip()] if keywords else []

    # 初始化对话历史和结果缓存
    messages = []
    stage1_result = ""
    stage2_result = ""
    stage3_result = ""

    try:
        # 第一阶段:基础分析
        yield ("🔍 Stage 1: Basic Analysis in progress...", "", "", "")

        stage1_final = None
        for chunk in perform_streaming_analysis(text, keyword_list, country, language, model, messages, stage=1):
            stage1_final = chunk
            yield (chunk, "", "", "")

        stage1_result = stage1_final

        # 第二阶段:详细标注
        yield (stage1_result, "🎨 Stage 2: Detailed Annotation in progress...", "", "")

        stage2_final = None
        for chunk in perform_streaming_analysis(text, keyword_list, country, language, model, messages, stage=2):
            stage2_final = chunk
            yield (stage1_result, chunk, "", "")

        stage2_result = stage2_final

        # 第三阶段:修改建议
        yield (stage1_result, stage2_result, "✨ Stage 3: Revision Suggestions in progress...", "")

        stage3_final = None
        for chunk in perform_streaming_analysis(text, keyword_list, country, language, model, messages, stage=3):
            stage3_final = chunk
            yield (stage1_result, stage2_result, chunk, "")

        stage3_result = stage3_final

        # 生成摘要界面
        summary_interface = generate_analysis_summary()
        yield (stage1_result, stage2_result, stage3_result, summary_interface)

    except Exception as e:
        print(f"Analysis error: {e}")
        error_msg = generate_error_card(str(e))
        yield (error_msg, "", "", "")

# 执行流式分析
def perform_streaming_analysis(text: str, keywords: List[str], country: str, language: str, model: str, messages: list, stage: int):
    """执行真正的流式AI分析"""

    # 解析模型名称和API配置
    model_mapping = {
        "Qwen/Qwen3-8B (Free - SiliconFlow)": {
            "model": "Qwen/Qwen3-8B",
            "api_key": os.getenv("SILICONFLOW_API_KEY", "sk-your-api-key-here"),
            "base_url": "https://api.siliconflow.cn/v1/chat/completions"
        },
        "deepseek-ai/DeepSeek-V3-0324 (Paid - Nebius)": {
            "model": "deepseek-ai/DeepSeek-V3-0324",
            "api_key": os.getenv("NEBIUS_API_KEY", "your-nebius-api-key"),
            "base_url": "https://api.studio.nebius.com/v1/chat/completions"
        },
        "deepseek-ai/DeepSeek-R1-0528 (Paid - Nebius)": {
            "model": "deepseek-ai/DeepSeek-R1-0528",
            "api_key": os.getenv("NEBIUS_API_KEY", "your-nebius-api-key"),
            "base_url": "https://api.studio.nebius.com/v1/chat/completions"
        },
        "Qwen/Qwen3-235B-A22B (Paid - Nebius)": {
            "model": "Qwen/Qwen3-235B-A22B",
            "api_key": os.getenv("NEBIUS_API_KEY", "your-nebius-api-key"),
            "base_url": "https://api.studio.nebius.com/v1/chat/completions"
        },
        "google/gemma-3-27b-it (Paid - Nebius, Vision)": {
            "model": "google/gemma-3-27b-it",
            "api_key": os.getenv("NEBIUS_API_KEY", "your-nebius-api-key"),
            "base_url": "https://api.studio.nebius.com/v1/chat/completions"
        }
    }

    model_config = model_mapping.get(model, model_mapping["Qwen/Qwen3-8B (Free - SiliconFlow)"])

    # 构建国家和标准信息
    country_standards = {
        "China": "中国广告法和相关法规",
        "USA": "美国FTC广告标准",
        "UK": "英国ASA广告标准",
        "Japan": "日本景品表示法",
        "Korea": "韩国公正交易委员会标准",
        "Singapore": "新加坡CCCS标准",
        "Malaysia": "马来西亚广告标准",
        "Other": "国际通用广告标准"
    }

    country_names = {
        "China": "中国",
        "USA": "美国",
        "UK": "英国",
        "Japan": "日本",
        "Korea": "韩国",
        "Singapore": "新加坡",
        "Malaysia": "马来西亚",
        "Other": "其他地区"
    }

    standard = country_standards.get(country, "国际通用广告标准")
    country_cn = country_names.get(country, country)
    keywords_str = ", ".join(keywords) if keywords else "无"

    # 根据阶段构建不同的prompt
    if stage == 1:
        stage_title = "🔍 Stage 1: Basic Analysis"
        user_prompt = f"""
你是专业的内容审核专家,请根据{country_cn}{standard}对以下文本进行初步分析。

文本内容:{text}
关键词:{keywords_str}
审核地区:{country_cn}
回答语言:{language}

请进行基础分析,包括:
1. 整体风险评估
2. 主要问题识别
3. 法规符合性初判

请用{language}回答,提供清晰的分析结论。
"""

    elif stage == 2:
        stage_title = "🎨 Stage 2: Detailed Annotation"
        user_prompt = f"""
基于前面的分析,现在请对文本进行详细的句子级标注分析,并生成HTML格式的标注版本。

请为每个句子标注风险等级:
- 绿色(#4CAF50):无问题,表述规范
- 黄色(#FFC107):轻微问题,建议优化
- 橙色(#FF9800):中等问题,需要修改
- 红色(#F44336):严重问题,必须修改

请直接返回HTML代码,格式如下:
```html
<div style="background-color: rgba(255,255,255,0.5); padding: 20px; border-radius: 10px;">
    <div style="margin: 15px 0; padding: 15px; border-left: 5px solid #4CAF50; background-color: rgba(76, 175, 80, 0.1); border-radius: 8px;">
        <p style="color: #333; font-size: 18px; line-height: 1.6; margin: 0 0 10px 0; font-weight: 500;">句子内容</p>
        <div style="color: #666; font-size: 14px; margin-top: 10px; padding: 10px; background-color: rgba(255,255,255,0.7); border-radius: 5px;">
            <strong>Risk Level:</strong> <span style="color: #4CAF50; font-weight: bold;">green</span><br>
            <strong>Issues:</strong> 具体问题<br>
            <strong>Explanation:</strong> 详细解释
        </div>
    </div>
</div>
```

请为原文的每个句子生成对应的HTML标注块。
"""

    elif stage == 3:
        stage_title = "✨ Stage 3: Revision Suggestions"
        user_prompt = f"""
基于前面的分析和标注,现在请提供修改后的文本版本,并生成HTML格式的对比显示。

要求:
1. 保持原意的前提下修正所有问题
2. 确保符合{country_cn}{standard}
3. 对比显示哪些句子被修改了,哪些保持不变

请直接返回HTML代码,格式如下:
```html
<div style="background-color: rgba(255,255,255,0.5); padding: 20px; border-radius: 10px;">
    <!-- 未修改的句子 -->
    <div style="margin: 15px 0; padding: 15px; border-left: 4px solid #4CAF50; background-color: rgba(76, 175, 80, 0.1); border-radius: 8px;">
        <p style="color: #4CAF50; font-size: 18px; line-height: 1.6; margin: 0; font-weight: bold;">未修改的句子内容</p>
    </div>

    <!-- 修改过的句子 -->
    <div style="margin: 15px 0; padding: 15px; border-left: 4px solid #333; background-color: rgba(76, 175, 80, 0.05); border-radius: 8px;">
        <p style="color: #333; font-size: 18px; line-height: 1.6; margin: 0 0 10px 0;">修改后的句子内容</p>
        <div style="color: #666; font-size: 14px; margin-top: 10px; padding: 10px; background-color: rgba(255,255,255,0.7); border-radius: 5px;">
            <strong>Original:</strong> 原始句子内容
        </div>
    </div>
</div>
```

请为每个句子生成对应的HTML显示块。
"""

    # 构建完整的消息列表
    current_messages = messages.copy()
    current_messages.append({"role": "user", "content": user_prompt})

    # 初始化累积内容
    accumulated_content = ""
    accumulated_reasoning = ""

    try:
        # 使用OpenAI客户端进行流式调用
        from openai import OpenAI

        client = OpenAI(
            base_url=model_config["base_url"].replace("/chat/completions", "/"),
            api_key=model_config["api_key"]
        )

        # 发送流式请求
        request_params = {
            "model": model_config["model"],
            "messages": current_messages,
            "stream": True,
            "max_tokens": 4096,
            "temperature": 0.1
        }

        # 注意:Qwen/Qwen3-8B不支持thinking,只有特定模型支持
        # 这里不添加thinking参数,因为会导致错误

        response = client.chat.completions.create(**request_params)

        # 逐步接收并处理响应
        for chunk in response:
            if chunk.choices[0].delta.content:
                accumulated_content += chunk.choices[0].delta.content
            if hasattr(chunk.choices[0].delta, 'reasoning_content') and chunk.choices[0].delta.reasoning_content:
                accumulated_reasoning += chunk.choices[0].delta.reasoning_content

            # 实时输出当前阶段的HTML
            yield generate_streaming_stage_html(stage, stage_title, accumulated_content, accumulated_reasoning)

        # 更新对话历史
        messages.extend([
            {"role": "user", "content": user_prompt},
            {"role": "assistant", "content": accumulated_content}
        ])

    except Exception as e:
        print(f"Streaming API call error: {e}")
        yield generate_error_card(str(e))

# 生成流式阶段HTML
def generate_streaming_stage_html(stage: int, title: str, content: str, reasoning: str) -> str:
    """生成流式输出的阶段HTML"""

    # 根据阶段选择不同的说明文字
    if stage == 1:
        description = "AI is analyzing the overall risk and compliance..."
        next_stage = "proceeding to detailed annotation..."
        content_title = "📊 Analysis Results"
    elif stage == 2:
        description = "AI is creating color-coded sentence annotations..."
        next_stage = "generating revision suggestions..."
        content_title = "🎨 Annotated Content"
    else:
        description = "AI is providing corrected text and comparisons..."
        next_stage = "analysis complete!"
        content_title = "✨ Revised Content"

    # 判断是否完成(有完整内容且不再更新)
    is_complete = len(content.strip()) > 50  # 简单判断

    # 处理内容显示 - 对于第2、3阶段,如果内容包含HTML,清理并直接显示
    if stage >= 2 and '<div' in content:
        # AI返回的是HTML,清理markdown标记
        content_display = clean_ai_html_content(content)
        content_style = ""
    else:
        # 第1阶段或纯文本,清理markdown格式并使用预格式化
        content_display = clean_markdown_format(content)
        content_style = "white-space: pre-wrap;"

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">{title}</h2>

            <!-- 折叠的推理过程 - 移到正文上方,随时可展开 -->
            <details style="
                background-color: rgba(255,255,255,0.5);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <summary style="
                    color: #5B5B5B;
                    font-size: 18px;
                    font-weight: bold;
                    cursor: pointer;
                    padding: 10px;
                    background-color: rgba(154, 143, 143, 0.1);
                    border-radius: 5px;
                    display: block;
                ">🧠 AI Reasoning Process (Click to expand/collapse)</summary>
                <div style="
                    color: #5B5B5B;
                    font-size: 14px;
                    line-height: 1.6;
                    padding: 15px;
                    background-color: rgba(255,255,255,0.3);
                    border-radius: 8px;
                    white-space: pre-wrap;
                    font-family: 'Courier New', monospace;
                    margin-top: 10px;
                    min-height: 30px;
                ">{reasoning if reasoning else 'AI reasoning process will appear here as analysis progresses...'}</div>
            </details>

            <!-- 分析内容 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
                border-left: 4px solid #4CAF50;
            ">
                <h3 style="color: #5B5B5B; margin-bottom: 15px; font-size: 20px;">{content_title}</h3>
                <div style="
                    color: #5B5B5B;
                    font-size: 16px;
                    line-height: 1.8;
                    {content_style}
                    min-height: 50px;
                ">{content_display}</div>
            </div>

            <div style="
                text-align: center;
                color: {'#4A7C59' if is_complete else '#FF9800'};
                font-size: 16px;
                font-weight: bold;
                padding: 15px;
                background-color: rgba({'74, 124, 89' if is_complete else '255, 152, 0'}, 0.1);
                border-radius: 8px;
            ">{'✅ Stage ' + str(stage) + ' Complete, ' + next_stage if is_complete else '🔄 ' + description}</div>
        </div>
    </div>
    """

# 清理AI返回的HTML内容
def clean_ai_html_content(content: str) -> str:
    """清理AI返回的HTML内容,移除markdown标记"""
    # 移除```html和```标记
    if "```html" in content:
        content = content.split("```html")[1].split("```")[0]
    elif "```" in content:
        # 如果有其他markdown代码块标记
        parts = content.split("```")
        if len(parts) >= 3:
            content = parts[1]

    # 清理多余的空白行
    content = content.strip()

    return content

# 清理文本中的markdown格式
def clean_markdown_format(text: str) -> str:
    """清理文本中的markdown格式标记"""
    # 移除双引号markdown标记
    text = text.replace('""', '"')
    text = text.replace('"', '"')
    text = text.replace('"', '"')

    # 移除粗体标记
    text = text.replace('**', '')
    text = text.replace('__', '')

    # 移除斜体标记
    text = text.replace('*', '')
    text = text.replace('_', '')

    # 移除其他常见markdown标记
    text = text.replace('`', '')
    text = text.replace('~~', '')

    return text

# 生成分析摘要
def generate_analysis_summary() -> str:
    """生成分析摘要界面"""
    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">📊 Analysis Summary</h2>

            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <h3 style="color: #5B5B5B; margin-bottom: 15px; font-size: 20px;">🎯 Three-Stage Analysis Complete</h3>

                <div style="margin: 15px 0;">
                    <h4 style="color: #4CAF50; margin-bottom: 10px;">🔍 Stage 1: Basic Analysis</h4>
                    <p style="color: #5B5B5B; margin-left: 20px;">Initial risk assessment and compliance evaluation</p>
                </div>

                <div style="margin: 15px 0;">
                    <h4 style="color: #FF9800; margin-bottom: 10px;">🎨 Stage 2: Detailed Annotation</h4>
                    <p style="color: #5B5B5B; margin-left: 20px;">Sentence-level risk marking with color coding</p>
                </div>

                <div style="margin: 15px 0;">
                    <h4 style="color: #9C27B0; margin-bottom: 10px;">✨ Stage 3: Revision Suggestions</h4>
                    <p style="color: #5B5B5B; margin-left: 20px;">Corrected text with compliance improvements</p>
                </div>
            </div>

            <div style="
                background-color: rgba(255,255,255,0.5);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <h3 style="color: #5B5B5B; margin-bottom: 15px; font-size: 20px;">💡 How to Use</h3>
                <ul style="color: #5B5B5B; line-height: 1.8;">
                    <li><strong>Switch between tabs</strong> to view different analysis stages</li>
                    <li><strong>Click the reasoning sections</strong> to see AI's thought process</li>
                    <li><strong>Compare original and revised text</strong> in Stage 3</li>
                    <li><strong>Use color coding</strong> in Stage 2 to identify risk levels</li>
                </ul>
            </div>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 18px;
                font-weight: bold;
                padding: 20px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">🎉 Content Audit Complete! Review all stages above.</div>
        </div>
    </div>
    """

# 执行reasoning分析
def perform_reasoning_analysis(text: str, keywords: List[str], country: str, language: str, model: str, messages: list, stage: int) -> dict:
    """执行带reasoning的AI分析"""

    # 解析模型名称
    model_mapping = {
        "Qwen/QwQ-32B (Reasoning - SiliconFlow)": "Qwen/QwQ-32B",
        "Pro/deepseek-ai/DeepSeek-R1 (Reasoning - SiliconFlow)": "Pro/deepseek-ai/DeepSeek-R1",
        "Qwen/Qwen3-8B (Free - SiliconFlow)": "Qwen/Qwen3-8B",
        "deepseek-ai/DeepSeek-V3-0324 (Paid - Nebius)": "deepseek-ai/DeepSeek-V3-0324",
        "deepseek-ai/DeepSeek-R1-0528 (Paid - Nebius)": "deepseek-ai/DeepSeek-R1-0528",
        "Qwen/Qwen3-235B-A22B (Paid - Nebius)": "Qwen/Qwen3-235B-A22B",
        "google/gemma-3-27b-it (Paid - Nebius, Vision)": "google/gemma-3-27b-it"
    }

    actual_model = model_mapping.get(model, "Qwen/QwQ-32B")

    # 构建国家和标准信息
    country_standards = {
        "China": "中国广告法和相关法规",
        "USA": "美国FTC广告标准",
        "UK": "英国ASA广告标准",
        "Japan": "日本景品表示法",
        "Korea": "韩国公正交易委员会标准",
        "Singapore": "新加坡CCCS标准",
        "Malaysia": "马来西亚广告标准",
        "Other": "国际通用广告标准"
    }

    country_names = {
        "China": "中国",
        "USA": "美国",
        "UK": "英国",
        "Japan": "日本",
        "Korea": "韩国",
        "Singapore": "新加坡",
        "Malaysia": "马来西亚",
        "Other": "其他地区"
    }

    standard = country_standards.get(country, "国际通用广告标准")
    country_cn = country_names.get(country, country)
    keywords_str = ", ".join(keywords) if keywords else "无"

    # 根据阶段构建不同的prompt
    if stage == 1:
        user_prompt = f"""
你是专业的内容审核专家,请根据{country_cn}{standard}对以下文本进行初步分析。

文本内容:{text}
关键词:{keywords_str}
审核地区:{country_cn}
回答语言:{language}

请进行基础分析,包括:
1. 整体风险评估
2. 主要问题识别
3. 法规符合性初判

请用{language}回答,提供清晰的分析结论。
"""

    elif stage == 2:
        user_prompt = f"""
基于前面的分析,现在请对文本进行详细的句子级标注分析。

请为每个句子标注风险等级:
- 绿色:无问题,表述规范
- 黄色:轻微问题,建议优化
- 橙色:中等问题,需要修改
- 红色:严重问题,必须修改

对每个句子说明具体问题和原因。
"""

    elif stage == 3:
        user_prompt = f"""
基于前面的分析和标注,现在请提供修改后的文本版本。

要求:
1. 保持原意的前提下修正所有问题
2. 确保符合{country_cn}{standard}
3. 对比显示哪些句子被修改了,哪些保持不变

请提供完整的修改版本。
"""

    # 构建完整的消息列表
    current_messages = messages.copy()
    current_messages.append({"role": "user", "content": user_prompt})

    # 调用AI API
    try:
        import requests

        # 判断是否使用reasoning模型
        is_reasoning_model = actual_model in ["Qwen/QwQ-32B", "Pro/deepseek-ai/DeepSeek-R1"]

        api_key = os.getenv("SILICONFLOW_API_KEY", "sk-your-api-key-here")

        payload = {
            "model": actual_model,
            "messages": current_messages,
            "stream": True,
            "max_tokens": 4096,
            "temperature": 0.1
        }

        # 如果是reasoning模型,添加特殊参数
        if is_reasoning_model:
            if actual_model == "Qwen/QwQ-32B":
                payload["enable_thinking"] = True
                payload["thinking_budget"] = 4096
            elif actual_model == "Pro/deepseek-ai/DeepSeek-R1":
                payload["extra_body"] = {"thinking_budget": 1024}

        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }

        response = requests.post(
            "https://api.siliconflow.cn/v1/chat/completions",
            json=payload,
            headers=headers,
            stream=True
        )

        content = ""
        reasoning_content = ""

        # 处理流式响应
        for line in response.iter_lines():
            if line:
                line_str = line.decode('utf-8')
                if line_str.startswith('data: '):
                    data_str = line_str[6:]
                    if data_str == '[DONE]':
                        break
                    try:
                        chunk = json.loads(data_str)
                        if 'choices' in chunk and len(chunk['choices']) > 0:
                            delta = chunk['choices'][0].get('delta', {})
                            if 'content' in delta and delta['content']:
                                content += delta['content']
                            if 'reasoning_content' in delta and delta['reasoning_content']:
                                reasoning_content += delta['reasoning_content']
                    except json.JSONDecodeError:
                        continue

        return {
            "content": content,
            "reasoning_content": reasoning_content,
            "user_prompt": user_prompt,
            "stage": stage
        }

    except Exception as e:
        print(f"API call error: {e}")
        return {
            "content": f"API调用失败: {str(e)}",
            "reasoning_content": "无法获取推理过程",
            "user_prompt": user_prompt,
            "stage": stage
        }

# 生成第一阶段HTML(分析报告)
def generate_stage1_html(result: dict) -> str:
    """生成第一阶段的分析报告HTML"""
    content = result.get("content", "")
    reasoning = result.get("reasoning_content", "")

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">📋 Stage 1: AI Analysis Report</h2>

            <!-- 分析内容 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
                border-left: 4px solid #4CAF50;
            ">
                <h3 style="color: #5B5B5B; margin-bottom: 15px; font-size: 20px;">📊 Analysis Results</h3>
                <div style="
                    color: #5B5B5B;
                    font-size: 16px;
                    line-height: 1.8;
                    white-space: pre-wrap;
                ">{content}</div>
            </div>

            <!-- 折叠的推理过程 -->
            <details style="
                background-color: rgba(255,255,255,0.5);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <summary style="
                    color: #5B5B5B;
                    font-size: 18px;
                    font-weight: bold;
                    cursor: pointer;
                    padding: 10px;
                    background-color: rgba(154, 143, 143, 0.1);
                    border-radius: 5px;
                    margin-bottom: 15px;
                ">🧠 AI Reasoning Process (Click to expand/collapse)</summary>
                <div style="
                    color: #5B5B5B;
                    font-size: 14px;
                    line-height: 1.6;
                    padding: 15px;
                    background-color: rgba(255,255,255,0.3);
                    border-radius: 8px;
                    white-space: pre-wrap;
                    font-family: 'Courier New', monospace;
                ">{reasoning}</div>
            </details>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 16px;
                font-weight: bold;
                padding: 15px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">✅ Stage 1 Complete, proceeding to detailed annotation...</div>
        </div>
    </div>
    """

# 生成第二阶段HTML(详细标注)
def generate_stage2_html(result: dict) -> str:
    """生成第二阶段的详细标注HTML"""
    content = result.get("content", "")
    reasoning = result.get("reasoning_content", "")

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">🎨 Stage 2: Detailed Annotation</h2>

            <!-- 颜色图例 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <h4 style="color: #5B5B5B; margin-bottom: 10px;">Color Legend:</h4>
                <div style="display: flex; flex-wrap: wrap; gap: 15px;">
                    <span style="color: #4CAF50; font-weight: bold;">🟢 Green: No Issues</span>
                    <span style="color: #FFC107; font-weight: bold;">🟡 Yellow: Minor Issues</span>
                    <span style="color: #FF9800; font-weight: bold;">🟠 Orange: Moderate Issues</span>
                    <span style="color: #F44336; font-weight: bold;">🔴 Red: Serious Issues</span>
                </div>
            </div>

            <!-- 标注内容 -->
            <div style="
                background-color: rgba(255,255,255,0.5);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <div style="
                    color: #5B5B5B;
                    font-size: 16px;
                    line-height: 1.8;
                    white-space: pre-wrap;
                ">{content}</div>
            </div>

            <!-- 折叠的推理过程 -->
            <details style="
                background-color: rgba(255,255,255,0.5);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <summary style="
                    color: #5B5B5B;
                    font-size: 18px;
                    font-weight: bold;
                    cursor: pointer;
                    padding: 10px;
                    background-color: rgba(154, 143, 143, 0.1);
                    border-radius: 5px;
                    margin-bottom: 15px;
                ">🧠 AI Reasoning Process (Click to expand/collapse)</summary>
                <div style="
                    color: #5B5B5B;
                    font-size: 14px;
                    line-height: 1.6;
                    padding: 15px;
                    background-color: rgba(255,255,255,0.3);
                    border-radius: 8px;
                    white-space: pre-wrap;
                    font-family: 'Courier New', monospace;
                ">{reasoning}</div>
            </details>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 16px;
                font-weight: bold;
                padding: 15px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">✅ Stage 2 Complete, generating revision suggestions...</div>
        </div>
    </div>
    """

# 生成第三阶段HTML(修改建议)
def generate_stage3_html(result: dict) -> str:
    """生成第三阶段的修改建议HTML"""
    content = result.get("content", "")
    reasoning = result.get("reasoning_content", "")

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">✨ Stage 3: Revision Suggestions</h2>

            <!-- 说明 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <h4 style="color: #5B5B5B; margin-bottom: 10px;">Legend:</h4>
                <p style="color: #4CAF50; font-weight: bold; margin: 5px 0;">🟢 Green: Unchanged sentences (compliant)</p>
                <p style="color: #333; margin: 5px 0;">⚫ Normal: Modified sentences (with explanations)</p>
            </div>

            <!-- 修改建议内容 -->
            <div style="
                background-color: rgba(255,255,255,0.5);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <div style="
                    color: #5B5B5B;
                    font-size: 16px;
                    line-height: 1.8;
                    white-space: pre-wrap;
                ">{content}</div>
            </div>

            <!-- 折叠的推理过程 -->
            <details style="
                background-color: rgba(255,255,255,0.5);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <summary style="
                    color: #5B5B5B;
                    font-size: 18px;
                    font-weight: bold;
                    cursor: pointer;
                    padding: 10px;
                    background-color: rgba(154, 143, 143, 0.1);
                    border-radius: 5px;
                    margin-bottom: 15px;
                ">🧠 AI Reasoning Process (Click to expand/collapse)</summary>
                <div style="
                    color: #5B5B5B;
                    font-size: 14px;
                    line-height: 1.6;
                    padding: 15px;
                    background-color: rgba(255,255,255,0.3);
                    border-radius: 8px;
                    white-space: pre-wrap;
                    font-family: 'Courier New', monospace;
                ">{reasoning}</div>
            </details>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 18px;
                font-weight: bold;
                padding: 20px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">🎉 All Stages Complete! Content audit finished.</div>
        </div>
    </div>
    """

# 获取AI生成的HTML(分阶段)
def get_ai_generated_html(text: str, keywords: List[str], country: str, language: str, model: str, stage: int) -> str:
    """获取AI生成的HTML内容"""
    ai = AIContentAnalyzer()

    # 解析模型名称
    model_mapping = {
        "Qwen/Qwen3-8B (Free - SiliconFlow)": "Qwen/Qwen3-8B",
        "deepseek-ai/DeepSeek-V3-0324 (Paid - Nebius)": "deepseek-ai/DeepSeek-V3-0324",
        "deepseek-ai/DeepSeek-R1-0528 (Paid - Nebius)": "deepseek-ai/DeepSeek-R1-0528",
        "Qwen/Qwen3-235B-A22B (Paid - Nebius)": "Qwen/Qwen3-235B-A22B",
        "google/gemma-3-27b-it (Paid - Nebius, Vision)": "google/gemma-3-27b-it"
    }

    actual_model = model_mapping.get(model, "Qwen/Qwen3-8B")
    ai.set_model(actual_model)

    # 构建不同阶段的prompt
    country_standards = {
        "China": "中国广告法和相关法规",
        "USA": "美国FTC广告标准",
        "UK": "英国ASA广告标准",
        "Japan": "日本景品表示法",
        "Korea": "韩国公正交易委员会标准",
        "Singapore": "新加坡CCCS标准",
        "Malaysia": "马来西亚广告标准",
        "Other": "国际通用广告标准"
    }

    country_names = {
        "China": "中国",
        "USA": "美国",
        "UK": "英国",
        "Japan": "日本",
        "Korea": "韩国",
        "Singapore": "新加坡",
        "Malaysia": "马来西亚",
        "Other": "其他地区"
    }

    standard = country_standards.get(country, "国际通用广告标准")
    country_cn = country_names.get(country, country)
    keywords_str = ", ".join(keywords) if keywords else "无"

    # 根据阶段生成不同的prompt
    if stage == 1:
        prompt = f"""
你是专业的内容审核专家,请根据{country_cn}{standard}对以下文本进行全面审核分析。

文本内容:{text}
关键词:{keywords_str}
审核地区:{country_cn}
回答语言:{language}

请生成第一阶段的分析报告HTML,包含:
1. 详细的推理过程(放在折叠的思考框中)
2. 分析摘要(发现的问题总数、风险等级、主要问题)

请直接返回完整的HTML代码,使用以下样式框架,并填入具体内容:

<div style="max-width: 900px; margin: 0 auto; padding: 30px; background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%); border-radius: 20px; font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;">
    <div style="background-color: #F2EDE9; border-radius: 15px; padding: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.1);">
        <h2 style="color: #5B5B5B; margin-bottom: 20px; font-size: 28px; border-bottom: 3px solid #9A8F8F; padding-bottom: 10px;">📋 Step 1: AI Analysis Report</h2>

        <!-- 分析摘要 -->
        <div style="background-color: rgba(255,255,255,0.7); padding: 20px; border-radius: 10px; margin-bottom: 20px; border-left: 4px solid #FF9800;">
            <h3 style="color: #5B5B5B; margin-bottom: 15px; font-size: 20px;">📊 Analysis Summary</h3>
            <p style="color: #5B5B5B; font-size: 18px; margin: 10px 0;"><strong>Issues Found:</strong> [填入具体数字]</p>
            <p style="color: #5B5B5B; font-size: 18px; margin: 10px 0;"><strong>Risk Level:</strong> <span style="color: #FF9800; font-weight: bold;">[填入风险等级]</span></p>
            <p style="color: #5B5B5B; font-size: 16px; margin: 10px 0;"><strong>Main Concerns:</strong> [填入主要问题]</p>
        </div>

        <!-- 折叠的思考过程 -->
        <details style="background-color: rgba(255,255,255,0.5); padding: 15px; border-radius: 10px; margin-bottom: 20px;">
            <summary style="color: #5B5B5B; font-size: 18px; font-weight: bold; cursor: pointer; padding: 10px; background-color: rgba(154, 143, 143, 0.1); border-radius: 5px; margin-bottom: 15px;">🧠 AI Reasoning Process (Click to expand/collapse)</summary>
            <div style="color: #5B5B5B; font-size: 16px; line-height: 1.6; padding: 15px; background-color: rgba(255,255,255,0.3); border-radius: 8px; white-space: pre-wrap;">
[在这里填入详细的推理过程,包括:
1. 对文本的初步分析
2. 发现的具体问题
3. 风险评估的依据
4. 法规符合性分析
等等]
            </div>
        </details>

        <div style="text-align: center; color: #4A7C59; font-size: 16px; font-weight: bold; padding: 15px; background-color: rgba(74, 124, 89, 0.1); border-radius: 8px;">✅ Step 1 Complete, generating annotated version...</div>
    </div>
</div>
"""

    elif stage == 2:
        prompt = f"""
请为以下文本生成第二阶段的标注版HTML:

原文:{text}
审核标准:{country_cn}{standard}

请生成带颜色标注的HTML版本,要求:
1. 每个句子根据风险等级标注颜色(绿色=无问题,黄色=轻微,橙色=中等,红色=严重)
2. 在句子下方添加问题说明
3. 包含颜色图例

请直接返回完整的HTML代码,使用以下样式框架:

<div style="max-width: 900px; margin: 0 auto; padding: 30px; background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%); border-radius: 20px; font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;">
    <div style="background-color: #F2EDE9; border-radius: 15px; padding: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.1);">
        <h2 style="color: #5B5B5B; margin-bottom: 20px; font-size: 28px; border-bottom: 3px solid #9A8F8F; padding-bottom: 10px;">🎨 Step 2: Annotated Version</h2>

        <!-- 颜色图例 -->
        <div style="background-color: rgba(255,255,255,0.7); padding: 15px; border-radius: 10px; margin-bottom: 20px;">
            <h4 style="color: #5B5B5B; margin-bottom: 10px;">Color Legend:</h4>
            <div style="display: flex; flex-wrap: wrap; gap: 15px;">
                <span style="color: #4CAF50; font-weight: bold;">🟢 Green: No Issues</span>
                <span style="color: #FFC107; font-weight: bold;">🟡 Yellow: Minor Issues</span>
                <span style="color: #FF9800; font-weight: bold;">🟠 Orange: Moderate Issues</span>
                <span style="color: #F44336; font-weight: bold;">🔴 Red: Serious Issues</span>
            </div>
        </div>

        <!-- 标注内容 -->
        <div style="background-color: rgba(255,255,255,0.5); padding: 20px; border-radius: 10px; margin-bottom: 20px;">
            [在这里为每个句子生成标注,格式如下:

            <div style="margin: 15px 0; padding: 15px; border-left: 5px solid #4CAF50; background-color: rgba(76, 175, 80, 0.1); border-radius: 8px;">
                <p style="color: #333; font-size: 18px; line-height: 1.6; margin: 0 0 10px 0; font-weight: 500;">句子内容</p>
                <div style="color: #666; font-size: 14px; margin-top: 10px; padding: 10px; background-color: rgba(255,255,255,0.7); border-radius: 5px;">
                    <strong>Risk Level:</strong> <span style="color: #4CAF50; font-weight: bold;">green</span><br>
                    <strong>Issues:</strong> 无问题<br>
                    <strong>Explanation:</strong> 表述规范,符合法规要求
                </div>
            </div>

            请为每个句子生成类似的标注块,根据实际风险等级调整颜色]
        </div>

        <div style="text-align: center; color: #4A7C59; font-size: 16px; font-weight: bold; padding: 15px; background-color: rgba(74, 124, 89, 0.1); border-radius: 8px;">✅ Step 2 Complete, generating revised version...</div>
    </div>
</div>
"""

    elif stage == 3:
        prompt = f"""
请为以下文本生成第三阶段的修改版HTML:

原文:{text}
审核标准:{country_cn}{standard}

请生成修改后的文本对比版,要求:
1. 显示修改后的完整文本
2. 未修改的句子用绿色粗体显示
3. 修改过的句子正常显示,并在下方显示原文

请直接返回完整的HTML代码,使用以下样式框架:

<div style="max-width: 900px; margin: 0 auto; padding: 30px; background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%); border-radius: 20px; font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;">
    <div style="background-color: #F2EDE9; border-radius: 15px; padding: 25px; box-shadow: 0 10px 30px rgba(0,0,0,0.1);">
        <h2 style="color: #5B5B5B; margin-bottom: 20px; font-size: 28px; border-bottom: 3px solid #9A8F8F; padding-bottom: 10px;">✨ Step 3: Revised Text</h2>

        <!-- 说明 -->
        <div style="background-color: rgba(255,255,255,0.7); padding: 15px; border-radius: 10px; margin-bottom: 20px;">
            <h4 style="color: #5B5B5B; margin-bottom: 10px;">Legend:</h4>
            <p style="color: #4CAF50; font-weight: bold; margin: 5px 0;">🟢 Green Bold: Unchanged sentences (compliant)</p>
            <p style="color: #333; margin: 5px 0;">⚫ Normal: Modified sentences (with original shown below)</p>
        </div>

        <!-- 修改后的文本 -->
        <div style="background-color: rgba(255,255,255,0.5); padding: 20px; border-radius: 10px; margin-bottom: 20px;">
            [在这里生成修改后的文本对比,格式如下:

            未修改的句子:
            <div style="margin: 15px 0; padding: 15px; border-left: 4px solid #4CAF50; background-color: rgba(76, 175, 80, 0.1); border-radius: 8px;">
                <p style="color: #4CAF50; font-size: 18px; line-height: 1.6; margin: 0; font-weight: bold;">句子内容</p>
            </div>

            修改过的句子:
            <div style="margin: 15px 0; padding: 15px; border-left: 4px solid #333; background-color: rgba(76, 175, 80, 0.05); border-radius: 8px;">
                <p style="color: #333; font-size: 18px; line-height: 1.6; margin: 0 0 10px 0;">修改后的句子</p>
                <div style="color: #666; font-size: 14px; margin-top: 10px; padding: 10px; background-color: rgba(255,255,255,0.7); border-radius: 5px;">
                    <strong>Original:</strong> 原始句子
                </div>
            </div>

            请为每个句子生成对应的显示块]
        </div>

        <div style="text-align: center; color: #4A7C59; font-size: 18px; font-weight: bold; padding: 20px; background-color: rgba(74, 124, 89, 0.1); border-radius: 8px;">🎉 All Steps Complete! Content audit finished.</div>
    </div>
</div>
"""

    # 调用AI API
    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        try:
            result = loop.run_until_complete(call_ai_api(ai, prompt))
            return result
        finally:
            loop.close()

    except Exception as e:
        print(f"AI API error: {e}")
        return generate_error_card(str(e))

# 调用AI API的辅助函数
async def call_ai_api(ai: AIContentAnalyzer, prompt: str) -> str:
    """调用AI API获取HTML响应"""
    try:
        headers = {
            "Authorization": f"Bearer {ai.api_key}",
            "Content-Type": "application/json"
        }

        data = {
            "model": ai.model,
            "messages": [
                {"role": "system", "content": "你是专业的内容审核专家,请直接返回完整的HTML代码,不要添加任何markdown标记或其他格式。"},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.1,
            "max_tokens": 4000
        }

        async with aiohttp.ClientSession() as session:
            async with session.post(ai.base_url, headers=headers, json=data) as response:
                if response.status == 200:
                    result = await response.json()
                    ai_response = result["choices"][0]["message"]["content"]

                    # 清理AI返回的内容,提取HTML
                    if "```html" in ai_response:
                        ai_response = ai_response.split("```html")[1].split("```")[0]
                    elif "```" in ai_response:
                        ai_response = ai_response.split("```")[1].split("```")[0]

                    return ai_response.strip()
                else:
                    return generate_error_card("AI API调用失败")

    except Exception as e:
        print(f"AI API call error: {e}")
        return generate_error_card(str(e))

# 获取完整AI分析结果
async def get_complete_ai_analysis(text: str, keywords: List[str], country: str, language: str, model: str):
    """获取完整的AI分析结果"""
    ai = AIContentAnalyzer()

    # 解析模型名称
    model_mapping = {
        "Qwen/Qwen3-8B (Free - SiliconFlow)": "Qwen/Qwen3-8B",
        "deepseek-ai/DeepSeek-V3-0324 (Paid - Nebius)": "deepseek-ai/DeepSeek-V3-0324",
        "deepseek-ai/DeepSeek-R1-0528 (Paid - Nebius)": "deepseek-ai/DeepSeek-R1-0528",
        "Qwen/Qwen3-235B-A22B (Paid - Nebius)": "Qwen/Qwen3-235B-A22B",
        "google/gemma-3-27b-it (Paid - Nebius, Vision)": "google/gemma-3-27b-it"
    }

    actual_model = model_mapping.get(model, "Qwen/Qwen3-8B")
    ai.set_model(actual_model)

    # 构建prompt
    country_standards = {
        "China": "中国广告法和相关法规",
        "USA": "美国FTC广告标准",
        "UK": "英国ASA广告标准",
        "Japan": "日本景品表示法",
        "Korea": "韩国公正交易委员会标准",
        "Singapore": "新加坡CCCS标准",
        "Malaysia": "马来西亚广告标准",
        "Other": "国际通用广告标准"
    }

    country_names = {
        "China": "中国",
        "USA": "美国",
        "UK": "英国",
        "Japan": "日本",
        "Korea": "韩国",
        "Singapore": "新加坡",
        "Malaysia": "马来西亚",
        "Other": "其他地区"
    }

    standard = country_standards.get(country, "国际通用广告标准")
    country_cn = country_names.get(country, country)
    keywords_str = ", ".join(keywords) if keywords else "无"

    prompt = f"""
你是专业的内容审核专家,请根据{country_cn}{standard}对以下文本进行全面审核分析。

文本内容:{text}
关键词:{keywords_str}
审核地区:{country_cn}
回答语言:{language}

请按照以下JSON格式返回分析结果:
{{
    "reasoning_content": "详细的推理过程和分析思路",
    "sentence_analysis": [
        {{
            "sentence": "具体句子内容",
            "risk_level": "green/yellow/orange/red",
            "issues": ["具体问题1", "具体问题2"],
            "explanation": "为什么认为有问题的详细解释"
        }}
    ],
    "revised_text": "修改后的完整文本",
    "summary": {{
        "total_issues": 问题总数,
        "risk_level": "整体风险等级",
        "main_concerns": ["主要问题1", "主要问题2"]
    }}
}}

风险等级说明:
- green: 无问题,表述规范
- yellow: 轻微问题,建议优化
- orange: 中等问题,需要修改
- red: 严重问题,必须修改

请确保:
1. 每个句子都要分析并标注风险等级
2. 问题解释要具体明确
3. 修改后的文本要保持原意但符合法规
4. 返回标准的JSON格式
"""

    try:
        headers = {
            "Authorization": f"Bearer {ai.api_key}",
            "Content-Type": "application/json"
        }

        data = {
            "model": ai.model,
            "messages": [
                {"role": "system", "content": f"你是专业的内容审核专家,请根据{country_cn}的法规标准进行分析,并用{language}回答。"},
                {"role": "user", "content": prompt}
            ],
            "temperature": 0.1,
            "max_tokens": 4000
        }

        async with aiohttp.ClientSession() as session:
            async with session.post(ai.base_url, headers=headers, json=data) as response:
                if response.status == 200:
                    result = await response.json()
                    ai_response = result["choices"][0]["message"]["content"]

                    # 尝试解析JSON
                    try:
                        # 清理AI返回的内容
                        if "```json" in ai_response:
                            ai_response = ai_response.split("```json")[1].split("```")[0]
                        elif "```" in ai_response:
                            ai_response = ai_response.split("```")[1].split("```")[0]

                        analysis_result = json.loads(ai_response.strip())
                        return analysis_result
                    except json.JSONDecodeError:
                        # 如果JSON解析失败,返回基础分析
                        return create_fallback_structured_analysis(text)
                else:
                    return create_fallback_structured_analysis(text)

    except Exception as e:
        print(f"AI analysis error: {e}")
        return create_fallback_structured_analysis(text)

def create_fallback_structured_analysis(text: str) -> Dict:
    """创建备用的结构化分析结果"""
    sentences = text.split('。')
    sentence_analysis = []

    for sentence in sentences:
        if sentence.strip():
            sentence_analysis.append({
                "sentence": sentence.strip() + "。",
                "risk_level": "green",
                "issues": [],
                "explanation": "AI分析服务暂时不可用,无法进行详细分析"
            })

    return {
        "reasoning_content": "AI分析服务暂时不可用,请稍后重试或检查网络连接。",
        "sentence_analysis": sentence_analysis,
        "revised_text": text,
        "summary": {
            "total_issues": 0,
            "risk_level": "unknown",
            "main_concerns": ["AI分析服务暂时不可用"]
        }
    }

# 生成加载卡片
def generate_loading_card(title: str, message: str) -> str:
    """生成加载中的卡片"""
    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        text-align: center;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="color: #5B5B5B; margin-bottom: 20px; font-size: 24px;">{title}</h2>
            <p style="color: #8C8C8C; margin-bottom: 30px; font-size: 16px;">{message}</p>
            <div style="
                width: 200px;
                height: 4px;
                background: #D1CBC3;
                border-radius: 2px;
                margin: 0 auto;
                overflow: hidden;
            ">
                <div style="
                    width: 30%;
                    height: 100%;
                    background: #9A8F8F;
                    border-radius: 2px;
                    animation: loading 2s infinite;
                "></div>
            </div>
        </div>
        <style>
        @keyframes loading {{
            0% {{ transform: translateX(-100%); }}
            100% {{ transform: translateX(400%); }}
        }}
        </style>
    </div>
    """

# 生成分析报告卡片(第一次输出)
def generate_analysis_report_card(analysis_result: Dict) -> str:
    """生成分析报告卡片,reasoning_content放在折叠栏中"""
    summary = analysis_result.get("summary", {})
    reasoning = analysis_result.get("reasoning_content", "")

    total_issues = summary.get("total_issues", 0)
    risk_level = summary.get("risk_level", "unknown")
    main_concerns = summary.get("main_concerns", [])

    # 风险等级颜色
    risk_colors = {
        "low": "#4CAF50",
        "medium": "#FF9800",
        "high": "#F44336",
        "unknown": "#9E9E9E"
    }

    risk_color = risk_colors.get(risk_level, "#9E9E9E")

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">📋 Step 1: AI Analysis Report</h2>

            <!-- 摘要信息 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
                border-left: 4px solid {risk_color};
            ">
                <h3 style="color: #5B5B5B; margin-bottom: 15px; font-size: 20px;">📊 Analysis Summary</h3>
                <p style="color: #5B5B5B; font-size: 18px; margin: 10px 0;">
                    <strong>Issues Found:</strong> {total_issues}
                </p>
                <p style="color: #5B5B5B; font-size: 18px; margin: 10px 0;">
                    <strong>Risk Level:</strong> <span style="color: {risk_color}; font-weight: bold;">{risk_level}</span>
                </p>
                {f'<p style="color: #5B5B5B; font-size: 16px; margin: 10px 0;"><strong>Main Concerns:</strong> {", ".join(main_concerns)}</p>' if main_concerns else ''}
            </div>

            <!-- 折叠的推理过程 -->
            <details style="
                background-color: rgba(255,255,255,0.5);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <summary style="
                    color: #5B5B5B;
                    font-size: 18px;
                    font-weight: bold;
                    cursor: pointer;
                    padding: 10px;
                    background-color: rgba(154, 143, 143, 0.1);
                    border-radius: 5px;
                    margin-bottom: 15px;
                ">🧠 AI Reasoning Process (Click to expand/collapse)</summary>
                <div style="
                    color: #5B5B5B;
                    font-size: 16px;
                    line-height: 1.6;
                    padding: 15px;
                    background-color: rgba(255,255,255,0.3);
                    border-radius: 8px;
                    white-space: pre-wrap;
                ">{reasoning}</div>
            </details>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 16px;
                font-weight: bold;
                padding: 15px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">✅ Step 1 Complete, generating annotated version...</div>
        </div>
    </div>
    """

# 生成原文标注版HTML卡片(第二次输出)
def generate_annotated_html_card(original_text: str, analysis_result: Dict) -> str:
    """生成原文标注版HTML"""
    sentence_analysis = analysis_result.get("sentence_analysis", [])

    # 风险等级颜色映射
    risk_colors = {
        "green": "#4CAF50",
        "yellow": "#FFC107",
        "orange": "#FF9800",
        "red": "#F44336"
    }

    # 生成标注的HTML内容
    annotated_html = ""

    for item in sentence_analysis:
        sentence = item.get("sentence", "")
        risk_level = item.get("risk_level", "green")
        issues = item.get("issues", [])
        explanation = item.get("explanation", "")

        color = risk_colors.get(risk_level, "#4CAF50")

        # 生成句子标注
        annotated_html += f"""
        <div style="
            margin: 15px 0;
            padding: 15px;
            border-left: 5px solid {color};
            background-color: rgba({','.join([str(int(color[i:i+2], 16)) for i in (1, 3, 5)])}, 0.1);
            border-radius: 8px;
        ">
            <p style="
                color: #333;
                font-size: 18px;
                line-height: 1.6;
                margin: 0 0 10px 0;
                font-weight: 500;
            ">{sentence}</p>

            {f'''
            <div style="
                color: #666;
                font-size: 14px;
                margin-top: 10px;
                padding: 10px;
                background-color: rgba(255,255,255,0.7);
                border-radius: 5px;
            ">
                <strong>Risk Level:</strong> <span style="color: {color}; font-weight: bold;">{risk_level}</span><br>
                {f"<strong>Issues:</strong> {', '.join(issues)}<br>" if issues else ""}
                <strong>Explanation:</strong> {explanation}
            </div>
            ''' if explanation or issues else ''}
        </div>
        """

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">🎨 Step 2: Annotated Version</h2>

            <!-- 颜色说明 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <h4 style="color: #5B5B5B; margin-bottom: 10px;">Color Legend:</h4>
                <div style="display: flex; flex-wrap: wrap; gap: 15px;">
                    <span style="color: #4CAF50; font-weight: bold;">🟢 Green: No Issues</span>
                    <span style="color: #FFC107; font-weight: bold;">🟡 Yellow: Minor Issues</span>
                    <span style="color: #FF9800; font-weight: bold;">🟠 Orange: Moderate Issues</span>
                    <span style="color: #F44336; font-weight: bold;">🔴 Red: Serious Issues</span>
                </div>
            </div>

            <!-- 标注内容 -->
            <div style="
                background-color: rgba(255,255,255,0.5);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                {annotated_html}
            </div>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 16px;
                font-weight: bold;
                padding: 15px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">✅ Step 2 Complete, generating revised version...</div>
        </div>
    </div>
    """

# 生成整改后的文本对比版(第三次输出)
def generate_revised_text_card(original_text: str, analysis_result: Dict) -> str:
    """生成整改后的文本对比版"""
    revised_text = analysis_result.get("revised_text", original_text)

    # 简单的句子对比(按句号分割)
    original_sentences = [s.strip() + "。" for s in original_text.split("。") if s.strip()]
    revised_sentences = [s.strip() + "。" for s in revised_text.split("。") if s.strip()]

    # 生成对比HTML
    comparison_html = ""

    max_len = max(len(original_sentences), len(revised_sentences))

    for i in range(max_len):
        orig_sentence = original_sentences[i] if i < len(original_sentences) else ""
        rev_sentence = revised_sentences[i] if i < len(revised_sentences) else ""

        # 判断是否有变化
        is_changed = orig_sentence != rev_sentence
        sentence_color = "#4CAF50" if not is_changed else "#333"

        if rev_sentence:
            comparison_html += f"""
            <div style="
                margin: 15px 0;
                padding: 15px;
                border-left: 4px solid {sentence_color};
                background-color: rgba(76, 175, 80, {'0.1' if not is_changed else '0.05'});
                border-radius: 8px;
            ">
                <p style="
                    color: {sentence_color};
                    font-size: 18px;
                    line-height: 1.6;
                    margin: 0;
                    font-weight: {'bold' if not is_changed else 'normal'};
                ">{rev_sentence}</p>

                {f'''
                <div style="
                    color: #666;
                    font-size: 14px;
                    margin-top: 10px;
                    padding: 10px;
                    background-color: rgba(255,255,255,0.7);
                    border-radius: 5px;
                ">
                    <strong>Original:</strong> {orig_sentence}
                </div>
                ''' if is_changed else ''}
            </div>
            """

    return f"""
    <div style="
        max-width: 900px;
        margin: 0 auto;
        padding: 30px;
        background: linear-gradient(135deg, #E8E3DE 0%, #F2EDE9 100%);
        border-radius: 20px;
        font-family: 'Microsoft YaHei', 'Noto Sans SC', sans-serif;
        margin-bottom: 25px;
    ">
        <div style="
            background-color: #F2EDE9;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        ">
            <h2 style="
                color: #5B5B5B;
                margin-bottom: 20px;
                font-size: 28px;
                border-bottom: 3px solid #9A8F8F;
                padding-bottom: 10px;
            ">✨ Step 3: Revised Text</h2>

            <!-- 说明 -->
            <div style="
                background-color: rgba(255,255,255,0.7);
                padding: 15px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                <h4 style="color: #5B5B5B; margin-bottom: 10px;">Legend:</h4>
                <p style="color: #4CAF50; font-weight: bold; margin: 5px 0;">🟢 Green Bold: Unchanged sentences (compliant)</p>
                <p style="color: #333; margin: 5px 0;">⚫ Normal: Modified sentences (with original shown below)</p>
            </div>

            <!-- 修改后的文本 -->
            <div style="
                background-color: rgba(255,255,255,0.5);
                padding: 20px;
                border-radius: 10px;
                margin-bottom: 20px;
            ">
                {comparison_html}
            </div>

            <div style="
                text-align: center;
                color: #4A7C59;
                font-size: 18px;
                font-weight: bold;
                padding: 20px;
                background-color: rgba(74, 124, 89, 0.1);
                border-radius: 8px;
            ">🎉 All Steps Complete! Content audit finished.</div>
        </div>
    </div>
    """



# Create Gradio Blocks interface for better control
with gr.Blocks(
    title="🛡️ AdGuardian - AI Advertising Compliance Agent",
    theme=gr.themes.Soft()
) as demo:
    gr.Markdown("""
    # 🛡️ AdGuardian - AI Advertising Compliance Agent
    **Multi-Country · Multi-Language · Three-Stage Analysis · AI-Driven Version**

    This system uses advanced AI analysis to ensure advertising compliance across different countries and languages.
    Powered by multiple language models for intelligent advertising content understanding and regulatory compliance.
    """)

    with gr.Row():
        with gr.Column(scale=1):
            # 主要输入
            text_input = gr.Textbox(
                label="Text to Audit",
                placeholder="Please enter the text content to be audited...",
                lines=8
            )

            keywords_input = gr.Textbox(
                label="Keywords (Optional)",
                placeholder="Please enter keywords to mark, separated by commas",
                lines=2
            )

            # 新增选项
            with gr.Row():
                country_select = gr.Dropdown(
                    label="Regulatory Standards",
                    choices=["China", "USA", "UK", "Japan", "Korea", "Singapore", "Malaysia", "Other"],
                    value="USA"
                )

                language_select = gr.Dropdown(
                    label="Response Language",
                    choices=["简体中文", "繁体中文", "English", "日本語", "한국어"],
                    value="English"
                )

            with gr.Row():
                model_select = gr.Dropdown(
                    label="AI Model",
                    choices=[
                        "Qwen/Qwen3-8B (Free - SiliconFlow)",
                        "deepseek-ai/DeepSeek-V3-0324 (Paid - Nebius)",
                        "deepseek-ai/DeepSeek-R1-0528 (Paid - Nebius)",
                        "Qwen/Qwen3-235B-A22B (Paid - Nebius)",
                        "google/gemma-3-27b-it (Paid - Nebius, Vision)"
                    ],
                    value="Qwen/Qwen3-8B (Free - SiliconFlow)"
                )

            # 控制按钮
            with gr.Row():
                submit_btn = gr.Button("🚀 Start AI Analysis", variant="primary", scale=2)
                clear_btn = gr.Button("🗑️ Clear", variant="secondary", scale=1)

        with gr.Column(scale=2):
            # 输出区域 - 四个标签页
            with gr.Tabs():
                with gr.TabItem("🔍 Stage 1: Basic Analysis"):
                    stage1_output = gr.HTML(
                        value="<div style='text-align: center; padding: 50px; color: #888;'>Stage 1 results will appear here...</div>",
                        label="Stage 1 Results"
                    )

                with gr.TabItem("🎨 Stage 2: Detailed Annotation"):
                    stage2_output = gr.HTML(
                        value="<div style='text-align: center; padding: 50px; color: #888;'>Stage 2 results will appear here...</div>",
                        label="Stage 2 Results"
                    )

                with gr.TabItem("✨ Stage 3: Revision Suggestions"):
                    stage3_output = gr.HTML(
                        value="<div style='text-align: center; padding: 50px; color: #888;'>Stage 3 results will appear here...</div>",
                        label="Stage 3 Results"
                    )

                with gr.TabItem("📊 Summary"):
                    summary_output = gr.HTML(
                        value="<div style='text-align: center; padding: 50px; color: #888;'>Analysis summary will appear here...</div>",
                        label="Summary"
                    )

    # 示例区域
    gr.Markdown("### 📋 Examples")
    with gr.Row():
        example1_btn = gr.Button("📝 Example 1: Beauty Product (EN)", size="sm")
        example2_btn = gr.Button("⚡ Example 2: Energy Drink (EN)", size="sm")
        example3_btn = gr.Button("🏠 Example 3: Real Estate (中文)", size="sm")

    # 事件处理 - 使用四个输出
    submit_btn.click(
        fn=comprehensive_text_audit_streaming,
        inputs=[text_input, keywords_input, country_select, language_select, model_select],
        outputs=[stage1_output, stage2_output, stage3_output, summary_output]
    )

    clear_btn.click(
        fn=lambda: ("", "", "USA", "English", "Qwen/Qwen3-8B (Free - SiliconFlow)",
                   "<div style='text-align: center; padding: 50px; color: #888;'>Stage 1 results will appear here...</div>",
                   "<div style='text-align: center; padding: 50px; color: #888;'>Stage 2 results will appear here...</div>",
                   "<div style='text-align: center; padding: 50px; color: #888;'>Stage 3 results will appear here...</div>",
                   "<div style='text-align: center; padding: 50px; color: #888;'>Analysis summary will appear here...</div>"),
        outputs=[text_input, keywords_input, country_select, language_select, model_select, stage1_output, stage2_output, stage3_output, summary_output]
    )

    # 示例按钮事件处理
    example1_btn.click(
        fn=lambda: ("Revolutionary Anti-Aging Serum - Guaranteed to eliminate all wrinkles within 24 hours! Our scientifically proven formula contains 100% natural ingredients that will make you look 20 years younger instantly. Thousands of customers have experienced miraculous results overnight. This breakthrough serum is the ultimate solution for aging skin and will completely transform your appearance forever. No other product can match our incredible effectiveness.",
                   "anti-aging, wrinkles, natural, guaranteed", "USA", "English"),
        outputs=[text_input, keywords_input, country_select, language_select]
    )

    example2_btn.click(
        fn=lambda: ("SuperBoost Energy Drink - The most powerful energy formula ever created! Increases your energy levels by 800% and keeps you alert for 48 hours straight without any crash. Our secret blend of natural caffeine and exotic herbs will revolutionize your productivity forever. Professional athletes choose our drink because it's the only one that delivers real results. Completely safe and approved by leading sports scientists worldwide. One sip will change your life permanently.",
                   "energy drink, caffeine, performance, athletes", "USA", "English"),
        outputs=[text_input, keywords_input, country_select, language_select]
    )

    example3_btn.click(
        fn=lambda: ("豪华市中心公寓 - 史上最佳投资机会!该地区房产价值在过去一年中增长了1000%,绝对会继续上涨。这是千载难逢的致富机会,我们的独家开发项目保证年回报率50%。不要错过这个令人难以置信的交易,它将让您超越梦想变得富有!限时优惠,仅剩50个名额。立即加入,马上开始每周赚取10万元。成功有保障,我们的系统绝对可靠。",
                   "房地产, 投资, 保证回报, 豪华", "China", "简体中文"),
        outputs=[text_input, keywords_input, country_select, language_select]
    )


if __name__ == "__main__":
    demo.launch(
        max_threads=5,  # 增加并发线程数到5
        show_error=True,  # 显示错误信息
        share=False  # HF Space不需要share
    )