-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathocr_tool.py
More file actions
771 lines (659 loc) · 32.7 KB
/
Copy pathocr_tool.py
File metadata and controls
771 lines (659 loc) · 32.7 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
import flet as ft
import os
import io
import json
import ssl
import warnings
from datetime import datetime
from PyPDF2 import PdfReader, PdfWriter
from dotenv import load_dotenv, set_key, find_dotenv
# טעינת משתני סביבה
load_dotenv()
class OCRToolFlet:
def __init__(self, page, get_selected_file_name, on_refresh, load_file_callback=None):
self.page = page
self.get_selected_file_name = get_selected_file_name
self.on_refresh = on_refresh
self.load_file_callback = load_file_callback
self.selected_pdf_path = None
# ברירת מחדל לפרומפט
self.default_prompt = """You have a PDF document in front of you. Write the exact content of the document, do not add anything from yourself.
Important instructions:
- Do NOT include headers (page headers)
- Do NOT include footnotes
- Only the main text content of the document
- Analyze the document structure yourself and determine if it has one column or two columns
- If two columns: read the right column first, then the left column
- If you are uncertain about a specific word, underline it like this: _word_
- Do NOT add line breaks (Enter) within paragraphs - only use spaces
- Add line breaks ONLY at the end of paragraphs/sections
- Preserve the original punctuation and structure"""
# UI Components
self.pdf_name_text = ft.Text(
"לא נבחר קובץ",
size=14,
color=ft.Colors.GREY_700,
text_align=ft.TextAlign.CENTER
)
self.status_text = ft.Text(
"",
size=12,
color=ft.Colors.BLUE_700,
text_align=ft.TextAlign.CENTER
)
self.credits_text = ft.Text(
"",
size=11,
color=ft.Colors.GREY_600,
text_align=ft.TextAlign.CENTER
)
# מעקב אחר שימוש
self.total_input_tokens = 0
self.total_output_tokens = 0
# טעינת נתוני שימוש חודשיים
self.usage_file = "gemini_usage.json"
self.load_monthly_usage()
self.update_monthly_display()
# File picker
self.pdf_picker = ft.FilePicker(on_result=self.on_pdf_selected)
self.page.overlay.append(self.pdf_picker)
# Settings dialog
self.settings_dialog = None
self.create_settings_dialog()
def create_settings_dialog(self):
"""יצירת דיאלוג הגדרות"""
api_key = os.getenv('GEMINI_API_KEY', '')
self.api_key_field = ft.TextField(
label="Gemini API Key",
value=api_key,
password=True,
can_reveal_password=True,
width=400,
text_align=ft.TextAlign.LEFT
)
self.model_dropdown = ft.Dropdown(
label="בחר מודל Gemini",
options=[
ft.dropdown.Option("gemini-2.5-pro"),
ft.dropdown.Option("gemini-2.5-flash"),
ft.dropdown.Option("gemini-1.5-pro"),
ft.dropdown.Option("gemini-1.5-flash"),
],
value="gemini-2.5-pro",
width=200
)
self.prompt_field = ft.TextField(
label="פרומפט למודל",
value=self.default_prompt,
multiline=True,
min_lines=8,
max_lines=15,
width=400,
text_align=ft.TextAlign.RIGHT
)
self.pages_per_chunk_field = ft.TextField(
label="עמודים לכל chunk",
value="5",
width=150,
keyboard_type=ft.KeyboardType.NUMBER
)
self.delay_between_chunks_field = ft.TextField(
label="המתנה בין chunks (שניות)",
value="35",
width=150,
keyboard_type=ft.KeyboardType.NUMBER,
hint_text="2.5-pro: 30s | 2.5-flash: 6s"
)
self.use_file_upload = ft.Checkbox(
label="העלה PDF (מומלץ לכיבוי אם יש 429)",
value=True,
width=200
)
self.model_dropdown = ft.Dropdown(
label="בחר מודל Gemini",
options=[
ft.dropdown.Option("gemini-2.5-pro"),
ft.dropdown.Option("gemini-2.5-flash"),
ft.dropdown.Option("gemini-1.5-pro"),
ft.dropdown.Option("gemini-1.5-flash"),
],
value="gemini-2.5-pro",
width=200
)
def test_api_key(e):
"""בדיקת API Key"""
test_key = self.api_key_field.value
if not test_key:
self.status_text.value = "אנא הזן API Key תחילה"
self.status_text.color = ft.Colors.ORANGE_700
self.page.update()
return
try:
# עקיפת SSL
ssl._create_default_https_context = ssl._create_unverified_context
warnings.filterwarnings('ignore')
# Monkey patch ל-httpx
try:
import httpx
_original_httpx_client_init = httpx.Client.__init__
def _patched_httpx_client_init(self, *args, **kwargs):
kwargs['verify'] = False
_original_httpx_client_init(self, *args, **kwargs)
httpx.Client.__init__ = _patched_httpx_client_init
except ImportError:
pass
from google import genai
client = genai.Client(api_key=test_key)
# ניסיון קריאה פשוטה
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Hello",
)
self.status_text.value = "✓ API Key תקין ועובד!"
self.status_text.color = ft.Colors.GREEN_700
self.page.update()
except Exception as ex:
error_msg = str(ex)
print(f"שגיאת בדיקה: {error_msg}")
if "API_KEY_INVALID" in error_msg or "invalid" in error_msg.lower():
self.status_text.value = "✗ API Key לא תקף"
self.status_text.color = ft.Colors.RED_700
elif "429" in error_msg or "RESOURCE_EXHAUSTED" in error_msg:
self.status_text.value = "✓ API Key תקין אבל הגעת למגבלה"
self.status_text.color = ft.Colors.ORANGE_700
elif "SSL" in error_msg or "CERTIFICATE" in error_msg:
self.status_text.value = "✗ בעיית SSL - בדוק חיבור לאינטרנט"
self.status_text.color = ft.Colors.RED_700
else:
self.status_text.value = f"שגיאה: {error_msg[:30]}"
self.status_text.color = ft.Colors.RED_700
self.page.update()
def save_settings(e):
# שמירת API Key בקובץ .env
env_file = find_dotenv()
if not env_file:
env_file = '.env'
with open(env_file, 'w') as f:
f.write('')
set_key(env_file, 'GEMINI_API_KEY', self.api_key_field.value)
self.status_text.value = "ההגדרות נשמרו בהצלחה"
self.status_text.color = ft.Colors.GREEN_700
self.settings_dialog.open = False
self.page.update()
def reset_prompt(e):
self.prompt_field.value = self.default_prompt
self.page.update()
def reset_monthly_usage(e):
"""איפוס נתוני שימוש חודשיים"""
self.monthly_data = {
'month': datetime.now().strftime("%Y-%m"),
'input_tokens': 0,
'output_tokens': 0,
'total_cost': 0.0
}
self.save_monthly_usage()
self.update_monthly_display()
self.show_message("נתוני השימוש אופסו", ft.Colors.GREEN_400)
self.settings_dialog = ft.AlertDialog(
title=ft.Text("הגדרות OCR", text_align=ft.TextAlign.RIGHT),
content=ft.Container(
content=ft.Column([
self.api_key_field,
ft.Container(height=10),
ft.Text(
"קבל API Key מ: https://aistudio.google.com/apikey",
size=11,
color=ft.Colors.BLUE_700,
text_align=ft.TextAlign.LEFT
),
ft.Divider(height=20),
self.prompt_field,
ft.Container(height=10),
ft.Row([
ft.ElevatedButton(
"איפוס פרומפט",
icon=ft.Icons.REFRESH,
on_click=reset_prompt
),
], alignment=ft.MainAxisAlignment.END),
ft.Divider(height=20),
self.model_dropdown,
ft.Container(height=5),
ft.Text(
"Free Tier: 2.5-pro=2 RPM | 2.5-flash=10 RPM",
size=11,
color=ft.Colors.ORANGE_700,
text_align=ft.TextAlign.RIGHT
),
ft.Divider(height=20),
self.use_file_upload,
ft.Text(
"אם מקבל 429 מיד - כבה העלאת PDF",
size=11,
color=ft.Colors.RED_700,
text_align=ft.TextAlign.RIGHT
),
ft.Container(height=10),
self.pages_per_chunk_field,
ft.Container(height=10),
self.delay_between_chunks_field,
ft.Container(height=5),
ft.Text(
"שגיאה 429? הגדל את זמן ההמתנה",
size=11,
color=ft.Colors.ORANGE_700,
text_align=ft.TextAlign.RIGHT
),
ft.Divider(height=20),
ft.Row([
ft.ElevatedButton(
"אפס נתוני שימוש חודשיים",
icon=ft.Icons.DELETE_SWEEP,
on_click=reset_monthly_usage,
bgcolor=ft.Colors.RED_100
),
], alignment=ft.MainAxisAlignment.CENTER),
], scroll=ft.ScrollMode.AUTO, width=400, height=650),
padding=20
),
actions=[
ft.TextButton("ביטול", on_click=lambda e: self.close_settings()),
ft.ElevatedButton("בדוק API Key", icon=ft.Icons.CHECK_CIRCLE, on_click=test_api_key),
ft.ElevatedButton("שמור", on_click=save_settings),
],
actions_alignment=ft.MainAxisAlignment.END,
)
def open_settings(self, e):
"""פתיחת דיאלוג הגדרות"""
self.page.open(self.settings_dialog)
self.page.update()
def close_settings(self):
"""סגירת דיאלוג הגדרות"""
self.settings_dialog.open = False
self.page.update()
def on_pdf_selected(self, e: ft.FilePickerResultEvent):
if e.files and len(e.files) > 0:
self.selected_pdf_path = e.files[0].path
self.pdf_name_text.value = os.path.basename(self.selected_pdf_path)
self.pdf_name_text.color = ft.Colors.GREEN_700
self.status_text.value = "קובץ נבחר בהצלחה"
self.status_text.color = ft.Colors.GREEN_700
else:
self.selected_pdf_path = None
self.pdf_name_text.value = "לא נבחר קובץ"
self.pdf_name_text.color = ft.Colors.GREY_700
self.status_text.value = ""
self.page.update()
def process_ocr(self, e):
"""עיבוד OCR עם Gemini"""
if not self.selected_pdf_path:
self.show_message("אנא בחר קובץ PDF תחילה", ft.Colors.ORANGE_400)
return
api_key = os.getenv('GEMINI_API_KEY', '')
if not api_key:
self.show_message("אנא הגדר API Key בהגדרות", ft.Colors.RED_400)
return
# איפוס מונה tokens
self.total_input_tokens = 0
self.total_output_tokens = 0
self.credits_text.value = ""
self.status_text.value = "מעבד OCR..."
self.status_text.color = ft.Colors.BLUE_700
self.page.update()
try:
# עקיפת בדיקת SSL
ssl._create_default_https_context = ssl._create_unverified_context
warnings.filterwarnings('ignore', message='Unverified HTTPS request')
# Monkey patch ל-httpx
try:
import httpx
_original_httpx_client_init = httpx.Client.__init__
def _patched_httpx_client_init(self, *args, **kwargs):
kwargs['verify'] = False
_original_httpx_client_init(self, *args, **kwargs)
httpx.Client.__init__ = _patched_httpx_client_init
except ImportError:
pass
from google import genai
from google.genai import types
# קריאת PDF
reader = PdfReader(self.selected_pdf_path)
total_pages = len(reader.pages)
pages_per_chunk = int(self.pages_per_chunk_field.value)
delay_seconds = int(self.delay_between_chunks_field.value)
# חישוב זמן המתנה מומלץ לפי המודל (Free Tier)
model_name = self.model_dropdown.value
if "2.5-pro" in model_name:
# 2 RPM = 30 שניות בין בקשות
recommended_delay = 30
elif "2.5-flash" in model_name:
# 10 RPM = 6 שניות בין בקשות
recommended_delay = 6
else:
recommended_delay = delay_seconds
# אם המשתמש הגדיר פחות מהמומלץ, הצג אזהרה
if delay_seconds < recommended_delay:
self.show_message(f"המתנה מומלצת: {recommended_delay}+ שניות למודל זה", ft.Colors.ORANGE_400)
delay_seconds = max(delay_seconds, recommended_delay)
self.status_text.value = f"מעבד {total_pages} עמודים (המתנה: {delay_seconds}s)..."
self.page.update()
# התחברות ל-Gemini
client = genai.Client(api_key=api_key)
all_text = []
# עיבוד בחלקים
for start_page in range(0, total_pages, pages_per_chunk):
end_page = min(start_page + pages_per_chunk, total_pages)
chunk_num = (start_page // pages_per_chunk) + 1
total_chunks = (total_pages + pages_per_chunk - 1) // pages_per_chunk
self.status_text.value = f"מעבד chunk {chunk_num}/{total_chunks} (עמודים {start_page + 1}-{end_page})"
self.page.update()
# ניסיון חוזר במקרה של שגיאה 429
max_retries = 3
retry_count = 0
success = False
while retry_count < max_retries and not success:
try:
# יצירת PDF זמני עם רק העמודים הנוכחיים
writer = PdfWriter()
for i in range(start_page, end_page):
writer.add_page(reader.pages[i])
# שמירה ל-BytesIO
pdf_buffer = io.BytesIO()
writer.write(pdf_buffer)
pdf_buffer.seek(0)
# קריאת ה-bytes (כמו בדוגמה המקורית)
pdf_bytes = pdf_buffer.read()
file_obj = io.BytesIO(pdf_bytes)
# העלאה ל-Gemini
uploaded = client.files.upload(
file=file_obj,
config=types.UploadFileConfig(mime_type="application/pdf")
)
# שליחה לעיבוד
contents = [
types.Part.from_uri(file_uri=uploaded.uri, mime_type="application/pdf"),
types.Part.from_text(text=self.prompt_field.value)
]
response = client.models.generate_content(
model=self.model_dropdown.value,
contents=contents,
config=types.GenerateContentConfig(
system_instruction=None,
response_mime_type='text/plain',
temperature=0.8
)
)
chunk_text = response.text.strip() if response.text else ""
all_text.append(chunk_text)
# מעקב אחר tokens
if hasattr(response, 'usage_metadata'):
usage = response.usage_metadata
input_tokens = getattr(usage, 'prompt_token_count', 0)
output_tokens = getattr(usage, 'candidates_token_count', 0)
self.total_input_tokens += input_tokens
self.total_output_tokens += output_tokens
# עדכון תצוגת קרדיטים
self.update_credits_display()
success = True
except Exception as chunk_error:
error_str = str(chunk_error)
# הצגת השגיאה המלאה למשתמש
print(f"שגיאה מפורטת: {error_str}")
if "429" in error_str or "quota" in error_str.lower() or "rate" in error_str.lower():
retry_count += 1
if retry_count < max_retries:
wait_time = delay_seconds * (retry_count + 1)
self.status_text.value = f"שגיאת 429 - ממתין {wait_time} שניות..."
self.status_text.color = ft.Colors.ORANGE_700
self.page.update()
# הצגת הודעה מפורטת
if "RESOURCE_EXHAUSTED" in error_str:
self.show_message("הגעת למגבלת API. בדוק ב-AI Studio", ft.Colors.RED_400)
import time
time.sleep(wait_time)
else:
# הצגת השגיאה המלאה
error_msg = f"נכשל אחרי {max_retries} נסיונות.\n\nשגיאה: {error_str[:200]}"
raise Exception(error_msg)
else:
raise chunk_error
# המתנה בין chunks (למעט האחרון)
if chunk_num < total_chunks:
import time
self.status_text.value = f"ממתין {delay_seconds} שניות לפני chunk הבא..."
self.status_text.color = ft.Colors.BLUE_700
self.page.update()
time.sleep(delay_seconds)
# שמירת הטקסט המלא
output_text = "\n\n".join(all_text)
# פתיחה בתוכנה
self.open_in_editor(output_text)
# עדכון סטטוס סופי
total_tokens = self.total_input_tokens + self.total_output_tokens
# חישוב עלות סשן זה
model = self.model_dropdown.value
if "2.5-pro" in model:
session_cost = (self.total_input_tokens / 1_000_000 * 1.25) + (self.total_output_tokens / 1_000_000 * 5)
elif "2.5-flash" in model:
session_cost = (self.total_input_tokens / 1_000_000 * 0.075) + (self.total_output_tokens / 1_000_000 * 0.30)
elif "1.5-pro" in model:
session_cost = (self.total_input_tokens / 1_000_000 * 1.25) + (self.total_output_tokens / 1_000_000 * 5)
else:
session_cost = (self.total_input_tokens / 1_000_000 * 0.075) + (self.total_output_tokens / 1_000_000 * 0.30)
self.status_text.value = f"הושלם! {total_pages} עמודים | {total_tokens:,} tokens | ${session_cost:.3f}"
self.status_text.color = ft.Colors.GREEN_700
self.show_message("OCR הושלם בהצלחה", ft.Colors.GREEN_400)
except ImportError:
self.show_message("חסרות ספריות: pip install google-genai PyPDF2 python-dotenv", ft.Colors.RED_400)
self.status_text.value = "שגיאה: חסרות ספריות"
self.status_text.color = ft.Colors.RED_700
except Exception as ex:
error_msg = str(ex)
print(f"שגיאה כללית: {error_msg}")
# ניתוח השגיאה
if "API_KEY_INVALID" in error_msg or "invalid" in error_msg.lower():
self.show_message("API Key לא תקף. בדוק בהגדרות", ft.Colors.RED_400)
self.status_text.value = "שגיאה: API Key לא תקף"
elif "RESOURCE_EXHAUSTED" in error_msg or "429" in error_msg:
# המלצה למשתמש
model_name = self.model_dropdown.value
if "2.5-pro" in model_name:
suggestion = "נסה gemini-2.5-flash (250 RPD)"
else:
suggestion = "המתן עד חצות Pacific (08:00 IL)"
self.show_message(f"חרגת ממכסת API. {suggestion}", ft.Colors.RED_400)
self.status_text.value = f"מכסה מלאה. {suggestion}"
elif "PERMISSION_DENIED" in error_msg:
self.show_message("אין הרשאה. בדוק הגדרות API Key", ft.Colors.RED_400)
self.status_text.value = "שגיאה: אין הרשאה"
else:
self.show_message(f"שגיאה: {error_msg[:100]}", ft.Colors.RED_400)
self.status_text.value = f"שגיאה: {error_msg[:50]}"
self.status_text.color = ft.Colors.RED_700
self.page.update()
def open_in_editor(self, text):
"""פתיחת הטקסט בתוכנה"""
# שמירה בקובץ זמני
temp_file = "ocr_output_temp.txt"
with open(temp_file, 'w', encoding='utf-8') as f:
f.write(text)
# דיאלוג אישור
def open_in_app(e):
confirm_dialog.open = False
self.page.update()
# פתיחה באפליקציה - קריאה לפונקציה שטוענת קובץ
if self.load_file_callback:
self.load_file_callback(temp_file)
else:
self.show_message("הקובץ נשמר ב: " + temp_file, ft.Colors.GREEN_400)
def open_in_notepad(e):
confirm_dialog.open = False
self.page.update()
try:
os.startfile(temp_file, 'edit')
except Exception as ex:
self.show_message(f"שגיאה בפתיחת הקובץ: {ex}", ft.Colors.RED_400)
def cancel(e):
confirm_dialog.open = False
self.page.update()
confirm_dialog = ft.AlertDialog(
title=ft.Text("OCR הושלם בהצלחה!", text_align=ft.TextAlign.CENTER),
content=ft.Text(
f"הקובץ נשמר בהצלחה.\nאיפה תרצה לפתוח אותו?",
text_align=ft.TextAlign.CENTER,
size=16
),
actions=[
ft.ElevatedButton(
"פתח באפליקציה",
icon=ft.Icons.BOOK,
on_click=open_in_app
),
ft.ElevatedButton(
"פתח בנוטפד",
icon=ft.Icons.EDIT_NOTE,
on_click=open_in_notepad
),
ft.TextButton("ביטול", on_click=cancel),
],
actions_alignment=ft.MainAxisAlignment.CENTER,
)
self.page.open(confirm_dialog)
self.page.update()
def load_monthly_usage(self):
"""טעינת נתוני שימוש חודשיים"""
current_month = datetime.now().strftime("%Y-%m")
if os.path.exists(self.usage_file):
try:
with open(self.usage_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# אם זה חודש חדש, אפס את הנתונים
if data.get('month') != current_month:
self.monthly_data = {
'month': current_month,
'input_tokens': 0,
'output_tokens': 0,
'total_cost': 0.0
}
else:
self.monthly_data = data
except:
self.monthly_data = {
'month': current_month,
'input_tokens': 0,
'output_tokens': 0,
'total_cost': 0.0
}
else:
self.monthly_data = {
'month': current_month,
'input_tokens': 0,
'output_tokens': 0,
'total_cost': 0.0
}
def save_monthly_usage(self):
"""שמירת נתוני שימוש חודשיים"""
try:
with open(self.usage_file, 'w', encoding='utf-8') as f:
json.dump(self.monthly_data, f, indent=2)
except Exception as ex:
print(f"שגיאה בשמירת נתוני שימוש: {ex}")
def update_monthly_display(self):
"""עדכון תצוגת השימוש החודשי"""
monthly_tokens = self.monthly_data['input_tokens'] + self.monthly_data['output_tokens']
monthly_cost = self.monthly_data['total_cost']
# מכסה חינמית של Gemini (לפי התיעוד הרשמי)
# Free tier: 15 RPM, 1M TPM, 1,500 RPD
# אין מגבלה חודשית מוגדרת, אבל נציג את השימוש
self.credits_text.value = f"חודש זה: {monthly_tokens:,} tokens | ${monthly_cost:.3f}"
# צבע לפי עלות
if monthly_cost < 1.0:
self.credits_text.color = ft.Colors.GREEN_700
elif monthly_cost < 5.0:
self.credits_text.color = ft.Colors.ORANGE_700
else:
self.credits_text.color = ft.Colors.RED_700
self.page.update()
def update_credits_display(self):
"""עדכון תצוגת השימוש בקרדיטים"""
total_tokens = self.total_input_tokens + self.total_output_tokens
# חישוב עלות משוערת (לפי מחירון Gemini)
model = self.model_dropdown.value
if "2.5-pro" in model:
cost = (self.total_input_tokens / 1_000_000 * 1.25) + (self.total_output_tokens / 1_000_000 * 5)
elif "2.5-flash" in model:
cost = (self.total_input_tokens / 1_000_000 * 0.075) + (self.total_output_tokens / 1_000_000 * 0.30)
elif "1.5-pro" in model:
cost = (self.total_input_tokens / 1_000_000 * 1.25) + (self.total_output_tokens / 1_000_000 * 5)
else: # 1.5-flash
cost = (self.total_input_tokens / 1_000_000 * 0.075) + (self.total_output_tokens / 1_000_000 * 0.30)
# עדכון נתונים חודשיים
self.monthly_data['input_tokens'] += self.total_input_tokens
self.monthly_data['output_tokens'] += self.total_output_tokens
self.monthly_data['total_cost'] += cost
self.save_monthly_usage()
# עדכון תצוגה
self.update_monthly_display()
self.page.update()
def show_message(self, message, color):
"""הצגת הודעה - משתמש ב-status_text במקום SnackBar"""
self.status_text.value = message
if color == ft.Colors.GREEN_400:
self.status_text.color = ft.Colors.GREEN_700
elif color == ft.Colors.RED_400:
self.status_text.color = ft.Colors.RED_700
elif color == ft.Colors.ORANGE_400:
self.status_text.color = ft.Colors.ORANGE_700
else:
self.status_text.color = ft.Colors.BLUE_700
self.page.update()
def get_view(self):
return ft.Column([
# כפתור הגדרות
ft.Row([
ft.IconButton(
icon=ft.Icons.SETTINGS,
tooltip="הגדרות OCR",
on_click=self.open_settings,
icon_size=24
),
], alignment=ft.MainAxisAlignment.END),
ft.Container(height=5),
# כפתור בחירת קובץ
ft.ElevatedButton(
"בחר קובץ PDF",
icon=ft.Icons.UPLOAD_FILE,
on_click=lambda _: self.pdf_picker.pick_files(
allowed_extensions=["pdf"],
dialog_title="בחר קובץ PDF"
),
width=220
),
ft.Container(height=8),
# שם הקובץ שנבחר
ft.Container(
content=self.pdf_name_text,
padding=10,
border=ft.border.all(1, ft.Colors.GREY_300),
border_radius=5,
width=220,
bgcolor=ft.Colors.WHITE,
),
ft.Container(height=20),
# כפתור הפעלה ראשי
ft.ElevatedButton(
"הפעל OCR עם Gemini",
icon=ft.Icons.AUTO_AWESOME,
on_click=self.process_ocr,
width=220
),
ft.Container(height=20),
# סטטוס
ft.Container(
content=self.status_text,
padding=10,
width=220,
),
# תצוגת קרדיטים
self.credits_text,
], horizontal_alignment=ft.CrossAxisAlignment.CENTER, spacing=0)