File size: 5,713 Bytes
f3aae92
 
 
e9fe174
f3aae92
 
e9fe174
 
f3aae92
e9fe174
 
 
 
 
 
 
 
 
 
f3aae92
e9fe174
f3aae92
e9fe174
 
 
 
 
f3aae92
e9fe174
 
 
 
f3aae92
 
 
 
 
 
 
 
 
 
e9fe174
 
f3aae92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9fe174
 
f3aae92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9fe174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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."}},
)


@router.post("/DDR2", response_model=ExtractResponse)
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
  

@router.post("/PDFLumber", response_model=ExtractResponse)
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
    }


@router.post("/vision", response_model=ExtractResponse)
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
    }