File size: 37,610 Bytes
13e139c
 
 
 
 
 
 
eaf5905
 
 
 
 
 
13e139c
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
76daf0f
13e139c
 
 
 
aec1143
13e139c
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
13e139c
 
 
 
 
 
 
aec1143
13e139c
 
eaf5905
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13e139c
c6145b5
aec1143
 
 
eaf5905
 
aec1143
 
 
 
 
 
eaf5905
aec1143
c6145b5
 
 
 
 
 
 
 
 
 
 
eaf5905
c6145b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13e139c
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
13e139c
aec1143
 
 
13e139c
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
13e139c
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
13e139c
 
 
 
 
 
 
 
 
 
aec1143
 
 
13e139c
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
13e139c
aec1143
 
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
aec1143
13e139c
 
aec1143
13e139c
aec1143
 
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
 
13e139c
 
 
 
 
 
 
 
 
 
b866834
 
 
 
 
 
 
 
 
 
 
 
 
86e1a52
 
 
 
 
 
 
 
 
 
 
 
 
b866834
 
 
 
 
86e1a52
b866834
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
b866834
13e139c
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
b866834
 
 
 
 
 
 
 
 
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
8c3cb3a
696932e
 
 
 
 
8c3cb3a
696932e
8c3cb3a
696932e
8c3cb3a
696932e
 
 
 
 
 
 
 
 
 
 
 
8c3cb3a
809ef06
696932e
 
 
 
8c3cb3a
 
696932e
 
8c3cb3a
 
696932e
8c3cb3a
696932e
 
 
 
8c3cb3a
 
696932e
 
8c3cb3a
696932e
 
 
8c3cb3a
696932e
 
8c3cb3a
 
696932e
8c3cb3a
696932e
 
 
 
8c3cb3a
 
696932e
 
8c3cb3a
696932e
 
 
 
8c3cb3a
 
696932e
13e139c
 
696932e
13e139c
 
 
 
 
 
 
 
aec1143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13e139c
 
aec1143
 
 
13e139c
 
 
 
 
 
aec1143
13e139c
 
 
aec1143
13e139c
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
 
 
aec1143
13e139c
 
 
 
aec1143
 
13e139c
 
 
aec1143
 
 
13e139c
 
aec1143
13e139c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec1143
13e139c
 
 
 
aec1143
13e139c
 
 
 
 
 
 
 
 
fee1fc0
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
"""
工程解題助手 (Engineering Problem Solver)
============================================
功能:學生拍照上傳電路學、靜力學、動力學等工程題目,
      由 Google Gemini 視覺模型逐步推導並給出最終答案。

部署:Hugging Face Spaces(Gradio SDK)

【v2 變更】2026-05-28
- 強化「電路學」system prompt:新增「相依電源(受控電源)解題子協定」
  針對 VCVS / CCVS / VCCS / CCCS 四種相依源,明確規範識別、約束方程、
  自檢、戴維寧/諾頓求 R_th 的測試源法。
- 詳見 CHANGES.md
"""

import os
import base64
import html as html_lib
from datetime import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional

import gradio as gr
from PIL import Image
import google.generativeai as genai


# ============================================================
# 1. 基本設定
# ============================================================
API_KEY = os.environ.get("GEMINI_API_KEY", "").strip()
MODEL_NAME = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash")

if API_KEY:
    genai.configure(api_key=API_KEY)
else:
    print("WARNING: GEMINI_API_KEY environment variable not set.")


# ============================================================
# 2. 系統提示詞
# ============================================================
BASE_INSTRUCTIONS = """請依照下列「六步驟解題法」回答:

**步驟 1:題目辨識**
仔細描述你在圖片中看到的內容(元件、數值、符號、座標、受力等),
確認沒有看錯。若圖片不清楚或資訊不足,請明確指出需要哪些補充資訊。

**步驟 2:已知與待求**
條列已知條件、待求量,並標註單位與符號。

**步驟 3:分析方法**
選擇適當的分析方法並說明為何使用該方法。

**步驟 4:逐步推導**
列出每一步驟的方程式與計算過程。
所有數學式請使用 LaTeX 語法:行內用 $...$、獨立式用 $$...$$、
矩陣用 \\begin{bmatrix}...\\end{bmatrix}、分數用 \\frac{a}{b}。

**步驟 5:數值驗算**
將最終答案代回原方程式驗證合理性。

**步驟 6:最終答案**
用 **粗體** 標示最終答案,並加上單位。

回答規範:一律使用繁體中文、SI 單位制、結構清楚(用 ## 與 ### 標題)。
"""


