AbhijitClemson commited on
Commit
b6c0e26
Β·
verified Β·
1 Parent(s): 3fe1ff6

Update page_files/Upload_Data.py

Browse files
Files changed (1) hide show
  1. page_files/Upload_Data.py +43 -13
page_files/Upload_Data.py CHANGED
@@ -27,10 +27,17 @@ from PIL import Image
27
  from dotenv import load_dotenv
28
  load_dotenv()
29
 
30
- _GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "")
 
 
31
 
32
  # ── imports from doctodb_rag (data extraction) ────────────────────────────────
33
- from categorized.Backend.PDF_DataExtraction import run_pipeline
 
 
 
 
 
34
 
35
  # ── imports from figure_extractor (image extraction) ─────────────────────────
36
  from categorized.Backend.Pdf_ImageExtraction import (
@@ -161,17 +168,18 @@ def save_single_image_with_property(
161
  # expected by the rest of the UI (list of {caption, page, image_data}).
162
  # ─────────────────────────────────────────────────────────────────────────────
163
 
 
164
 
165
  def extract_images(pdf_path: str) -> list:
 
 
 
 
 
166
  try:
167
- from categorized.Backend.Pdf_ImageExtraction import get_available_model
168
- import google.generativeai as genai
169
- api_key = os.getenv("GEMINI_API_KEY", "")
170
- genai.configure(api_key=api_key)
171
- model_name = get_available_model(api_key)
172
- active_model = genai.GenerativeModel(model_name)
173
- plot_data = get_plot_data_from_llm(active_model, pdf_path)
174
- raw_plots = extract_plots(
175
  pdf_path=pdf_path,
176
  plot_data=plot_data,
177
  pad=22,
@@ -181,23 +189,32 @@ def extract_images(pdf_path: str) -> list:
181
  log.error(f"extract_images failed: {e}")
182
  return []
183
 
 
 
 
 
 
184
  image_results = []
185
  for item in raw_plots:
186
  bgr = cv2.imread(item["path"]) if item.get("path") else None
 
187
  if item.get("path") and os.path.exists(item["path"]):
188
  try:
189
  os.remove(item["path"])
190
  except Exception:
191
  pass
 
192
  page = item.get("page", 1)
193
  caption = item.get("caption", f"Figure (page {page})")
194
  safe = re.sub(r"[^\w\-]", "_", caption)[:40]
195
  filename = f"page{page}_{safe}.png"
 
196
  image_results.append({
197
  "caption": caption,
198
  "page": page,
199
  "image_data": [{"array": bgr, "filename": filename}] if bgr is not None else [],
200
  })
 
201
  return image_results
202
 
203
 
@@ -688,9 +705,22 @@ def render_material_data_tab(pdf_path: str):
688
  with open(pdf_path, "rb") as f:
689
  pdf_bytes = f.read()
690
 
691
- df, _, _, _, api_errors, meta = run_pipeline(
692
- pdf_bytes, progress_callback=_cb
693
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
694
  elapsed_total = time.time() - start_ts
695
  bar.progress(1.0)
696
  status.empty()
 
27
  from dotenv import load_dotenv
28
  load_dotenv()
29
 
30
+ _GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
31
+ if not _GEMINI_API_KEY:
32
+ raise RuntimeError("GEMINI_API_KEY not set in environment")
33
 
34
  # ── imports from doctodb_rag (data extraction) ────────────────────────────────
35
+ from categorized.Backend.FinalVerdict import (
36
+ call_gemini_from_bytes,
37
+ convert_to_dataframe,
38
+ _extract_sentences,
39
+ verify_dataframe,
40
+ )
41
 
42
  # ── imports from figure_extractor (image extraction) ─────────────────────────
43
  from categorized.Backend.Pdf_ImageExtraction import (
 
168
  # expected by the rest of the UI (list of {caption, page, image_data}).
169
  # ─────────────────────────────────────────────────────────────────────────────
170
 
171
+ _GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AIzaSyBzyMFKEqcjsWpR-OGAY42T250o1O39v3Y")
172
 
173
  def extract_images(pdf_path: str) -> list:
174
+ """
175
+ Use figure_extractor to detect and crop plot images from a PDF path.
176
+ Returns a list compatible with the image_results shape used throughout the UI:
177
+ [{ "caption": str, "page": int, "image_data": [{"array": bgr_ndarray, "filename": str}] }]
178
+ """
179
  try:
180
+ # gemini_model = init_gemini(_GEMINI_API_KEY)
181
+ plot_data = get_plot_data_from_llm( GEMINI_MODEL, pdf_path)
182
+ raw_plots = extract_plots(
 
 
 
 
 
183
  pdf_path=pdf_path,
184
  plot_data=plot_data,
185
  pad=22,
 
189
  log.error(f"extract_images failed: {e}")
190
  return []
191
 
192
+
193
+
194
+
195
+ # raw_plots items: {caption, page, path, plot_score, plot_type}
196
+ # Convert to image_results shape
197
  image_results = []
198
  for item in raw_plots:
199
  bgr = cv2.imread(item["path"]) if item.get("path") else None
200
+ # clean up temp file written by extract_plots
201
  if item.get("path") and os.path.exists(item["path"]):
202
  try:
203
  os.remove(item["path"])
204
  except Exception:
205
  pass
206
+
207
  page = item.get("page", 1)
208
  caption = item.get("caption", f"Figure (page {page})")
209
  safe = re.sub(r"[^\w\-]", "_", caption)[:40]
210
  filename = f"page{page}_{safe}.png"
211
+
212
  image_results.append({
213
  "caption": caption,
214
  "page": page,
215
  "image_data": [{"array": bgr, "filename": filename}] if bgr is not None else [],
216
  })
217
+
218
  return image_results
219
 
220
 
 
705
  with open(pdf_path, "rb") as f:
706
  pdf_bytes = f.read()
707
 
708
+ _cb("Extracting via Gemini…", 0.30)
709
+ data = call_gemini_from_bytes(pdf_bytes)
710
+ df = convert_to_dataframe(data)
711
+ api_errors = []
712
+
713
+ if not df.empty:
714
+ _cb("Verifying against source PDF…", 0.70)
715
+ sentences = _extract_sentences(pdf_bytes)
716
+ df = verify_dataframe(df, sentences)
717
+
718
+ row0 = df.iloc[0] if not df.empty else {}
719
+ meta = {
720
+ "material_name": str(row0.get("material_name", "")) if not df.empty else "",
721
+ "material_abbreviation": str(row0.get("material_abbreviation", "")) if not df.empty else "",
722
+ }
723
+ _cb("Done.", 1.0)
724
  elapsed_total = time.time() - start_ts
725
  bar.progress(1.0)
726
  status.empty()