segovia commited on
Commit
2704ee7
·
1 Parent(s): 22b7714

Open AI client init

Browse files
Files changed (1) hide show
  1. app.py +22 -6
app.py CHANGED
@@ -9,6 +9,8 @@ from pathlib import Path
9
  os.environ["GRADIO_SSR_MODE"] = "false"
10
 
11
  import gradio as gr
 
 
12
 
13
  from document_processing import extract_text, is_image_document, to_data_uri
14
  from receipt_ai import extract_receipt_json, extract_receipt_json_from_image
@@ -41,6 +43,19 @@ def gpu_decorator(fn):
41
  return spaces.GPU(fn)
42
 
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  def parse_uploaded_file(client, model: str, file_path: str) -> dict:
45
  path = Path(file_path)
46
  if is_image_document(path):
@@ -72,16 +87,17 @@ def build_csv_download(rows: list[dict]) -> str:
72
 
73
  @gpu_decorator
74
  def process_files(files: list[str] | None, existing_rows: list[dict] | None, model: str):
75
- from dotenv import load_dotenv
76
- from openai import OpenAI
77
-
78
- load_dotenv()
79
- client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
80
-
81
  rows = list(existing_rows or [])
82
  if not files:
83
  return rows, gr.update(value=rows_to_table(rows)), "No files selected."
84
 
 
 
 
 
 
 
 
85
  for file_path in files:
86
  rows.append(parse_uploaded_file(client, model, file_path))
87
 
 
9
  os.environ["GRADIO_SSR_MODE"] = "false"
10
 
11
  import gradio as gr
12
+ from dotenv import load_dotenv
13
+ from openai import OpenAI
14
 
15
  from document_processing import extract_text, is_image_document, to_data_uri
16
  from receipt_ai import extract_receipt_json, extract_receipt_json_from_image
 
43
  return spaces.GPU(fn)
44
 
45
 
46
+ load_dotenv()
47
+
48
+
49
+ def create_openai_client() -> OpenAI | None:
50
+ api_key = (os.getenv("OPENAI_API_KEY") or "").strip()
51
+ if not api_key:
52
+ return None
53
+ return OpenAI(api_key=api_key)
54
+
55
+
56
+ client = create_openai_client()
57
+
58
+
59
  def parse_uploaded_file(client, model: str, file_path: str) -> dict:
60
  path = Path(file_path)
61
  if is_image_document(path):
 
87
 
88
  @gpu_decorator
89
  def process_files(files: list[str] | None, existing_rows: list[dict] | None, model: str):
 
 
 
 
 
 
90
  rows = list(existing_rows or [])
91
  if not files:
92
  return rows, gr.update(value=rows_to_table(rows)), "No files selected."
93
 
94
+ if client is None:
95
+ return (
96
+ rows,
97
+ gr.update(value=rows_to_table(rows)),
98
+ "Missing OPENAI_API_KEY. Add it as a Hugging Face Space Secret or define it in your local environment.",
99
+ )
100
+
101
  for file_path in files:
102
  rows.append(parse_uploaded_file(client, model, file_path))
103