Spaces:
Sleeping
Sleeping
Victor Gerardo Rivera commited on
Commit ·
a63e7fe
1
Parent(s): 1b379e9
Refine AI extraction questions and logging
Browse files21 unmodified lines222324252627281 unmodified line303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878821 unmodified linesself.hf_token = hf_token or os.getenv("HF_TOKEN")async def extract_data(self, file_content: str, file_name: str) -> LabReportData:# 1. Ensure we have an image even if it's a PDFimage_to_process = Nonetry:image_data = base64.b64decode(file_content)1 unmodified linefrom pdf2image import convert_from_bytesimages = convert_from_bytes(image_data)if images:# Use the first page for extractionbuffered = io.BytesIO()images[0].save(buffered, format="JPEG")image_to_process = base64.b64encode(buffered.getvalue()).decode("utf-8")else:image_to_process = file_content # Already an imageexcept Exception as e:print(f"Error preparing file for extraction: {e}")# 2. Use the Inference API for real extractionif self.hf_token and image_to_process:try:import requestsAPI_URL = "https://api-inference.huggingface.co/models/impira/layoutlm-document-qa"headers = {"Authorization": f"Bearer {self.hf_token}"}def query(question):payload = {"inputs": {"image": image_to_process,"question": question}}response = requests.post(API_URL, headers=headers, json=payload)return response.json()# Attempt real extractionsstrain_resp = query("What is the strain name?")thc_resp = query("What is the Total THC percentage?")cbd_resp = query("What is the Total CBD percentage?")# If we get credible answers, we build a real objectif isinstance(strain_resp, list) and len(strain_resp) > 0:real_strain = strain_resp[0].get("answer", "Blue Dream")real_thc = 0.0if isinstance(thc_resp, list) and len(thc_resp) > 0:try:# Clean "22.5%" -> 22.5thc_str = thc_resp[0].get("answer", "0").replace("%", "").strip()real_thc = float(thc_str)except: passreturn LabReportData(strain_name=real_strain,cannabinoids=[Cannabinoid(name="Total THC", value=real_thc)],file_name=file_name,confidence=strain_resp[0].get("score", 0.0),source_type="api")except Exception as e:print(f"Inference API failed, falling back to mock: {e}")# Fallback to mockreturn self._mock_extraction(file_name)def _mock_extraction(self, file_name: str) -> LabReportData:21 unmodified lines222324252627281 unmodified line303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909121 unmodified linesself.hf_token = hf_token or os.getenv("HF_TOKEN")async def extract_data(self, file_content: str, file_name: str) -> LabReportData:# 1. Ensure we have an imageimage_to_process = Nonetry:image_data = base64.b64decode(file_content)1 unmodified linefrom pdf2image import convert_from_bytesimages = convert_from_bytes(image_data)if images:buffered = io.BytesIO()images[0].save(buffered, format="JPEG", quality=90)image_to_process = base64.b64encode(buffered.getvalue()).decode("utf-8")else:image_to_process = file_contentexcept Exception as e:print(f"Error preparing file: {e}")# 2. Inference APIif self.hf_token and image_to_process:try:import requestsAPI_URL = "https://api-inference.huggingface.co/models/impira/layoutlm-document-qa"headers = {"Authorization": f"Bearer {self.hf_token}"}results = {}questions = {"strain": "What is the strain name or sample name?","thc": "What is the total THC percentage?","cbd": "What is the total CBD percentage?","lab": "What is the name of the lab?","date": "What is the test date?"}for key, q in questions.items():payload = {"inputs": {"image": image_to_process, "question": q}}resp = requests.post(API_URL, headers=headers, json=payload).json()if isinstance(resp, list) and len(resp) > 0:results[key] = resp[0]if "strain" in results:strain_name = results["strain"].get("answer", "Unknown Strain")thc_val = 0.0if "thc" in results:try:# Extract number like "22.5" from "22.5%"val_str = "".join(c for c in results["thc"]["answer"] if c.isdigit() or c == ".")thc_val = float(val_str)except: passprint(f"AI Success: {strain_name} - THC: {thc_val}%")return LabReportData(strain_name=strain_name,lab_name=results.get("lab", {}).get("answer"),test_date=results.get("date", {}).get("answer"),cannabinoids=[Cannabinoid(name="Total THC", value=thc_val),Cannabinoid(name="Total CBD", value=0.0) # simplify for now],file_name=file_name,confidence=results["strain"].get("score", 0.0),source_type="ai_real")except Exception as e:print(f"AI Extraction failed: {e}")return self._mock_extraction(file_name)def _mock_extraction(self, file_name: str) -> LabReportData:
services/parser.py+37-34