# ------------------------------------------------------------
# 2-A. 相依電源(受控電源)解題子協定
# ------------------------------------------------------------
# 這段子協定會在「電路學」科目下附加到系統提示詞末尾。
# 透過硬性結構強制 Gemini 不犯下列四種典型錯誤:
#   ① 誤判電源符號(菱形◇被當作圓形○)
#   ② 控制變數讀錯
#   ③ 漏寫約束方程
#   ④ 求 R_th 時把相依源也歸零
DEPENDENT_SOURCE_PROTOCOL = """

**【★ 相依電源(受控電源)解題子協定 ─ 含相依源題目必須嚴格遵守 ★】**

當電路含任何受控電源(VCVS、CCVS、VCCS、CCCS,符號為菱形 ◇)時,
若不遵守下列協定,答案幾乎必錯。請逐項執行:

**(A) 識別階段(必於「步驟 1:題目辨識」中完成)**
1. 電源符號形狀區分:**圓形 ○ = 獨立源;菱形 ◇ = 相依源(受控源)**。
   看到菱形必須明確指出類型(VCVS / CCVS / VCCS / CCCS 四選一)
   與電源值完整表達式(例如「$5\\,i_x$ V」、「$2\\,v_\\pi$ A」)。
   嚴禁將菱形誤判為獨立電源;也嚴禁省略乘數或下標。
2. 控制變數識別:明確指出控制變數是
   「**哪個元件上的電壓**(用 $v_\\varphi$、$v_x$ 等表示)」或
   「**哪個元件上流過的電流**(用 $i_x$、$i_\\phi$ 等表示)」,
   並標明 + 極性所在端 或 電流的參考方向(用箭頭描述)。
3. 若圖中標示模糊(下標看不清、極性/箭頭不明、乘數讀不出),
   必須在此階段明確列出「需補充資訊」,**禁止猜測**後再硬解。

**(B) 方程組階段(必於「步驟 4:逐步推導」中按下列順序執行)**
1. **第一條方程必須是「控制變數約束方程」**:把控制變數
   $i_x$、$v_\\varphi$ 等用節點電壓或網目電流表達。
   例:$i_x = (V_s - v_b)/R_1$ 或 $v_\\varphi = v_1 - v_2$。
2. 接著才寫 KCL / KVL,**每條方程旁註記**(KCL@節點X 或 KVL@網目Y)。
3. VCCS / CCCS 在 KCL 中以「箭頭尖端 = 流入該節點」為正號約定,
   並在式旁加註「(VCCS / CCCS)」提示。
4. 若 VCVS / CCVS 跨在兩個非接地節點之間 → 使用 **supernode** 技巧。
5. 若 CCCS / VCCS 在兩個網目的共用支路 → 使用 **supermesh** 技巧。

**(C) 自檢階段(必於「步驟 5:數值驗算」之前完成)**
1. 點算未知數數量 $N_u$ 與方程式數量 $N_e$。
   若 $N_e \\neq N_u$ → **確定漏寫約束方程**,停下重新檢查。
2. 把求出的數值代回**所有原始方程**(含控制變數約束方程)驗證。
3. 若控制變數為負值,必須說明這代表「實際方向與假設參考方向相反」。

**(D) 戴維寧 / 諾頓等效專屬規則(最關鍵!)**
若電路含**任何**相依源且要求 $R_\\text{th}$、$R_N$ 或諾頓等效電阻:
**▼ 嚴格禁止:把獨立源與相依源「全部歸零」後用 R 串並聯求等效電阻。 ▼**
必須使用以下兩法之一,且須在解答中明確聲明所用方法:

  **方法 ①:測試源法(test source method)**
  - 僅歸零所有**獨立源**(電壓源短路、電流源開路)。
  - **保留所有相依源不變**(這是與純電阻電路最大的差別)。
  - 在 a-b 端施加測試源:$v_T = 1$ V(或 $i_T = 1$ A)。
  - 解出對應的端口電流 $i_T$(或電壓 $v_T$)。
  - $R_\\text{th} = v_T / i_T$。

  **方法 ②:$V_\\text{oc} / i_\\text{sc}$ 法**
  - 保留原電路(含所有獨立源與相依源)。
  - 求 a-b 端開路電壓:$V_\\text{oc} = V_\\text{th}$。
  - 將 a-b 短路,求短路電流 $i_\\text{sc}$。
  - $R_\\text{th} = V_\\text{oc} / i_\\text{sc}$。

若電路只有相依源、沒有獨立源 → $V_\\text{th} = 0$,
僅能用方法 ①(測試源法)求 $R_\\text{th}$。

**(E) 常見錯誤檢查清單(每題解完前自我審視)**
- ✗ 把菱形 ◇ 看成圓形 ○(誤判為獨立源)
- ✗ 把控制變數方向看反($v_\\varphi = v_2 - v_1$ 與 $v_1 - v_2$ 差一個負號)
- ✗ 漏寫控制變數約束方程,導致方程組欠定(最常見)
- ✗ 求 $R_\\text{th}$ 時把相依源也歸零(最嚴重的災難)
- ✗ 把控制變數的下標、電源乘數看錯(例如把 $5\\,i_x$ 看成 $5\\,i$)
"""


