-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathForm1.cs
More file actions
1766 lines (1503 loc) · 66.1 KB
/
Form1.cs
File metadata and controls
1766 lines (1503 loc) · 66.1 KB
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
using Gma.System.MouseKeyHook;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows.Forms;
using Tesseract;
using static GeminiClient;
namespace ScreenOCRTranslator
{
public partial class Form1 : Form
{
private GeminiClient geminiClient;
private System.Windows.Forms.Timer monitorTimer;
private Point lastMousePosition;
private DateTime lastMoveTime;
private bool isMonitoring = false;
private IKeyboardMouseEvents globalHook;
private bool isQPressed = false;
private bool isLeftMouseDown = false;
private bool isSelecting = false;
private Rectangle lastCapturedRegion;
private TranslationOverlayForm _overlay;
private CursorHintForm _cursorHint;
private NotifyIcon _trayIcon;
private ContextMenuStrip _trayMenu;
private bool _allowExit = false;
private DailyQuotaTracker _quotaTracker;
private QuotaBoardForm _quotaBoard;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmbModel.SelectedIndex = 0;
cmbLanguage.SelectedIndex = 3;
cmbTranslationMode.SelectedIndex = 1; // 預設 OCR 模式
cmbModel_Pixtral.Items.Clear();
cmbModel_Pixtral.Items.AddRange(new object[]
{
"mistralai/Pixtral-12B-2409"
});
cmbModel_MistralPixtral.Items.Clear();
cmbModel_MistralPixtral.Items.AddRange(new object[]
{
"pixtral-large-latest",
"pixtral-large-2411"
});
cmbModel_Llama4.Items.Clear();
cmbModel_Llama4.Items.AddRange(new object[]
{
"meta-llama/llama-4-scout-17b-16e-instruct"
});
cmbModel_Pixtral.SelectedIndex = 0;
cmbModel_MistralPixtral.SelectedIndex = 0;
cmbModel_Llama4.SelectedIndex = 0;
// 載入儲存的 API Key 和模型
txtApiKey.Text = Properties.Settings.Default.ApiKey;
string savedModel = Properties.Settings.Default.ModelName;
if (!string.IsNullOrEmpty(savedModel))
{
int index = cmbModel.Items.IndexOf(savedModel);
if (index >= 0)
cmbModel.SelectedIndex = index;
}
txtApiKey_Pixtral.Text = Properties.Settings.Default.ApiKey_Pixtral;
string savedPixtralModel = Properties.Settings.Default.ModelName_Pixtral;
if (!string.IsNullOrEmpty(savedPixtralModel))
{
int index = cmbModel_Pixtral.Items.IndexOf(savedPixtralModel);
if (index >= 0)
cmbModel_Pixtral.SelectedIndex = index;
}
txtApiKey_MistralPixtral.Text = Properties.Settings.Default.ApiKey_MistralPixtral;
string savedMistralPixtralModel = Properties.Settings.Default.ModelName_MistralPixtral;
if (!string.IsNullOrEmpty(savedMistralPixtralModel))
{
int index = cmbModel_MistralPixtral.Items.IndexOf(savedMistralPixtralModel);
if (index >= 0)
cmbModel_MistralPixtral.SelectedIndex = index;
}
txtApiKey_Llama4.Text = Properties.Settings.Default.ApiKey_Llama4;
string savedLlama4Model = Properties.Settings.Default.ModelName_Llama4;
if (!string.IsNullOrEmpty(savedLlama4Model))
{
int index = cmbModel_Llama4.Items.IndexOf(savedLlama4Model);
if (index >= 0)
cmbModel_Llama4.SelectedIndex = index;
}
cmbTranslationMode.SelectedIndex = Properties.Settings.Default.TranslationModeIndex;
cmbLanguage.SelectedIndex = Properties.Settings.Default.LanguageModeIndex;
numOverlaySeconds.Value = Math.Max(numOverlaySeconds.Minimum,
Math.Min(numOverlaySeconds.Maximum, Properties.Settings.Default.OverlaySeconds));
monitorTimer = new System.Windows.Forms.Timer();
monitorTimer.Interval = 200; // 每 200ms 檢查一次滑鼠
monitorTimer.Tick += MonitorTimer_Tick;
globalHook = Hook.GlobalEvents();
globalHook.KeyDown += GlobalHook_KeyDown;
globalHook.KeyUp += GlobalHook_KeyUp;
globalHook.MouseDownExt += GlobalHook_MouseDownExt;
globalHook.MouseUpExt += GlobalHook_MouseUpExt;
linkLabel1.Links.Clear();
linkLabel1.Links.Add(0, linkLabel1.Text.Length, "https://aistudio.google.com/api-keys"); // LinkData 存網址
linkLabel_Pixtral.Text = "前往查看Pixtral-12B-2409 (vLLM路線)";
linkLabel_Pixtral.Links.Clear();
linkLabel_Pixtral.Links.Add(0, linkLabel_Pixtral.Text.Length, "https://huggingface.co/mistralai/Pixtral-12B-2409");
linkLabel_MistralPixtral.Text = "前往取得Mistral API key";
linkLabel_MistralPixtral.Links.Clear();
linkLabel_MistralPixtral.Links.Add(0, linkLabel_MistralPixtral.Text.Length, "https://console.mistral.ai/api-keys/");
linkLabel_Llama4.Text = "前往取得Groq API key";
linkLabel_Llama4.Links.Clear();
linkLabel_Llama4.Links.Add(0, linkLabel_Llama4.Text.Length, "https://console.groq.com/keys");
InitializeTrayIcon();
_quotaTracker = DailyQuotaTracker.LoadOrCreate(Path.Combine(Application.StartupPath, "usage_daily.json"));
_quotaTracker.EnsureToday();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (!_allowExit && e.CloseReason == CloseReason.UserClosing)
{
var choice = MessageBox.Show(
"請選擇:\n是(Y):關閉程式\n否(N):縮小到右下角常駐\n取消:維持目前視窗",
"關閉選項",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);
if (choice == DialogResult.Yes)
{
_allowExit = true;
}
else if (choice == DialogResult.No)
{
e.Cancel = true;
HideToTray();
return;
}
else
{
e.Cancel = true;
return;
}
}
Properties.Settings.Default.ApiKey = txtApiKey.Text.Trim();
Properties.Settings.Default.ModelName = cmbModel.SelectedItem?.ToString();
Properties.Settings.Default.ApiKey_Pixtral = txtApiKey_Pixtral.Text.Trim();
Properties.Settings.Default.ModelName_Pixtral = cmbModel_Pixtral.SelectedItem?.ToString();
Properties.Settings.Default.ApiKey_MistralPixtral = txtApiKey_MistralPixtral.Text.Trim();
Properties.Settings.Default.ModelName_MistralPixtral = cmbModel_MistralPixtral.SelectedItem?.ToString();
Properties.Settings.Default.ApiKey_Llama4 = txtApiKey_Llama4.Text.Trim();
Properties.Settings.Default.ModelName_Llama4 = cmbModel_Llama4.SelectedItem?.ToString();
Properties.Settings.Default.TranslationModeIndex = cmbTranslationMode.SelectedIndex;
Properties.Settings.Default.LanguageModeIndex = cmbLanguage.SelectedIndex;
Properties.Settings.Default.OverlaySeconds = (int)numOverlaySeconds.Value;
Properties.Settings.Default.Save(); // 寫入設定
_quotaTracker?.Save();
globalHook?.Dispose();
_cursorHint?.Dispose();
_trayIcon?.Dispose();
_trayMenu?.Dispose();
}
private void btnQuotaBoard_Click(object sender, EventArgs e)
{
ShowQuotaBoard();
}
private void ShowQuotaBoard()
{
_quotaTracker?.EnsureToday();
if (_quotaBoard == null || _quotaBoard.IsDisposed)
{
_quotaBoard = new QuotaBoardForm();
_quotaBoard.FormClosed += (s, e) => _quotaBoard = null;
}
var rows = _quotaTracker?.GetSnapshot(BuildLlmCredentials()) ?? new List<DailyQuotaEntry>();
_quotaBoard.UpdateRows(rows, DateTime.Now);
_quotaBoard.Show();
_quotaBoard.BringToFront();
}
private void InitializeTrayIcon()
{
_trayMenu = new ContextMenuStrip();
_trayMenu.Items.Add("開啟主視窗", null, (s, e) => ShowFromTray());
_trayMenu.Items.Add("結束", null, (s, e) => ExitApplication());
_trayIcon = new NotifyIcon
{
Text = "ScreenOCRTranslator",
Icon = this.Icon,
Visible = false,
ContextMenuStrip = _trayMenu
};
_trayIcon.DoubleClick += (s, e) => ShowFromTray();
}
private void HideToTray()
{
ShowInTaskbar = false;
Hide();
if (_trayIcon != null)
{
_trayIcon.Visible = true;
_trayIcon.ShowBalloonTip(1200, "ScreenOCRTranslator", "已縮小到右下角常駐。", ToolTipIcon.Info);
}
}
private void ShowFromTray()
{
Show();
WindowState = FormWindowState.Normal;
ShowInTaskbar = true;
Activate();
if (_trayIcon != null)
{
_trayIcon.Visible = false;
}
}
private void ExitApplication()
{
_allowExit = true;
_trayIcon.Visible = false;
Close();
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (WindowState == FormWindowState.Minimized)
{
HideToTray();
}
}
private void btnCapture_Click(object sender, EventArgs e)
{
// 顯示選取視窗
using (var selector = new SelectionForm())
{
if (selector.ShowDialog() == DialogResult.OK)
{
Rectangle captureRect = selector.SelectedRectangle;
// 擷取畫面該範圍
Bitmap captured = new Bitmap(captureRect.Width, captureRect.Height);
using (Graphics g = Graphics.FromImage(captured))
{
g.CopyFromScreen(captureRect.Location, Point.Empty, captureRect.Size);
}
lastCapturedRegion = captureRect; // ✅ 存起來方便之後畫文字用
picturePreview.Image = captured; // 顯示原圖以供除錯
// OCR 辨識(使用選擇的語言)
string langCode = GetSelectedLanguageCode();
var ocr = new TesseractOcrProcessor(langCode, picturePreview);
txtResult.Text = "辨識中...";
string text = ocr.PerformOCR(captured);
txtResult.Text = text;
}
}
}
private Bitmap CaptureCursorArea(int width = 300, int height = 150)
{
Point cursorPos = Cursor.Position;
int x = Math.Max(0, cursorPos.X - width / 2);
int y = Math.Max(0, cursorPos.Y - height / 2);
Rectangle captureRect = new Rectangle(x, y, width, height);
Bitmap bmp = new Bitmap(captureRect.Width, captureRect.Height);
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(captureRect.Location, Point.Empty, captureRect.Size);
}
return bmp;
}
private void btnStartStop_Click(object sender, EventArgs e)
{
if (!isMonitoring)
{
// ⚠ 初始化 GeminiClient
string apiKey = txtApiKey.Text.Trim();
string model = cmbModel.SelectedItem?.ToString();
if (string.IsNullOrEmpty(apiKey) || string.IsNullOrEmpty(model))
{
MessageBox.Show("請輸入 API Key 並選擇模型");
return;
}
geminiClient = new GeminiClient(apiKey, model); // ✅ 修正點
isMonitoring = true;
btnStartStop.Text = "停止";
lblStatus.Text = "滑鼠偵測中...";
lblStatus.ForeColor = Color.LightGreen;
lastMousePosition = Cursor.Position;
lastMoveTime = DateTime.Now;
monitorTimer.Start();
}
else
{
isMonitoring = false;
btnStartStop.Text = "啟動";
lblStatus.Text = "已停止";
lblStatus.ForeColor = Color.DarkRed;
monitorTimer.Stop();
}
}
private async void MonitorTimer_Tick(object sender, EventArgs e)
{
var currentPos = Cursor.Position;
if (currentPos != lastMousePosition)
{
lastMousePosition = currentPos;
lastMoveTime = DateTime.Now;
return;
}
int idleSeconds = (int)numIdleSeconds.Value;
if ((DateTime.Now - lastMoveTime).TotalSeconds >= idleSeconds)
{
monitorTimer.Stop(); // 暫停監聽避免重複觸發
lblStatus.Text = "擷取中...";
Bitmap img = CaptureCursorArea();
txtResult.Text = "辨識中...";
string langCode = GetSelectedLanguageCode();
var ocr = new TesseractOcrProcessor(langCode, picturePreview); // 這樣圖片才會顯示
string text = ocr.PerformOCR(img);
txtResult.Text = text;
//string result = await geminiClient.SendImageForOCRAndTranslate(img);
//txtResult.Text = result;
lastMoveTime = DateTime.Now;
monitorTimer.Start(); // 再次啟動
lblStatus.Text = "滑鼠偵測中...";
}
}
public class TesseractOcrProcessor
{
private readonly string _language;
private readonly PictureBox _previewControl;
public TesseractOcrProcessor(string language = "eng", PictureBox previewControl = null)
{
_language = language;
_previewControl = previewControl;
}
public string PerformOCR(Bitmap image)
{
// 將圖片放大 3 倍
Bitmap scaled = new Bitmap(image, image.Width * 3, image.Height * 3);
// 轉為灰階
Bitmap gray = new Bitmap(image.Width, image.Height);
using (Graphics g = Graphics.FromImage(gray))
{
var colorMatrix = new ColorMatrix(new float[][]
{
new float[] { 0.3f, 0.3f, 0.3f, 0, 0 },
new float[] { 0.59f, 0.59f, 0.59f, 0, 0 },
new float[] { 0.11f, 0.11f, 0.11f, 0, 0 },
new float[] { 0, 0, 0, 1, 0 },
new float[] { 0, 0, 0, 0, 1 }
});
var attributes = new ImageAttributes();
attributes.SetColorMatrix(colorMatrix);
g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
}
// 加上銳化處理
gray = ApplySharpenFilter(gray);
// 自動 threshold:計算整張圖片的平均灰階亮度
int total = 0;
for (int y = 0; y < gray.Height; y++)
{
for (int x = 0; x < gray.Width; x++)
{
Color pixel = gray.GetPixel(x, y);
total += pixel.R; // 灰階圖 RGB 相同
}
}
int avg = total / (gray.Width * gray.Height);
int threshold = avg; // 使用平均亮度作為臨界值(類似 adaptive)
// 黑白二值化
Bitmap binary = new Bitmap(gray.Width, gray.Height);
for (int y = 0; y < gray.Height; y++)
{
for (int x = 0; x < gray.Width; x++)
{
Color pixel = gray.GetPixel(x, y);
Color newColor = (pixel.R > threshold) ? Color.White : Color.Black;
binary.SetPixel(x, y, newColor);
}
}
if (IsMostlyDark(binary))
{
binary = InvertImage(binary);
}
// 顯示處理後圖片(方便 debug)
_previewControl.Image = binary; // ✅ 這裡要先傳入 previewControl(例如 PictureBox)
// 使用 Tesseract 進行辨識
using (var engine = new TesseractEngine(@"./tessdata", _language, EngineMode.LstmOnly))
{
// 小區域框選:PSM 6 通常最穩
engine.DefaultPageSegMode = PageSegMode.SingleBlock;
// 避免截圖被當成低 DPI 影像
engine.SetVariable("user_defined_dpi", "300");
// 如果你原本的 binary 是 Bitmap,這樣最保險(不依賴 engine.Process(Bitmap) 是否存在)
using (var pix = PixConverter.ToPix(binary))
using (var page = engine.Process(pix))
{
var text = page.GetText();
// 你可以用它做 debug / 自動挑參數(可先印出來)
var conf = page.GetMeanConfidence(); // 0~1
return text;
}
}
}
public static Bitmap ApplySharpenFilter(Bitmap image)
{
Bitmap sharpenImage = new Bitmap(image.Width, image.Height);
// 銳化矩陣 (Laplacian kernel)
float[][] kernel =
{
new float[] { -1, -1, -1 },
new float[] { -1, 9, -1 },
new float[] { -1, -1, -1 }
};
int w = image.Width;
int h = image.Height;
for (int y = 1; y < h - 1; y++)
{
for (int x = 1; x < w - 1; x++)
{
float r = 0, g = 0, b = 0;
for (int ky = -1; ky <= 1; ky++)
{
for (int kx = -1; kx <= 1; kx++)
{
Color pixel = image.GetPixel(x + kx, y + ky);
float k = kernel[ky + 1][kx + 1];
r += pixel.R * k;
g += pixel.G * k;
b += pixel.B * k;
}
}
int rr = Math.Min(255, Math.Max(0, (int)r));
int gg = Math.Min(255, Math.Max(0, (int)g));
int bb = Math.Min(255, Math.Max(0, (int)b));
sharpenImage.SetPixel(x, y, Color.FromArgb(rr, gg, bb));
}
}
return sharpenImage;
}
}
private string GetSelectedLanguageCode()
{
switch (cmbLanguage.SelectedItem?.ToString())
{
case "繁體中文": return "chi_tra";
case "簡體中文": return "chi_sim";
case "日文": return "jpn";
case "英文": return "eng";
default:
return "eng";
}
}
public static Bitmap InvertImage(Bitmap original)
{
Bitmap inverted = new Bitmap(original.Width, original.Height);
for (int y = 0; y < original.Height; y++)
{
for (int x = 0; x < original.Width; x++)
{
Color pixelColor = original.GetPixel(x, y);
Color invertedColor = Color.FromArgb(255 - pixelColor.R, 255 - pixelColor.G, 255 - pixelColor.B);
inverted.SetPixel(x, y, invertedColor);
}
}
return inverted;
}
public static bool IsMostlyDark(Bitmap image)
{
long totalBrightness = 0;
int pixelCount = image.Width * image.Height;
for (int y = 0; y < image.Height; y++)
{
for (int x = 0; x < image.Width; x++)
{
Color c = image.GetPixel(x, y);
int brightness = (c.R + c.G + c.B) / 3;
totalBrightness += brightness;
}
}
int avg = (int)(totalBrightness / pixelCount);
return avg < 128; // 小於 128 表示整體偏暗,可視為黑底白字
}
private class DownscaleResult
{
public Bitmap Image;
public int SrcW, SrcH;
public Rectangle InkBounds;
public int LineCount;
public float EstLineH;
public float Scale;
public bool Cropped;
}
// 你呼叫 AI 前用這個縮圖(支援 Debug + 可裁切)
private static DownscaleResult DownscaleForAi(
Bitmap src,
int targetLinePx = 22, // 想縮更小就降這個:18~24 建議
int minLinePx = 14, // 保護下限:多行小字不要縮到看不清
bool cropToInk = true, // ✅ 建議開:大量留白會被砍掉,縮圖會更有效
int cropPadPx = 6, // 裁切邊界留白
int maxWidth = 1200,
int maxHeight = 1200,
int maxPixels = 350_000, // 想更小就降:例如 250_000
float minScaleHard = 0.12f // 最低縮放保險(避免變太小)
)
{
if (src == null) return null;
var (inkBounds, lineCount) = EstimateTextBoundsAndLineCount(src);
// 估算單行行高(用 inkBounds,單行/少字會比較準)
float estLineH = Math.Max(1f, (float)inkBounds.Height / Math.Max(1, lineCount));
// 1) 先決定裁切矩形(可選)
Rectangle cropRect = new Rectangle(0, 0, src.Width, src.Height);
bool cropped = false;
if (cropToInk && inkBounds.Width > 0 && inkBounds.Height > 0)
{
// 加 padding,避免切到筆畫
int left = Math.Max(0, inkBounds.Left - cropPadPx);
int top = Math.Max(0, inkBounds.Top - cropPadPx);
int right = Math.Min(src.Width, inkBounds.Right + cropPadPx);
int bottom = Math.Min(src.Height, inkBounds.Bottom + cropPadPx);
cropRect = Rectangle.FromLTRB(left, top, right, bottom);
// 避免裁太小(極端情況)
if (cropRect.Width >= 20 && cropRect.Height >= 20)
cropped = true;
else
cropRect = new Rectangle(0, 0, src.Width, src.Height);
}
// 2) 用行高決定縮放:希望縮到 targetLinePx,但不低於 minLinePx
// scaleWanted:把 estLineH 縮到 targetLinePx
// scaleMinByLine:保證縮完後行高 >= minLinePx
float scaleWanted = targetLinePx / estLineH;
float scaleMinByLine = minLinePx / estLineH;
// 我們只做「縮小」,不放大,所以 clamp 到 <= 1
float scaleByLine = Math.Min(1f, scaleWanted);
// 但也不要縮到小於 minLinePx(縮太小 AI 反而看不清)
scaleByLine = Math.Max(scaleByLine, Math.Min(1f, scaleMinByLine));
// 3) 尺寸與像素上限保護(用裁切後的尺寸來算)
int baseW = cropRect.Width;
int baseH = cropRect.Height;
float scaleByDim = Math.Min(1f, Math.Min((float)maxWidth / baseW, (float)maxHeight / baseH));
long pixels = (long)baseW * baseH;
float scaleByPixels = (pixels > maxPixels)
? (float)Math.Sqrt(maxPixels / (double)pixels)
: 1f;
// 最終縮放取最小(最嚴格)
float scale = Math.Min(scaleByLine, Math.Min(scaleByDim, scaleByPixels));
// 最低縮放保險
scale = Math.Max(scale, minScaleHard);
// 4) 先裁切,再縮放(都會產生新 bitmap)
Bitmap working = CropBitmap(src, cropRect); // 一律 new
Bitmap resized = working;
if (scale < 0.999f)
{
int newW = Math.Max(1, (int)Math.Round(working.Width * scale));
int newH = Math.Max(1, (int)Math.Round(working.Height * scale));
resized = ResizeBitmap(working, newW, newH);
working.Dispose();
}
return new DownscaleResult
{
Image = resized,
SrcW = src.Width,
SrcH = src.Height,
InkBounds = inkBounds,
LineCount = Math.Max(1, lineCount),
EstLineH = estLineH,
Scale = scale,
Cropped = cropped
};
}
private static Bitmap CropBitmap(Bitmap src, Rectangle rect)
{
// rect 若剛好是全圖,也會 clone 一份,確保呼叫端可 Dispose
var dst = new Bitmap(rect.Width, rect.Height, PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(dst))
{
g.InterpolationMode = InterpolationMode.NearestNeighbor;
g.DrawImage(src, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
}
return dst;
}
private static Bitmap ResizeBitmap(Bitmap src, int newW, int newH)
{
var dst = new Bitmap(newW, newH, PixelFormat.Format24bppRgb);
using (var g = Graphics.FromImage(dst))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.SmoothingMode = SmoothingMode.None;
g.DrawImage(src, new Rectangle(0, 0, newW, newH));
}
return dst;
}
/// <summary>
/// 會同時嘗試「深色字」與「淺色字」兩種 ink,選擇更像文字的那個(避免把黑底條當成文字)
/// </summary>
private static (Rectangle inkBounds, int lineCount) EstimateTextBoundsAndLineCount(Bitmap bmp)
{
int w = bmp.Width, h = bmp.Height;
// 背景亮度:取四邊取樣中位數
List<int> samples = new List<int>();
int stepEdgeX = Math.Max(1, w / 60);
int stepEdgeY = Math.Max(1, h / 60);
for (int x = 0; x < w; x += stepEdgeX)
{
samples.Add(Luma(bmp.GetPixel(x, 0)));
samples.Add(Luma(bmp.GetPixel(x, h - 1)));
}
for (int y = 0; y < h; y += stepEdgeY)
{
samples.Add(Luma(bmp.GetPixel(0, y)));
samples.Add(Luma(bmp.GetPixel(w - 1, y)));
}
samples.Sort();
int bg = samples.Count > 0 ? samples[samples.Count / 2] : 255;
int tol = 40; // 30~60 可調
int step = Math.Max(1, Math.Min(w, h) / 350);
// 兩種候選:darkInk(比背景暗) / lightInk(比背景亮)
var candDark = MeasureInkCandidate(bmp, bg, tol, step, wantLightInk: false);
var candLight = MeasureInkCandidate(bmp, bg, tol, step, wantLightInk: true);
// 選「更像文字」的:ink 佔比要小(文字通常是少數),但不能太少到是雜訊
InkCandidate best = ChooseBetterCandidate(candDark, candLight);
if (!best.Valid)
return (new Rectangle(0, 0, w, h), 1);
return (best.Bounds, Math.Max(1, best.Lines));
}
private struct InkCandidate
{
public bool Valid;
public Rectangle Bounds;
public int Lines;
public double FillRatio; // 0~1
}
private static InkCandidate ChooseBetterCandidate(InkCandidate a, InkCandidate b)
{
// 合理文字佔比範圍(太大多半是背景塊,太小多半是雜訊)
bool aOk = a.Valid && a.FillRatio >= 0.002 && a.FillRatio <= 0.45;
bool bOk = b.Valid && b.FillRatio >= 0.002 && b.FillRatio <= 0.45;
if (aOk && bOk) return (a.FillRatio <= b.FillRatio) ? a : b;
if (aOk) return a;
if (bOk) return b;
// 退一步:至少挑一個 valid 的
if (a.Valid && b.Valid) return (a.FillRatio <= b.FillRatio) ? a : b;
if (a.Valid) return a;
if (b.Valid) return b;
return default;
}
private static InkCandidate MeasureInkCandidate(Bitmap bmp, int bg, int tol, int step, bool wantLightInk)
{
int w = bmp.Width, h = bmp.Height;
int minX = w, minY = h, maxX = -1, maxY = -1;
bool[] rowInk = new bool[h];
long inkTotal = 0;
long sampleTotal = 0;
for (int y = 0; y < h; y += step)
{
int inkCountRow = 0;
int sampleCountRow = 0;
for (int x = 0; x < w; x += step)
{
sampleCountRow++;
int l = Luma(bmp.GetPixel(x, y));
bool isInk = wantLightInk
? (l > bg + tol)
: (l < bg - tol);
if (isInk)
{
inkCountRow++;
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
}
inkTotal += inkCountRow;
sampleTotal += sampleCountRow;
if (sampleCountRow > 0 && inkCountRow > sampleCountRow * 0.02) // 2%
rowInk[y] = true;
}
if (maxX < 0 || sampleTotal == 0)
return default;
// 行數:rowInk 連續區塊
int lines = 0;
bool inLine = false;
int gap = 0;
int maxGap = Math.Max(2, 3 * step);
for (int y = 0; y < h; y++)
{
bool has = rowInk[y];
if (has)
{
if (!inLine)
{
inLine = true;
lines++;
}
gap = 0;
}
else if (inLine)
{
gap++;
if (gap > maxGap) inLine = false;
}
}
if (lines < 1) lines = 1;
var bounds = Rectangle.FromLTRB(
Math.Max(0, minX - step * 3),
Math.Max(0, minY - step * 3),
Math.Min(w, maxX + step * 3),
Math.Min(h, maxY + step * 3)
);
return new InkCandidate
{
Valid = bounds.Width > 0 && bounds.Height > 0,
Bounds = bounds,
Lines = lines,
FillRatio = inkTotal / (double)sampleTotal
};
}
private static int Luma(Color c) => (c.R * 299 + c.G * 587 + c.B * 114) / 1000;
private List<LlmCredential> BuildLlmCredentials()
{
var list = new List<LlmCredential>();
// 1) Gemini
if (!string.IsNullOrWhiteSpace(txtApiKey.Text) && cmbModel.SelectedItem != null)
{
list.Add(new LlmCredential
{
Provider = LlmProvider.Gemini,
ApiKey = txtApiKey.Text.Trim(),
Model = cmbModel.SelectedItem.ToString(),
BaseUrl = "",
DisplayName = "Gemini"
});
}
// 2) Pixtral-12B-2409(進階路線 A:本地 vLLM)
// 預設 base URL 為 http://127.0.0.1:8000/v1
if (cmbModel_Pixtral.SelectedItem != null)
{
list.Add(new LlmCredential
{
Provider = LlmProvider.Pixtral12BLocalVllm,
ApiKey = txtApiKey_Pixtral.Text.Trim(), // vLLM token,可留空
Model = cmbModel_Pixtral.SelectedItem.ToString(),
BaseUrl = "http://127.0.0.1:8000/v1",
DisplayName = "Pixtral-12B-2409(vLLM)"
});
}
// 3) Mistral Pixtral Large
if (!string.IsNullOrWhiteSpace(txtApiKey_MistralPixtral.Text) && cmbModel_MistralPixtral.SelectedItem != null)
{
list.Add(new LlmCredential
{
Provider = LlmProvider.MistralPixtral,
ApiKey = txtApiKey_MistralPixtral.Text.Trim(),
Model = cmbModel_MistralPixtral.SelectedItem.ToString(),
BaseUrl = "https://api.mistral.ai/v1",
DisplayName = "Mistral Pixtral"
});
}
// 4) Groq Llama4
if (!string.IsNullOrWhiteSpace(txtApiKey_Llama4.Text) && cmbModel_Llama4.SelectedItem != null)
{
list.Add(new LlmCredential
{
Provider = LlmProvider.GroqLlama4,
ApiKey = txtApiKey_Llama4.Text.Trim(),
Model = cmbModel_Llama4.SelectedItem.ToString(),
BaseUrl = "https://api.groq.com/openai/v1",
DisplayName = "Groq Llama4"
});
}
return list;
}
private async Task<GeminiResult> TranslateTextWithFallbackAsync(string prompt)
{
var credentials = BuildLlmCredentials();
if (credentials.Count == 0)
{
return new GeminiResult
{
HttpStatus = 0,
Error = "請至少填入一組可用的 API Key 與模型",
Text = "錯誤:請至少填入一組可用的 API Key 與模型"
};
}
GeminiResult last = null;
for (int i = 0; i < credentials.Count; i++)
{
var c = credentials[i];
txtResult.AppendText($"\r\n[嘗試] {c.DisplayName} / {c.Model}\r\n");
try
{
GeminiResult gr;
if (c.Provider == LlmProvider.Gemini)
{
var client = new GeminiClient(c.ApiKey, c.Model);
gr = await client.TranslateTextEx(prompt);
}
else
{
var client = new OpenAiCompatibleClient(c.BaseUrl, c.ApiKey, c.Model, c.DisplayName);
gr = await client.TranslateTextEx(prompt);
}
if (gr != null && gr.HttpStatus == 200 && string.IsNullOrWhiteSpace(gr.Error))
{
_quotaTracker?.RecordResult(DailyQuotaTracker.MapProvider(c.Provider, c.Model), c.Model, gr.Usage, true, null);
_quotaTracker?.Save();
return gr;
}
last = gr;
_quotaTracker?.RecordResult(DailyQuotaTracker.MapProvider(c.Provider, c.Model), c.Model, gr?.Usage, false, gr?.Error);
_quotaTracker?.Save();
bool canSwitch = LlmErrorPolicy.IsQuotaOrRateLimit(gr);
if (canSwitch)
{
if (i < credentials.Count - 1)
{
txtResult.AppendText($"[切換] {c.DisplayName} 配額或速率受限,改用下一組 API Key。\r\n");
continue;
}
return new GeminiResult
{
HttpStatus = 429,
Error = "所有API KEY額度已用盡",
Text = "錯誤:所有API KEY額度已用盡"
};
}
return gr;
}
catch (Exception ex)
{
_quotaTracker?.RecordResult(DailyQuotaTracker.MapProvider(c.Provider, c.Model), c.Model, null, false, ex.Message);
_quotaTracker?.Save();
last = new GeminiResult
{
HttpStatus = 0,
Error = ex.Message,
Text = "錯誤:" + ex.Message
};
if (LlmErrorPolicy.IsRetryableNetworkError(ex) && i < credentials.Count - 1)
{
txtResult.AppendText($"[切換] {c.DisplayName} 網路或連線失敗,改用下一組 API Key。\r\n");
continue;
}
return last;
}
}