-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscan_namer.py
More file actions
1727 lines (1492 loc) · 64.5 KB
/
scan_namer.py
File metadata and controls
1727 lines (1492 loc) · 64.5 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
#!/usr/bin/env python3
"""
Scan Namer - Automatically rename scanned documents in Google Drive
using LLM analysis of document content.
"""
# /// script
# requires-python = ">=3.8"
# dependencies = [
# "google-auth-oauthlib==1.2.0",
# "google-auth==2.29.0",
# "google-api-python-client==2.133.0",
# "google-genai>=0.1.0",
# "anthropic>=0.7.0",
# "openai>=1.0.0",
# "PyPDF2==3.0.1",
# "requests==2.31.0",
# "python-dotenv==1.0.1",
# "types-requests",
# "pytesseract==0.3.10",
# "pdf2image==1.17.0",
# "Pillow>=10.0.0",
# ]
# ///
import argparse
import json
import logging
import os
import sys
import tempfile
# from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import base64
from datetime import datetime
# ignore lint errors related to unresolved imports; using uv to avoid using venv
import requests
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload, MediaFileUpload
import PyPDF2
from dotenv import load_dotenv
import pytesseract
from pdf2image import convert_from_path
class ConfigManager:
"""Manages configuration loading and validation."""
def __init__(self, config_file: str = "config.json"):
self.config_file = config_file
self.config = self._load_config()
self._validate_config()
def _load_config(self) -> Dict[str, Any]:
"""Load configuration from JSON file."""
try:
with open(self.config_file, "r") as f:
config_data = json.load(f)
return config_data
except FileNotFoundError:
logging.error(f"Configuration file {self.config_file} not found")
sys.exit(1)
except json.JSONDecodeError as e:
logging.error(f"Invalid JSON in {self.config_file}: {e}")
sys.exit(1)
def _validate_config(self) -> None:
"""Validate required configuration sections exist."""
required_sections = ["llm", "pdf", "google_drive", "logging"]
for section in required_sections:
if section not in self.config:
logging.error(f"Missing required config section: {section}")
sys.exit(1)
def get(self, key_path: str, default=None) -> Any:
"""Get configuration value using dot notation (e.g., 'llm.api_key')."""
# Check for environment variable override first
env_value = self._get_env_override(key_path)
if env_value is not None:
return env_value
# Fall back to config file value
keys = key_path.split(".")
value = self.config
for key in keys:
if isinstance(value, dict) and key in value:
value = value[key]
else:
return default
return value
def _get_env_override(self, key_path: str) -> Any:
"""Check for environment variable override for a config key."""
# Map config keys to environment variable names
env_mappings = {
"llm.provider": "LLM_PROVIDER",
"llm.model": "LLM_MODEL",
"llm.max_tokens": "LLM_MAX_TOKENS",
"llm.temperature": "LLM_TEMPERATURE",
"pdf.max_pages_before_extraction": "PDF_MAX_PAGES_BEFORE_EXTRACTION",
"pdf.extraction_pages": "PDF_EXTRACTION_PAGES",
"ocr.enable_embedding": "OCR_ENABLE_EMBEDDING",
"ocr.min_text_per_page": "OCR_MIN_TEXT_PER_PAGE",
"ocr.language": "OCR_LANGUAGE",
"ocr.dpi": "OCR_DPI",
"google_drive.credentials_file": "GOOGLE_DRIVE_CREDENTIALS_FILE",
"google_drive.token_file": "GOOGLE_DRIVE_TOKEN_FILE",
"logging.level": "LOG_LEVEL",
"logging.format": "LOG_FORMAT",
"logging.date_format": "LOG_DATE_FORMAT",
"logging.file": "LOG_FILE",
}
env_var = env_mappings.get(key_path)
if env_var:
env_value = os.getenv(env_var)
if env_value is not None:
# Convert string values to appropriate types
return self._convert_env_value(env_value, key_path)
return None
def _convert_env_value(self, value: str, key_path: str) -> Any:
"""Convert environment variable string to appropriate type."""
# Integer conversions
if key_path in [
"llm.max_tokens",
"pdf.max_pages_before_extraction",
"pdf.extraction_pages",
]:
try:
return int(value)
except ValueError:
logging.warning(f"Invalid integer value for {key_path}: {value}")
return None
# Float conversions
if key_path in ["llm.temperature"]:
try:
return float(value)
except ValueError:
logging.warning(f"Invalid float value for {key_path}: {value}")
return None
# Boolean conversions
if key_path in ["auto_select_first_folder"]:
return value.lower() in ("true", "1", "yes", "on")
# String values (no conversion needed)
return value
class PromptManager:
"""Manages prompt templates from JSON file."""
def __init__(self, prompts_file: str = "prompts.json"):
self.prompts_file = prompts_file
self.prompts = self._load_prompts()
def _load_prompts(self) -> Dict[str, Any]:
"""Load prompts from JSON file."""
try:
with open(self.prompts_file, "r") as f:
prompts_data = json.load(f)
return prompts_data
except FileNotFoundError:
logging.error(f"Prompts file {self.prompts_file} not found")
sys.exit(1)
except json.JSONDecodeError as e:
logging.error(f"Invalid JSON in {self.prompts_file}: {e}")
sys.exit(1)
def get_prompt(self, prompt_key: str) -> Dict[str, Any]:
"""Get prompt configuration by key."""
if prompt_key not in self.prompts:
raise ValueError(f"Prompt key '{prompt_key}' not found")
return self.prompts[prompt_key]
class GoogleDriveManager:
"""Handles Google Drive authentication and operations."""
def __init__(self, config: ConfigManager):
self.config = config
self.service: Optional[Any] = None
self._authenticate()
def _authenticate(self) -> None:
"""Authenticate with Google Drive API."""
creds = None
token_file = self.config.get("google_drive.token_file")
creds_file = self.config.get("google_drive.credentials_file")
scopes = self.config.get("google_drive.scopes")
# Load existing token
if token_file and os.path.exists(token_file):
creds = Credentials.from_authorized_user_file(token_file, scopes)
# If no valid credentials, get new ones
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
try:
creds.refresh(Request())
logging.info("Refreshed Google Drive credentials")
except Exception as e:
logging.warning(f"Failed to refresh credentials: {e}")
creds = None
if not creds:
if not creds_file or not os.path.exists(creds_file):
logging.error(
f"Google Drive credentials file {creds_file} not found"
)
logging.error(
"Please download OAuth 2.0 credentials from Google Cloud Console"
)
sys.exit(1)
flow = InstalledAppFlow.from_client_secrets_file(creds_file, scopes)
creds = flow.run_local_server(port=0)
logging.info("Completed Google Drive OAuth flow")
# Save the credentials
if token_file:
with open(token_file, "w") as token:
token.write(creds.to_json())
logging.info(f"Saved credentials to {token_file}")
self.service = build("drive", "v3", credentials=creds)
logging.info("Successfully authenticated with Google Drive")
def list_folders(self, parent_id: str = "root") -> List[Dict[str, Any]]:
"""List folders in Google Drive."""
if self.service is None:
logging.error("Google Drive service not initialized")
return []
try:
query = f"'{parent_id}' in parents and mimeType='application/vnd.google-apps.folder' and trashed=false"
results = (
self.service.files()
.list(q=query, fields="files(id,name,parents)")
.execute()
)
return results.get("files", [])
except HttpError as e:
logging.error(f"Error listing folders: {e}")
return []
def select_folder(self) -> Optional[str]:
"""Allow user to select a Google Drive folder."""
print("\nAvailable folders in your Google Drive:")
folders = self.list_folders()
if not folders:
print("No folders found in root directory.")
return None
for i, folder in enumerate(folders, 1):
print(f"{i}. {folder['name']}")
print(f"{len(folders) + 1}. Enter custom folder path")
try:
choice = input(f"\nSelect folder (1-{len(folders) + 1}): ").strip()
choice_num = int(choice)
if 1 <= choice_num <= len(folders):
selected = folders[choice_num - 1]
logging.info(
f"Selected folder: {selected['name']} (ID: {selected['id']})"
)
return selected["id"]
elif choice_num == len(folders) + 1:
folder_path = input("Enter folder path or ID: ").strip()
return folder_path
else:
print("Invalid selection")
return None
except (ValueError, KeyboardInterrupt):
print("Invalid input or cancelled")
return None
def list_pdfs(self, folder_id: str) -> List[Dict[str, Any]]:
"""List PDF files in a Google Drive folder."""
if self.service is None:
logging.error("Google Drive service not initialized")
return []
try:
query = f"'{folder_id}' in parents and mimeType='application/pdf' and trashed=false"
results = (
self.service.files()
.list(
q=query,
fields="files(id,name,size,modifiedTime)",
orderBy="modifiedTime desc",
)
.execute()
)
files = results.get("files", [])
logging.info(f"Found {len(files)} PDF files in folder")
return files
except HttpError as e:
logging.error(f"Error listing PDFs: {e}")
return []
def download_file(self, file_id: str, output_path: str) -> bool:
"""Download a file from Google Drive."""
if self.service is None:
logging.error("Google Drive service not initialized")
return False
try:
request = self.service.files().get_media(fileId=file_id)
with open(output_path, "wb") as f:
downloader = MediaIoBaseDownload(f, request)
done = False
while not done:
status, done = downloader.next_chunk()
logging.debug(f"Downloaded file to {output_path}")
return True
except HttpError as e:
logging.error(f"Error downloading file: {e}")
return False
def rename_file(self, file_id: str, new_name: str) -> bool:
"""Rename a file in Google Drive."""
if self.service is None:
logging.error("Google Drive service not initialized")
return False
try:
self.service.files().update(
fileId=file_id, body={"name": new_name}
).execute()
logging.info(f"Renamed file to: {new_name}")
return True
except HttpError as e:
logging.error(f"Error renaming file: {e}")
return False
def update_file(self, file_id: str, file_path: str) -> bool:
"""Update a file in Google Drive with a new version."""
if self.service is None:
logging.error("Google Drive service not initialized")
return False
try:
# Create media upload object
media = MediaFileUpload(
file_path, mimetype="application/pdf", resumable=True
)
# Update the file
self.service.files().update(fileId=file_id, media_body=media).execute()
logging.info(f"Updated file {file_id} with new content from {file_path}")
return True
except HttpError as e:
logging.error(f"Error updating file: {e}")
return False
except Exception as e:
logging.error(f"Unexpected error updating file: {e}")
return False
class PDFProcessor:
"""Handles PDF processing operations."""
def __init__(self, config: ConfigManager):
self.config = config
self.max_pages = config.get("pdf.max_pages_before_extraction", 3)
self.extraction_pages = config.get("pdf.extraction_pages", 3)
def get_page_count(self, pdf_path: str) -> int:
"""Get the number of pages in a PDF."""
try:
with open(pdf_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
return len(reader.pages)
except Exception as e:
logging.error(f"Error reading PDF {pdf_path}: {e}")
return 0
def extract_pages(
self, input_path: str, output_path: str, num_pages: Optional[int] = None
) -> bool:
"""Extract first N pages from PDF to a new file."""
if num_pages is None:
extraction_pages = self.config.get("pdf.extraction_pages", 3)
if isinstance(extraction_pages, int):
num_pages = extraction_pages
else:
num_pages = 3
try:
with open(input_path, "rb") as input_file:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
pages_to_extract = min(num_pages, len(reader.pages))
for i in range(pages_to_extract):
writer.add_page(reader.pages[i])
with open(output_path, "wb") as output_file:
writer.write(output_file)
logging.debug(f"Extracted {pages_to_extract} pages to {output_path}")
return True
except Exception as e:
logging.error(f"Error extracting pages: {e}")
return False
def extract_text(self, pdf_path: str, max_pages: Optional[int] = None) -> str:
"""Extract text content from PDF for LLM analysis."""
if max_pages is None:
extraction_pages = self.config.get("pdf.extraction_pages", 3)
if isinstance(extraction_pages, int):
max_pages = extraction_pages
else:
max_pages = 3
try:
text_content = []
with open(pdf_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
pages_to_process = min(max_pages, len(reader.pages))
for i in range(pages_to_process):
page = reader.pages[i]
page_text = page.extract_text()
if page_text.strip():
text_content.append(
f"--- Page {i + 1} ---\n{page_text.strip()}"
)
full_text = "\n\n".join(text_content)
logging.debug(
f"Extracted {len(full_text)} characters of text from {pages_to_process} pages"
)
return full_text
except Exception as e:
logging.error(f"Error extracting text from PDF {pdf_path}: {e}")
return ""
def should_extract(self, page_count: int) -> bool:
"""Determine if PDF should be truncated based on page count."""
max_pages = self.config.get("pdf.max_pages_before_extraction", 3)
if isinstance(max_pages, int):
return page_count > max_pages
return page_count > 3
def detect_image_only_pdf(
self, pdf_path: str, min_text_per_page: Optional[int] = None
) -> bool:
"""Detect if a PDF contains only images with no extractable text."""
if min_text_per_page is None:
min_text_per_page = self.config.get("ocr.min_text_per_page", 50)
try:
total_text_length = 0
page_count = 0
with open(pdf_path, "rb") as f:
reader = PyPDF2.PdfReader(f)
page_count = len(reader.pages)
for page in reader.pages:
page_text = page.extract_text()
total_text_length += len(page_text.strip())
# Calculate average text per page
avg_text_per_page = total_text_length / page_count if page_count > 0 else 0
# If average text per page is less than threshold, consider it image-only
is_image_only = avg_text_per_page < min_text_per_page
logging.debug(
f"PDF text analysis: {total_text_length} chars across {page_count} pages "
f"(avg: {avg_text_per_page:.1f} chars/page). Image-only: {is_image_only}"
)
return is_image_only
except Exception as e:
logging.error(f"Error detecting image-only PDF: {e}")
return False
def perform_ocr(self, pdf_path: str, language: Optional[str] = None) -> List[str]:
"""Perform OCR on a PDF and return text for each page."""
ocr_results = []
# Get OCR configuration
if language is None:
language = self.config.get("ocr.language", "eng")
dpi = self.config.get("ocr.dpi", 300)
try:
# Convert PDF to images
logging.info(f"Converting PDF to images for OCR (DPI: {dpi})...")
images = convert_from_path(pdf_path, dpi=dpi)
# Perform OCR on each page
for i, image in enumerate(images):
logging.debug(f"Performing OCR on page {i + 1}/{len(images)}...")
try:
text = pytesseract.image_to_string(image, lang=language)
ocr_results.append(text)
except Exception as e:
logging.error(f"OCR failed on page {i + 1}: {e}")
ocr_results.append("")
logging.info(f"OCR completed on {len(images)} pages")
return ocr_results
except Exception as e:
logging.error(f"Error performing OCR: {e}")
return []
def create_searchable_pdf(
self, original_pdf_path: str, ocr_text_list: List[str], output_path: str
) -> bool:
"""Create a searchable PDF by adding OCR text as an invisible layer."""
try:
# Read original PDF
with open(original_pdf_path, "rb") as input_file:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
# Process each page
for page_num, page in enumerate(reader.pages):
# Create a new page with the same dimensions
writer.add_page(page)
# If we have OCR text for this page, we'll add it as metadata
# Note: PyPDF2 doesn't directly support invisible text layers,
# but we can add the text to the page's content stream in a way
# that makes it searchable
if page_num < len(ocr_text_list) and ocr_text_list[page_num]:
# This is a simplified approach - in production, you might want
# to use a more sophisticated library like reportlab for better
# text layer handling
pass
# Add metadata indicating OCR was performed
writer.add_metadata(
{
"/OCR": "Tesseract",
"/OCRDate": str(datetime.now()),
}
)
# Write the output file
with open(output_path, "wb") as output_file:
writer.write(output_file)
logging.info(f"Created searchable PDF at {output_path}")
return True
except Exception as e:
logging.error(f"Error creating searchable PDF: {e}")
return False
class BaseLLMClient:
"""Base class for LLM clients."""
def __init__(
self,
config: ConfigManager,
provider: str,
model: str,
max_tokens: Optional[int] = None,
):
self.config = config
self.provider = provider
self.model = model
# Use command line override if provided, otherwise fall back to config
if max_tokens is not None:
self.max_tokens = max_tokens
logging.info(f"Using command line override: max_tokens = {max_tokens}")
else:
self.max_tokens = config.get("llm.max_tokens", 1000)
self.temperature = config.get("llm.temperature", 0.3)
self.token_costs: List[Dict[str, Any]] = []
def analyze_document(
self,
document_text: Optional[str] = None,
prompt_config: Optional[Dict[str, Any]] = None,
pdf_path: Optional[str] = None,
) -> Tuple[Optional[str], Dict[str, Any]]:
"""Send document text or PDF to LLM for analysis.
Args:
document_text: Extracted text content (if available)
prompt_config: Prompt configuration dictionary
pdf_path: Path to PDF file for direct upload (if text extraction failed)
"""
raise NotImplementedError("Subclasses must implement analyze_document")
def _encode_pdf_to_base64(self, pdf_path: str) -> str:
"""Encode PDF file to base64 for API upload."""
try:
with open(pdf_path, "rb") as pdf_file:
pdf_bytes = pdf_file.read()
return base64.b64encode(pdf_bytes).decode("utf-8")
except Exception as e:
logging.error(f"Error encoding PDF to base64: {e}")
return ""
def supports_pdf(self) -> bool:
"""Check if the current model supports PDF upload."""
pdf_support = self.config.get(f"llm.providers.{self.provider}.pdf_support", {})
if isinstance(pdf_support, dict):
return pdf_support.get(self.model, False)
return False
def get_total_costs(self) -> Dict[str, int]:
"""Get total token costs for all requests."""
if not self.token_costs:
return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
return {
"prompt_tokens": sum(cost["prompt_tokens"] for cost in self.token_costs),
"completion_tokens": sum(
cost["completion_tokens"] for cost in self.token_costs
),
"total_tokens": sum(cost["total_tokens"] for cost in self.token_costs),
}
class XAIClient(BaseLLMClient):
"""X.AI (Grok) API client."""
def __init__(
self,
config: ConfigManager,
provider: str,
model: str,
max_tokens: Optional[int] = None,
):
super().__init__(config, provider, model, max_tokens)
self.api_key = self._get_api_key()
self.endpoint = config.get(f"llm.providers.{provider}.api_endpoint")
def _get_api_key(self) -> str:
api_key_env = self.config.get(f"llm.providers.{self.provider}.api_key_env")
if not isinstance(api_key_env, str):
logging.error(
f"Invalid API key environment variable name for {self.provider}"
)
sys.exit(1)
api_key = os.getenv(api_key_env)
if not api_key:
logging.error(f"API key not found in environment variable: {api_key_env}")
sys.exit(1)
return api_key
def analyze_document(
self,
document_text: Optional[str] = None,
prompt_config: Optional[Dict[str, Any]] = None,
pdf_path: Optional[str] = None,
) -> Tuple[Optional[str], Dict[str, Any]]:
"""Send document text or PDF to Grok for analysis."""
try:
if prompt_config is None:
logging.error("Prompt config is required")
return None, {}
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
# Prepare message content based on available input
if document_text:
user_message = f"{prompt_config.get('user_prompt', '')}\n\nDocument content:\n{document_text}"
messages = [
{
"role": "system",
"content": prompt_config.get("system_prompt", ""),
},
{"role": "user", "content": user_message},
]
elif pdf_path and self.supports_pdf():
# For vision models, encode PDF as base64
pdf_base64 = self._encode_pdf_to_base64(pdf_path)
if not pdf_base64:
return None, {}
user_message = f"{prompt_config.get('user_prompt', '')}\n\nPlease analyze this PDF document:"
messages = [
{
"role": "system",
"content": prompt_config.get("system_prompt", ""),
},
{
"role": "user",
"content": [
{"type": "text", "text": user_message},
{
"type": "image_url",
"image_url": {
"url": f"data:application/pdf;base64,{pdf_base64}"
},
},
],
},
]
else:
if pdf_path and not self.supports_pdf():
logging.error(
f"Model {self.model} does not support PDF uploads. PDF support available in: grok-4-0709, grok-vision-beta"
)
else:
logging.error("Neither document text nor PDF path provided")
return None, {}
payload = {
"model": self.model,
"messages": messages,
"max_tokens": self.max_tokens,
"temperature": self.temperature,
}
endpoint = self.endpoint
if not isinstance(endpoint, str):
logging.error("Invalid API endpoint configuration")
return None, {}
response = requests.post(
endpoint, json=payload, headers=headers, timeout=60
)
response.raise_for_status()
result = response.json()
usage = result.get("usage", {})
cost_info = {
"prompt_tokens": usage.get("prompt_tokens", 0),
"completion_tokens": usage.get("completion_tokens", 0),
"total_tokens": usage.get("total_tokens", 0),
}
self.token_costs.append(cost_info)
suggested_name = result["choices"][0]["message"]["content"].strip()
logging.info(f"X.AI suggested filename: {suggested_name}")
return suggested_name, cost_info
except Exception as e:
logging.error(f"X.AI API error: {e}")
return None, {}
class AnthropicClient(BaseLLMClient):
"""Anthropic Claude API client."""
def __init__(
self,
config: ConfigManager,
provider: str,
model: str,
max_tokens: Optional[int] = None,
):
super().__init__(config, provider, model, max_tokens)
self.api_key = self._get_api_key()
self._setup_client()
def _get_api_key(self) -> str:
api_key_env = self.config.get(f"llm.providers.{self.provider}.api_key_env")
api_key = os.getenv(api_key_env)
if not api_key:
logging.error(f"API key not found in environment variable: {api_key_env}")
sys.exit(1)
return api_key
def _setup_client(self) -> None:
try:
import anthropic
self.client = anthropic.Anthropic(api_key=self.api_key)
except ImportError:
logging.error(
"Anthropic library not installed. Please install with: pip install anthropic"
)
sys.exit(1)
def analyze_document(
self,
document_text: Optional[str] = None,
prompt_config: Optional[Dict[str, Any]] = None,
pdf_path: Optional[str] = None,
) -> Tuple[Optional[str], Dict[str, Any]]:
"""Send document text or PDF to Claude for analysis."""
try:
if prompt_config is None:
logging.error("Prompt config is required")
return None, {}
# Prepare message content based on available input
if document_text:
user_message = f"{prompt_config.get('user_prompt', '')}\n\nDocument content:\n{document_text}"
messages = [{"role": "user", "content": user_message}]
elif pdf_path and self.supports_pdf():
# Claude supports PDF uploads via base64 encoding
pdf_base64 = self._encode_pdf_to_base64(pdf_path)
if not pdf_base64:
return None, {}
user_message = f"{prompt_config.get('user_prompt', '')}\n\nPlease analyze this PDF document:"
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": user_message},
{
"type": "document",
"source": {
"type": "base64",
"media_type": "application/pdf",
"data": pdf_base64,
},
},
],
}
]
else:
if pdf_path and not self.supports_pdf():
logging.error(
f"Model {self.model} does not support PDF uploads. PDF support available in: claude-opus-4-20250514, claude-sonnet-4-20250514, claude-3-7-sonnet-20250219, claude-3-5-sonnet-20241022"
)
else:
logging.error("Neither document text nor PDF path provided")
return None, {}
response = self.client.messages.create(
model=self.model,
max_tokens=self.max_tokens,
temperature=self.temperature,
system=prompt_config.get("system_prompt", ""),
messages=messages,
)
cost_info = {
"prompt_tokens": response.usage.input_tokens,
"completion_tokens": response.usage.output_tokens,
"total_tokens": response.usage.input_tokens
+ response.usage.output_tokens,
}
self.token_costs.append(cost_info)
suggested_name = response.content[0].text.strip()
logging.info(f"Claude suggested filename: {suggested_name}")
return suggested_name, cost_info
except Exception as e:
logging.error(f"Anthropic API error: {e}")
return None, {}
class OpenAIClient(BaseLLMClient):
"""OpenAI GPT API client."""
def __init__(
self,
config: ConfigManager,
provider: str,
model: str,
max_tokens: Optional[int] = None,
):
super().__init__(config, provider, model, max_tokens)
self.api_key = self._get_api_key()
self._setup_client()
def _get_api_key(self) -> str:
api_key_env = self.config.get(f"llm.providers.{self.provider}.api_key_env")
api_key = os.getenv(api_key_env)
if not api_key:
logging.error(f"API key not found in environment variable: {api_key_env}")
sys.exit(1)
return api_key
def _setup_client(self) -> None:
try:
import openai
self.client = openai.OpenAI(api_key=self.api_key)
except ImportError:
logging.error(
"OpenAI library not installed. Please install with: pip install openai"
)
sys.exit(1)
def analyze_document(
self,
document_text: Optional[str] = None,
prompt_config: Optional[Dict[str, Any]] = None,
pdf_path: Optional[str] = None,
) -> Tuple[Optional[str], Dict[str, Any]]:
"""Send document text or PDF to OpenAI for analysis."""
try:
if prompt_config is None:
logging.error("Prompt config is required")
return None, {}
# Prepare message content based on available input
if document_text:
user_message = f"{prompt_config.get('user_prompt', '')}\n\nDocument content:\n{document_text}"
messages = [
{
"role": "system",
"content": prompt_config.get("system_prompt", ""),
},
{"role": "user", "content": user_message},
]
elif pdf_path and self.supports_pdf():
# Vision-enabled models support PDF uploads
pdf_base64 = self._encode_pdf_to_base64(pdf_path)
if not pdf_base64:
return None, {}
user_message = f"{prompt_config.get('user_prompt', '')}\n\nPlease analyze this PDF document:"
messages = [
{
"role": "system",
"content": prompt_config.get("system_prompt", ""),
},
{
"role": "user",
"content": [
{"type": "text", "text": user_message},
{
"type": "image_url",
"image_url": {
"url": f"data:application/pdf;base64,{pdf_base64}"
},
},
],
},
]
else:
if pdf_path and not self.supports_pdf():
logging.error(
f"Model {self.model} does not support PDF uploads. PDF support available in: o3, gpt-4o, gpt-4o-mini"
)
else:
logging.error("Neither document text nor PDF path provided")
return None, {}
response = self.client.chat.completions.create(
model=self.model,
messages=messages,
max_tokens=self.max_tokens,
temperature=self.temperature,
)
cost_info = {
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens,
"total_tokens": response.usage.total_tokens,
}
self.token_costs.append(cost_info)
suggested_name = response.choices[0].message.content.strip()
logging.info(f"OpenAI suggested filename: {suggested_name}")
return suggested_name, cost_info
except Exception as e:
logging.error(f"OpenAI API error: {e}")
return None, {}
class GoogleClient(BaseLLMClient):
"""Google Vertex AI API client."""
def __init__(
self,
config: ConfigManager,
provider: str,
model: str,
max_tokens: Optional[int] = None,
):
super().__init__(config, provider, model, max_tokens)
self.project_id = self._get_project_id()
self.location = config.get(f"llm.providers.{provider}.location", "us-central1")
self._setup_client()
def _get_project_id(self) -> str:
project_env = self.config.get(f"llm.providers.{self.provider}.project_id_env")
project_id = os.getenv(project_env)
if not project_id:
logging.error(
f"Project ID not found in environment variable: {project_env}"
)
sys.exit(1)
return project_id