SUBJECT_PROMPTS: Dict[str, str] = {
    # ===== 電機系課程 =====
    "電路學 (Circuit Analysis)": (
        "你是一位專精於電路學的大學教授,熟悉直流/交流電路、"
        "節點分析 (KCL)、網目分析 (KVL)、戴維寧/諾頓等效電路、"
        "重疊定理、相量分析、頻率響應、共振、運算放大器、二階電路暫態、"
        "受控電源(VCVS / CCVS / VCCS / CCCS)等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**電路學特別注意事項**:\n"
        "- 明確標示電流方向與電壓極性\n"
        "- 區分直流穩態與暫態分析\n"
        "- 交流電路請使用相量並標註角頻率\n"
        "- 若涉及 RC/RL/RLC 暫態,列出時間常數\n"
        + DEPENDENT_SOURCE_PROTOCOL
    ),
    "電子學 (Electronics)": (
        "你是一位專精於電子學的大學教授,熟悉半導體物理、二極體電路、"
        "雙極性電晶體 (BJT)、金氧半場效電晶體 (MOSFET)、小訊號模型、"
        "共射/共源/共集/共閘放大器、差動放大器、電流鏡、運算放大器、"
        "回授放大器、頻率響應、振盪器、功率放大器等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**電子學特別注意事項**:\n"
        "- 區分大訊號分析(DC 偏壓)與小訊號分析(增益、頻率響應)\n"
        "- 明確標示工作區(截止/飽和/三極/飽和區)\n"
        "- 計算 Q 點(IDQ、VDSQ 或 ICQ、VCEQ)\n"
        "- 使用混合 π 模型或 T 模型推導小訊號參數\n"
        + DEPENDENT_SOURCE_PROTOCOL  # 小訊號等效電路也充滿相依源,同樣適用
    ),
    "電磁學 (Electromagnetics)": (
        "你是一位專精於電磁學的大學教授,熟悉向量分析、靜電場、"
        "高斯定律、電位、電容、靜磁場、Ampère 定律、Biot-Savart 定律、"
        "電磁感應、Faraday 定律、Maxwell 方程組、平面波、傳輸線、"
        "Smith 圖、波導、天線輻射等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**電磁學特別注意事項**:\n"
        "- 明確標示座標系(直角/圓柱/球面)與單位向量\n"
        "- 區分靜場與時變場\n"
        "- 微分形式與積分形式的 Maxwell 方程式請正確使用\n"
        "- 標註介質的 ε、μ、σ\n"
    ),
    "電力電子學 (Power Electronics)": (
        "你是一位專精於電力電子學的大學教授,熟悉功率半導體元件"
        "(BJT、Power MOSFET、IGBT、Thyristor/SCR、GTO)、二極體整流器、"
        "相控整流器、AC 電壓控制、DC-DC 轉換器 (Buck、Boost、Buck-Boost、Cuk)、"
        "DC-AC 變頻器、PWM 調變、變壓器與磁性元件、馬達驅動、UPS 等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**電力電子學特別注意事項**:\n"
        "- 明確區分連續導通模式 (CCM) 與不連續導通模式 (DCM)\n"
        "- 計算輸入/輸出電壓比、電流漣波、責任週期 D\n"
        "- 標註開關元件的開/關狀態與導通損失\n"
        "- 注意功率因數 (PF) 與總諧波失真 (THD)\n"
    ),
    "超大型積體電路設計 (VLSI Design)": (
        "你是一位專精於 VLSI 設計的大學教授,熟悉 CMOS 製程、"
        "MOSFET 物理與 SPICE 模型、靜態 CMOS 邏輯閘設計、"
        "動態邏輯、傳輸閘、組合電路與時序電路、靜態時序分析 (STA)、"
        "Setup/Hold 時間、靜態與動態功耗、Wire delay、SRAM/DRAM 設計、"
        "Verilog/SystemVerilog、合成與佈線、低功耗設計、製程變異等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**VLSI 設計特別注意事項**:\n"
        "- 計算電晶體 W/L 比與驅動強度\n"
        "- 推導傳播延遲 tp,使用 RC 模型或 logical effort\n"
        "- 區分動態功耗 (CV²f)、短路功耗、漏電流功耗\n"
        "- 標註製程節點(如 28nm、7nm)對應的電壓與閾值\n"
    ),
    # ===== 其他工程課程 =====
    "靜力學 (Statics)": (
        "你是一位專精於靜力學的大學教授,熟悉力與力矩、自由體圖、"
        "平衡方程、桁架分析、構架與機器、摩擦、重心與形心、慣性矩等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**靜力學特別注意事項**:\n"
        "- 必須先畫(或文字描述)自由體圖,標示所有作用力\n"
        "- 明確列出 ΣFx=0、ΣFy=0、ΣM=0\n"
        "- 標註座標系統與正負方向慣例\n"
        "- 桁架分析請說明是節點法還是截面法\n"
    ),
    "動力學 (Dynamics)": (
        "你是一位專精於動力學的大學教授,熟悉質點運動學、剛體運動學、"
        "牛頓第二定律、功能定理、衝量-動量定理、角動量、振動學等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**動力學特別注意事項**:\n"
        "- 區分運動學與動力學\n"
        "- 明確說明參考座標系\n"
        "- 涉及向量者標註各分量方向\n"
    ),
    "工程數學 (Engineering Math)": (
        "你是一位專精於工程數學的大學教授,熟悉微積分、線性代數、"
        "常微分方程、偏微分方程、複變函數、傅立葉/拉普拉斯轉換等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**工程數學特別注意事項**:\n"
        "- 明確標註定義域、值域與邊界條件\n"
        "- 矩陣運算逐列展開\n"
        "- 微分方程註明階數與線性/非線性\n"
    ),
    "材料力學 (Mechanics of Materials)": (
        "你是一位專精於材料力學的大學教授,熟悉應力/應變、軸力、扭轉、"
        "彎曲、剪力/彎矩圖、變形、樑的撓度、Mohr 圓、破壞準則等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**材料力學特別注意事項**:\n"
        "- 區分正交應力與剪應力\n"
        "- 樑問題請繪製剪力圖 (V) 與彎矩圖 (M)\n"
        "- 標註正負號慣例\n"
    ),
    "熱力學 (Thermodynamics)": (
        "你是一位專精於熱力學的大學教授,熟悉熱力學第一/第二定律、"
        "理想氣體、Carnot/Otto/Rankine 循環、熵、焓、可用能、熱傳導等主題。\n\n"
        + BASE_INSTRUCTIONS
        + "\n\n**熱力學特別注意事項**:\n"
        "- 明確定義系統與邊界\n"
        "- 標註過程種類(等溫、絕熱、等壓、多變)\n"
        "- 引用熱力學表數值時請註明\n"
    ),
}


