Spaces:
Sleeping
Sleeping
Download api/extractor.py from RigDataDynamics/cygnus_server: direct link, hf CLI and curl.
- Browser
- Download file 5.71 kB
-
https://huggingface.co/spaces/RigDataDynamics/cygnus_server/resolve/main/api/extractor.py
- Command line
-
hf download hf://spaces/RigDataDynamics/cygnus_server/api/extractor.py
-
curl -L -o extractor.py https://huggingface.co/spaces/RigDataDynamics/cygnus_server/resolve/main/api/extractor.py
5.71 kB
| import os | |
| from fastapi import APIRouter, File, UploadFile,HTTPException | |
| from langchain_community.document_loaders import PDFPlumberLoader | |
| from db.models import DDR | |
| from extraction.parsing import parse_binary_input | |
| from database import get_mongo_client | |
| import pdfplumber | |
| import pandas as pd | |
| from typing import Any, List, Optional,Dict | |
| from langchain_openai import ChatOpenAI | |
| from graph_version import extract_drilling_information | |
| from retrieval import ExtractResponse | |
| from langchain_core.messages import HumanMessage | |
| import base64 | |
| import io | |
| from IPython.display import Image as IPImage | |
| from IPython.display import display | |
| import fitz | |
| from PIL import Image | |
| MAX_CHUNKS=7000 | |
| def pdf_page_to_base64(pdf_path: str, page_number: int): | |
| pdf_document = fitz.open(pdf_path) | |
| page = pdf_document.load_page(page_number - 1) # input is one-indexed | |
| pix = page.get_pixmap() | |
| img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) | |
| buffer = io.BytesIO() | |
| img.save(buffer, format="PNG") | |
| return base64.b64encode(buffer.getvalue()).decode("utf-8") | |
| router = APIRouter( | |
| prefix="/extract", | |
| tags=["extract"], | |
| responses={404: {"description": "Not found"}, | |
| 422: {"description": "no file provided."}}, | |
| ) | |
| async def upload_ddr2( | |
| *, | |
| file: Optional[UploadFile] = File(None) | |
| ) -> ExtractResponse: | |
| """Endpoint that is used with DDR extractor. | |
| This endpoint will be expanded to support upload of binary files as well as | |
| text files. | |
| """ | |
| if file is None: | |
| raise HTTPException(status_code=422, detail="No file provided.") | |
| temp_file_path = f"./temp_{file.filename}" | |
| with open(temp_file_path, "wb") as buffer: | |
| buffer.write(await file.read()) | |
| # Load the PDF using PDFPlumberLoader | |
| loader = PDFPlumberLoader(file_path=temp_file_path, dedupe=True,text_kwargs={'layout':True}) | |
| documents = loader.load() | |
| # Clean up the temporary file | |
| os.remove(temp_file_path) | |
| #documents = parse_binary_input(file.file) | |
| # TODO: Add metadata like location from original file where | |
| # the text was extracted from | |
| # we also can clasify what informatio exist in echa page to only extract that information | |
| text_ = "\n".join([document.page_content for document in documents]) | |
| #data_result= await extract_entire_document(text_) | |
| data_result=extract_drilling_information(text_) | |
| # Save data_result to the database with file name as metadata | |
| client = get_mongo_client() | |
| db = client['Cygnus'] # Replace with your actual database name | |
| collection = db['ddr_reports'] # Replace with your actual collection name | |
| # Prepare the data to be inserted | |
| data_to_insert = { | |
| "file_name": file.filename, | |
| "raw_data": text_, | |
| "data_result": data_result["data"], | |
| "content_too_long":data_result["content_too_long"] | |
| } | |
| # Insert the data into the collection | |
| collection.insert_one(data_to_insert) | |
| # Return the response | |
| return data_result | |
| async def upload_ddr_with_PDFlumber( | |
| *, | |
| file: Optional[UploadFile] = File(None) | |
| ) -> ExtractResponse: | |
| """Endpoint that is used with DDR extractor. | |
| This endpoint will be expanded to support upload of binary files as well as | |
| text files. | |
| """ | |
| if file is None: | |
| raise HTTPException(status_code=422, detail="No file provided.") | |
| temp_file_path = f"./temp_{file.filename}" | |
| with open(temp_file_path, "wb") as buffer: | |
| buffer.write(await file.read()) | |
| # Load the PDF using PDFPlumberLoader | |
| with pdfplumber.open(temp_file_path) as pdf: | |
| p0 = pdf.pages[0] | |
| im = p0.to_image() | |
| im.debug_tablefinder() | |
| im.show() | |
| tables = p0.extract_tables() | |
| import pandas as pd | |
| # Iterate over the tables list and create a DataFrame for each one | |
| dataframes = [] | |
| for table in tables: | |
| df = pd.DataFrame(table[1:]) # Assuming the first row is the header | |
| dataframes.append(df) | |
| # For demonstration, let's concatenate all dataframes into a single one | |
| df = pd.concat(dataframes, ignore_index=True) | |
| return { | |
| "data": df.to_json() , | |
| "content_too_long": True | |
| } | |
| async def upload_ddr_with_vision( | |
| *, | |
| file: Optional[UploadFile] = File(None) | |
| )-> ExtractResponse: | |
| if file is None: | |
| raise HTTPException(status_code=422, detail="No file provided.") | |
| temp_file_path = f"./temp_{file.filename}" | |
| with open(temp_file_path, "wb") as buffer: | |
| buffer.write(await file.read()) | |
| base64_image = pdf_page_to_base64(temp_file_path, 1) | |
| display(IPImage(data=base64.b64decode(base64_image))) | |
| llm = ChatOpenAI(model="gpt-4o-mini", temperature=0).with_structured_output(DDR) | |
| query = "You are a top-tier algorithm for extracting information from text,you are specialized in Oil Drilling Reports. think step by step and Only extract relevant information entities mentioned in the following passage, together with their properties, If you do not know the value of an attribute asked to extract, return 'null' for the attribute's value." | |
| message = HumanMessage( | |
| content=[ | |
| {"type": "text", "text": query}, | |
| { | |
| "type": "image_url", | |
| "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}, | |
| }, | |
| ], | |
| ) | |
| response = llm.invoke([message]) | |
| print(response) | |
| return { | |
| "data": response.json(), | |
| "content_too_long": True | |
| } |