# ============================================================
# 3. Gemini API 呼叫核心
# ============================================================
def _extract_path(content: Any) -> Optional[str]:
    """從 Gradio messages 格式的 content 抽出檔案路徑。"""
    if isinstance(content, dict) and "path" in content:
        return content["path"]
    if isinstance(content, (list, tuple)) and len(content) >= 1:
        first = content[0]
        if isinstance(first, str) and Path(first).exists():
            return first
    return None


def build_gemini_history(history: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
    """將 Gradio messages 格式轉換為 Gemini chat history 格式。"""
    gemini_history = []
    for msg in history:
        role = "user" if msg["role"] == "user" else "model"
        content = msg["content"]
        parts: List[Any] = []

        path = _extract_path(content)
        if path:
            try:
                parts.append(Image.open(path))
            except Exception as e:
                parts.append(f"[image load failed: {e}]")
        elif isinstance(content, (list, tuple)):
            for item in content:
                if isinstance(item, str) and Path(item).exists():
                    try:
                        parts.append(Image.open(item))
                    except Exception:
                        parts.append(str(item))
                else:
                    parts.append(str(item))
        else:
            text = str(content).strip()
            if text:
                parts.append(text)

        if parts:
            gemini_history.append({"role": role, "parts": parts})
    return gemini_history


def stream_gemini_response(user_message, history, subject):
    """呼叫 Gemini API 並串流回傳結果。"""
    if not API_KEY:
        yield ("**錯誤**:尚未設定 `GEMINI_API_KEY`。\n\n"
               "請至 Hugging Face Space 的 Settings → Repository secrets 新增此金鑰。\n\n"
               "申請金鑰:https://aistudio.google.com/apikey")
        return

    system_prompt = SUBJECT_PROMPTS.get(subject, BASE_INSTRUCTIONS)

    try:
        model = genai.GenerativeModel(
            MODEL_NAME,
            system_instruction=system_prompt,
            generation_config={
                "temperature": 0.2,
                "top_p": 0.95,
                "max_output_tokens": 8192,
            },
        )
    except Exception as e:
        yield f"模型初始化失敗:{e}"
        return

    gemini_history = build_gemini_history(history)
    chat = model.start_chat(history=gemini_history)

    parts: List[Any] = []
    files = user_message.get("files", []) or []
    for f in files:
        try:
            parts.append(Image.open(f))
        except Exception as e:
            yield f"圖片載入失敗:{e}"
            return

    text = (user_message.get("text") or "").strip()
    if text:
        parts.append(text)
    elif files:
        parts.append("請依照六步驟解題法逐步分析這道題目。")
    else:
        yield "請上傳題目圖片或輸入文字描述。"
        return

    try:
        response = chat.send_message(parts, stream=True)
        full_text = ""
        for chunk in response:
            if chunk.text:
                full_text += chunk.text
                yield full_text
    except Exception as e:
        yield (f"Gemini API 呼叫失敗:{e}\n\n"
               "可能原因:API 金鑰錯誤、額度用盡、圖片過大或網路問題。")


# ============================================================
# 4. 匯出功能
# ============================================================
HTML_TEMPLATE = """<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>{title}</title>
<script>
window.MathJax = {{
  tex: {{
    inlineMath: [['$', '$'], ['\\\\(', '\\\\)']],
    displayMath: [['$$', '$$'], ['\\\\[', '\\\\]']],
    processEscapes: true
  }}
}};
</script>
<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<style>
  body {{ font-family: "Noto Sans TC", "Microsoft JhengHei", sans-serif;
         max-width: 880px; margin: 2em auto; padding: 0 1em; line-height: 1.7; color: #222; }}
  h1 {{ color: #1a4d8f; border-bottom: 3px solid #1a4d8f; padding-bottom: 0.3em; }}
  h2 {{ color: #2a6db5; margin-top: 1.8em; }}
  h3 {{ color: #444; }}
  .user {{ background: #f0f7ff; border-left: 4px solid #2a6db5; padding: 0.8em 1.2em; margin: 1em 0; border-radius: 4px; }}
  .assistant {{ background: #fdfbf3; border-left: 4px solid #c79a3a; padding: 0.8em 1.2em; margin: 1em 0; border-radius: 4px; }}
  .meta {{ color: #888; font-size: 0.9em; }}
  img {{ max-width: 100%; border: 1px solid #ddd; border-radius: 4px; margin: 0.5em 0; }}
  pre {{ background: #f6f6f6; padding: 0.8em; border-radius: 4px; overflow-x: auto; }}
  code {{ background: #f0f0f0; padding: 0.1em 0.4em; border-radius: 3px; }}
  hr {{ border: 0; border-top: 1px dashed #ccc; margin: 2em 0; }}
  .print-btn {{ position: fixed; top: 1em; right: 1em; padding: 0.6em 1.2em;
                background: #1a4d8f; color: white; border: none; border-radius: 4px;
                cursor: pointer; font-size: 1em; }}
  @media print {{ .print-btn {{ display: none; }} }}
</style>
</head>
<body>
<button class="print-btn" onclick="window.print()">列印或存為 PDF</button>
<h1>{title}</h1>
<p class="meta">產生時間:{timestamp} | 科目:{subject}</p>
<hr>
{body}
<hr>
<p class="meta">此份解答由 AI 輔助生成,僅供學習參考。請務必自行驗證每一步推導。</p>
<script>
  document.querySelectorAll('.markdown').forEach(el => {{
    const raw = el.textContent;
    el.innerHTML = marked.parse(raw);
  }});
  window.addEventListener('load', () => {{
    if (window.MathJax) MathJax.typesetPromise();
  }});
</script>
</body>
</html>
"""


def history_to_html(history, subject):
    """產生帶 MathJax 渲染的獨立 HTML 檔。"""
    body_parts = []

    def _embed_image(path):
        try:
            with open(path, "rb") as f:
                b64 = base64.b64encode(f.read()).decode()
            ext = Path(path).suffix.lstrip(".").lower() or "png"
            if ext == "jpg":
                ext = "jpeg"
            return f'<img src="data:image/{ext};base64,{b64}" alt="題目圖片">'
        except Exception:
            return f"<p>[圖片:{html_lib.escape(Path(path).name)}]</p>"

    for msg in history:
        role = msg["role"]
        content = msg["content"]
        cls = "user" if role == "user" else "assistant"
        label = "學生提問" if role == "user" else "教授解答"

        path = _extract_path(content)
        if path:
            body_parts.append(
                f'<div class="{cls}"><h3>{label}</h3>{_embed_image(path)}</div>'
            )
        elif isinstance(content, (list, tuple)):
            inner = [f"<h3>{label}</h3>"]
            for item in content:
                if isinstance(item, str) and Path(item).exists():
                    inner.append(_embed_image(item))
                else:
                    inner.append(f'<div class="markdown">{html_lib.escape(str(item))}</div>')
            body_parts.append(f'<div class="{cls}">{"".join(inner)}</div>')
        else:
            body_parts.append(
                f'<div class="{cls}"><h3>{label}</h3>'
                f'<div class="markdown">{html_lib.escape(str(content))}</div></div>'
            )

    return HTML_TEMPLATE.format(
        title=f"解題紀錄 — {subject}",
        timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        subject=html_lib.escape(subject),
        body="\n".join(body_parts),
    )


def export_html(history, subject):
    """匯出為 HTML 檔案。"""
    if not history:
        return None
    html_text = history_to_html(history, subject)
    out_dir = Path("/tmp") if Path("/tmp").exists() else Path(".")
    filename = f"solution_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
    out_path = out_dir / filename
    out_path.write_text(html_text, encoding="utf-8")
    return str(out_path)


def _register_cjk_font():
    """搜尋並註冊系統 CJK TTF 字體(嵌入 PDF),找不到則回傳 None。"""
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont

    # 已註冊則直接回傳
    try:
        if "CJK" in pdfmetrics.getRegisteredFontNames():
            return "CJK"
    except Exception:
        pass

    candidates = [
        # 楷體 (AR PL UKai) — TrueType,reportlab 完全支援,使用者偏好
        "/usr/share/fonts/truetype/arphic/ukai.ttc",
        "/usr/share/fonts/arphic-ukai/ukai.ttc",
        "/usr/share/fonts/truetype/cwtex/cwTeXKai-zhonly.ttf",
        # 黑體後備 (WenQuanYi)
        "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
        "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
        "/usr/share/fonts/wqy-microhei/wqy-microhei.ttc",
        "/usr/share/fonts/wqy-zenhei/wqy-zenhei.ttc",
        # 明體後備 (AR PL UMing)
        "/usr/share/fonts/truetype/arphic/uming.ttc",
        "/usr/share/fonts/arphic-uming/uming.ttc",
        # Noto CJK (CFF, reportlab 可能不支援) — 後備
        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
        "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
        "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc",
        "/usr/share/fonts/truetype/noto/NotoSerifCJK-Regular.ttc",
        "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc",
        # Windows / macOS
        "C:/Windows/Fonts/msjh.ttc",
        "C:/Windows/Fonts/msjh.ttf",
        "/Library/Fonts/PingFang.ttc",
    ]
    for p in candidates:
        if Path(p).exists():
            try:
                pdfmetrics.registerFont(TTFont("CJK", p, subfontIndex=0))
                return "CJK"
            except Exception as e:
                print(f"font register fail {p}: {e}")

    # fc-list 找系統中第一個中文字體
    try:
        import subprocess
        r = subprocess.run(
            ["fc-list", ":lang=zh", "file"],
            capture_output=True, text=True, timeout=5,
        )
        for line in r.stdout.splitlines():
            p = line.split(":")[0].strip()
            if p and Path(p).exists():
                try:
                    pdfmetrics.registerFont(TTFont("CJK", p, subfontIndex=0))
                    return "CJK"
                except Exception:
                    continue
    except Exception:
        pass

    return None


def export_pdf(history, subject):
    """匯出為 PDF 檔案(嵌入中文字體)。"""
    if not history:
        return None
    try:
        from reportlab.lib.pagesizes import A4
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.units import cm
        from reportlab.lib.enums import TA_LEFT
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.cidfonts import UnicodeCIDFont
        from reportlab.platypus import (
            SimpleDocTemplate, Paragraph, Spacer, Image as RLImage,
        )
    except ImportError:
        return None

    # 優先使用嵌入式 TTF 字體;失敗才退回 CID(依賴閱讀器有字體)
    cjk_font = _register_cjk_font()
    if not cjk_font:
        try:
            pdfmetrics.registerFont(UnicodeCIDFont("STSong-Light"))
            cjk_font = "STSong-Light"
        except Exception:
            cjk_font = "Helvetica"
    print(f"PDF using font: {cjk_font}")

    out_dir = Path("/tmp") if Path("/tmp").exists() else Path(".")
    filename = f"solution_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
    out_path = out_dir / filename

    doc = SimpleDocTemplate(
        str(out_path), pagesize=A4,
        leftMargin=2*cm, rightMargin=2*cm,
        topMargin=2*cm, bottomMargin=2*cm,
    )
    styles = getSampleStyleSheet()
    title_style = ParagraphStyle(
        "TitleCJK", parent=styles["Title"],
        fontName=cjk_font, fontSize=20, leading=26, alignment=TA_LEFT,
    )
    h2_style = ParagraphStyle(
        "H2CJK", parent=styles["Heading2"],
        fontName=cjk_font, fontSize=14, leading=20, textColor="#1a4d8f",
    )
    body_style = ParagraphStyle(
        "BodyCJK", parent=styles["BodyText"],
        fontName=cjk_font, fontSize=11, leading=17,
    )
    meta_style = ParagraphStyle(
        "MetaCJK", parent=styles["BodyText"],
        fontName=cjk_font, fontSize=9, textColor="#888888",
    )

    story = []
    story.append(Paragraph(f"解題紀錄 — {html_lib.escape(subject)}", title_style))
    story.append(Paragraph(
        f"產生時間:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
        meta_style,
    ))
    story.append(Spacer(1, 0.5*cm))

    for msg in history:
        role = msg["role"]
        content = msg["content"]
        label = "學生提問" if role == "user" else "教授解答"
        story.append(Paragraph(label, h2_style))

        path = _extract_path(content)
        if path:
            try:
                img = RLImage(path, width=14*cm, height=10*cm, kind="proportional")
                story.append(img)
                story.append(Spacer(1, 0.2*cm))
            except Exception:
                story.append(Paragraph(f"[圖片:{Path(path).name}]", body_style))
        elif isinstance(content, (list, tuple)):
            for item in content:
                if isinstance(item, str) and Path(item).exists():
                    try:
                        img = RLImage(item, width=14*cm, height=10*cm, kind="proportional")
                        story.append(img)
                        story.append(Spacer(1, 0.2*cm))
                    except Exception:
                        story.append(Paragraph(f"[圖片:{Path(item).name}]", body_style))
                else:
                    text = html_lib.escape(str(item)).replace("\n", "<br/>")
                    story.append(Paragraph(text, body_style))
        else:
            text = html_lib.escape(str(content)).replace("\n", "<br/>")
            story.append(Paragraph(text, body_style))
        story.append(Spacer(1, 0.4*cm))

    story.append(Spacer(1, 0.5*cm))
    story.append(Paragraph(
        "此份解答由 AI 輔助生成,僅供學習參考。請務必自行驗證每一步推導。",
        meta_style,
    ))

    try:
        doc.build(story)
        return str(out_path)
    except Exception as e:
        print(f"PDF generation failed: {e}")
        return None


# ============================================================
# 5. Gradio 介面
# ============================================================
THEME = gr.themes.Soft(primary_hue="blue", secondary_hue="amber")


# === 浮水印 SVG(四角:AI / 機器人 / 無人機 / IC)===
_WM_AI = """<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200' fill='none' stroke='%2300D4FF' stroke-width='1.5'><circle cx='40' cy='60' r='5' fill='%2300D4FF'/><circle cx='40' cy='100' r='5' fill='%2300D4FF'/><circle cx='40' cy='140' r='5' fill='%2300D4FF'/><circle cx='100' cy='40' r='5' fill='%2300D4FF'/><circle cx='100' cy='80' r='5' fill='%2300D4FF'/><circle cx='100' cy='120' r='5' fill='%2300D4FF'/><circle cx='100' cy='160' r='5' fill='%2300D4FF'/><circle cx='160' cy='70' r='5' fill='%2300D4FF'/><circle cx='160' cy='130' r='5' fill='%2300D4FF'/><line x1='40' y1='60' x2='100' y2='40'/><line x1='40' y1='60' x2='100' y2='80'/><line x1='40' y1='60' x2='100' y2='120'/><line x1='40' y1='100' x2='100' y2='40'/><line x1='40' y1='100' x2='100' y2='80'/><line x1='40' y1='100' x2='100' y2='120'/><line x1='40' y1='100' x2='100' y2='160'/><line x1='40' y1='140' x2='100' y2='80'/><line x1='40' y1='140' x2='100' y2='120'/><line x1='40' y1='140' x2='100' y2='160'/><line x1='100' y1='40' x2='160' y2='70'/><line x1='100' y1='80' x2='160' y2='70'/><line x1='100' y1='80' x2='160' y2='130'/><line x1='100' y1='120' x2='160' y2='70'/><line x1='100' y1='120' x2='160' y2='130'/><line x1='100' y1='160' x2='160' y2='130'/></svg>"""

_WM_ROBOT = """<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200' fill='none' stroke='%23FFB627' stroke-width='2'><rect x='60' y='40' width='80' height='70' rx='8'/><line x1='100' y1='40' x2='100' y2='25'/><circle cx='100' cy='22' r='4' fill='%23FFB627'/><circle cx='80' cy='70' r='6' fill='%23FFB627'/><circle cx='120' cy='70' r='6' fill='%23FFB627'/><rect x='80' y='90' width='40' height='6' rx='3'/><rect x='50' y='115' width='100' height='65' rx='6'/><rect x='75' y='130' width='50' height='35' rx='3'/></svg>"""

_WM_DRONE = """<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 220 220' fill='none' stroke='%23A663CC' stroke-width='2'><circle cx='110' cy='110' r='15'/><rect x='98' y='98' width='24' height='24' rx='4'/><line x1='110' y1='110' x2='50' y2='50'/><line x1='110' y1='110' x2='170' y2='50'/><line x1='110' y1='110' x2='50' y2='170'/><line x1='110' y1='110' x2='170' y2='170'/><circle cx='50' cy='50' r='28' stroke-dasharray='4 4'/><circle cx='50' cy='50' r='20'/><circle cx='170' cy='50' r='28' stroke-dasharray='4 4'/><circle cx='170' cy='50' r='20'/><circle cx='50' cy='170' r='28' stroke-dasharray='4 4'/><circle cx='50' cy='170' r='20'/><circle cx='170' cy='170' r='28' stroke-dasharray='4 4'/><circle cx='170' cy='170' r='20'/></svg>"""

_WM_IC = """<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 240 200' fill='none' stroke='%23A8DADC' stroke-width='1.5'><rect x='80' y='65' width='80' height='70' rx='2'/><line x1='95' y1='55' x2='95' y2='65'/><line x1='110' y1='55' x2='110' y2='65'/><line x1='125' y1='55' x2='125' y2='65'/><line x1='140' y1='55' x2='140' y2='65'/><line x1='95' y1='135' x2='95' y2='145'/><line x1='110' y1='135' x2='110' y2='145'/><line x1='125' y1='135' x2='125' y2='145'/><line x1='140' y1='135' x2='140' y2='145'/><line x1='70' y1='80' x2='80' y2='80'/><line x1='70' y1='95' x2='80' y2='95'/><line x1='70' y1='110' x2='80' y2='110'/><line x1='70' y1='125' x2='80' y2='125'/><line x1='160' y1='80' x2='170' y2='80'/><line x1='160' y1='95' x2='170' y2='95'/><line x1='160' y1='110' x2='170' y2='110'/><line x1='160' y1='125' x2='170' y2='125'/></svg>"""

import urllib.parse as _urlparse
def _svg_data_url(svg_str):
    return "data:image/svg+xml;utf8," + _urlparse.quote(svg_str, safe="")

_WM_AI_URL = _svg_data_url(_WM_AI)
_WM_ROBOT_URL = _svg_data_url(_WM_ROBOT)
_WM_DRONE_URL = _svg_data_url(_WM_DRONE)
_WM_IC_URL = _svg_data_url(_WM_IC)


CUSTOM_CSS = f"""
/* 工程解題助手 · 簡約浮水印版(不影響元件功能)*/

.gradio-container {{
    max-width: 1180px !important;
}}

/* 浮水印(fixed 四角,pointer-events: none)*/
body::before, body::after {{
    content: "";
    position: fixed;
    width: 220px;
    height: 220px;
    pointer-events: none;
    opacity: 0.08;
    z-index: 0;
    background-repeat: no-repeat;
    background-size: contain;
}}
body::before {{
    top: 90px; left: 20px;
    background-image: url("{_WM_AI_URL}");
}}
body::after {{
    bottom: 30px; right: 20px;
    background-image: url("{_WM_IC_URL}");
}}
.gradio-container::before, .gradio-container::after {{
    content: "";
    position: fixed;
    width: 200px;
    height: 200px;
    pointer-events: none;
    opacity: 0.08;
    z-index: 0;
    background-repeat: no-repeat;
    background-size: contain;
}}
.gradio-container::before {{
    top: 110px; right: 30px;
    background-image: url("{_WM_ROBOT_URL}");
}}
.gradio-container::after {{
    bottom: 80px; left: 30px;
    background-image: url("{_WM_DRONE_URL}");
}}

footer {{
    display: none !important;
}}
"""


LATEX_DELIMS = [
    {"left": "$$", "right": "$$", "display": True},
    {"left": "$", "right": "$", "display": False},
    {"left": "\\[", "right": "\\]", "display": True},
    {"left": "\\(", "right": "\\)", "display": False},
]


def add_user_message(user_input, history):
    history = history or []
    files = user_input.get("files", []) or []
    text = (user_input.get("text") or "").strip()

    for f in files:
        history.append({"role": "user", "content": {"path": f}})
    if text:
        history.append({"role": "user", "content": text})

    return history, gr.MultimodalTextbox(value=None, interactive=False)


def bot_respond(history, subject):
    if not history:
        yield history
        return

    last_user_idx = len(history) - 1
    while last_user_idx >= 0 and history[last_user_idx]["role"] == "user":
        last_user_idx -= 1
    current_user_msgs = history[last_user_idx + 1:]

    text_parts = []
    file_parts = []
    for m in current_user_msgs:
        c = m["content"]
        path = _extract_path(c)
        if path:
            file_parts.append(path)
        elif isinstance(c, (list, tuple)):
            for x in c:
                if isinstance(x, str) and Path(x).exists():
                    file_parts.append(x)
                else:
                    text_parts.append(str(x))
        else:
            text_parts.append(str(c))

    user_msg = {"text": "\n".join(text_parts), "files": file_parts}
    past_history = history[: last_user_idx + 1]

    history.append({"role": "assistant", "content": ""})
    for partial in stream_gemini_response(user_msg, past_history, subject):
        history[-1]["content"] = partial
        yield history


def enable_input():
    return gr.MultimodalTextbox(interactive=True)


def clear_history():
    return [], None


def build_app():
    with gr.Blocks(theme=THEME, css=CUSTOM_CSS, title="工程解題助手") as demo:
        gr.Markdown(
            "# 工程解題助手 — AI Engineering Problem Solver\n"
            "上傳題目照片,AI 教授會逐步推導並給出最終答案。\n"
            "支援 **電路學、靜力學、動力學、工程數學、材料力學、熱力學**。"
        )

        with gr.Row():
            subject_dd = gr.Dropdown(
                choices=list(SUBJECT_PROMPTS.keys()),
                value="電路學 (Circuit Analysis)",
                label="選擇科目",
                interactive=True,
                scale=3,
            )
            clear_btn = gr.Button("清除對話", variant="secondary", scale=1)

        chatbot = gr.Chatbot(
            label="解題對話",
            type="messages",
            height=520,
            show_copy_button=True,
            latex_delimiters=LATEX_DELIMS,
            avatar_images=(None, None),
            placeholder="請拍照或上傳題目圖片開始解題。可同時上傳多張圖。",
        )

        chat_input = gr.MultimodalTextbox(
            interactive=True,
            file_count="multiple",
            file_types=["image"],
            placeholder="輸入文字(可選),或點迴紋針上傳題目照片,然後按 Enter 送出…",
            show_label=False,
        )

        with gr.Row():
            export_html_btn = gr.Button("匯出 HTML(含 LaTeX 渲染)", variant="secondary")
            export_pdf_btn = gr.Button("匯出 PDF", variant="secondary")
        export_file = gr.File(label="下載解答檔案", interactive=False)

        gr.Markdown(
            "**提示**:LaTeX 數學式會在對話視窗中自動渲染。"
            "匯出 HTML 後可在瀏覽器中按「列印或存為 PDF」獲得完美排版的 PDF。"
            "本工具僅為學習輔助,所有解答請務必自行驗證。"
        )

        chat_input.submit(
            add_user_message,
            [chat_input, chatbot],
            [chatbot, chat_input],
            queue=False,
        ).then(
            bot_respond,
            [chatbot, subject_dd],
            [chatbot],
        ).then(
            enable_input,
            None,
            [chat_input],
            queue=False,
        )

        clear_btn.click(clear_history, None, [chatbot, export_file], queue=False)

        export_html_btn.click(
            export_html,
            [chatbot, subject_dd],
            [export_file],
        )
        export_pdf_btn.click(
            export_pdf,
            [chatbot, subject_dd],
            [export_file],
        )

    return demo


if __name__ == "__main__":
    app = build_app()
    app.launch()