HPirela commited on
Commit
f3aae92
·
1 Parent(s): cdc9d2c

first version

Browse files
Files changed (14) hide show
  1. .gitignore +2 -0
  2. .vscode/launch.json +16 -0
  3. Dockerfile +13 -0
  4. __init__.py +0 -0
  5. api/__init__.py +0 -0
  6. api/examples.py +90 -0
  7. api/extractor.py +74 -0
  8. database.py +35 -0
  9. db/models.py +206 -0
  10. extraction/parsing.py +78 -0
  11. main.py +72 -0
  12. requirements.txt +17 -0
  13. retrieval.py +262 -0
  14. validators.py +15 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ __pycache__
2
+ venv
.vscode/launch.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ // Use IntelliSense to learn about possible attributes.
3
+ // Hover to view descriptions of existing attributes.
4
+ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
+ "version": "0.2.0",
6
+ "configurations": [
7
+ {
8
+ "name": "Run Cygnus Server",
9
+ "type": "debugpy",
10
+ "request": "launch",
11
+ "program": "main.py",
12
+ "console": "integratedTerminal",
13
+ "env": {"PYTHONPATH":"${workspaceRoot}"}, //
14
+ }
15
+ ]
16
+ }
Dockerfile ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.9
2
+
3
+ RUN useradd -m -u 1000 user
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ CMD ["uvicorn", "app:main.py", "--host", "0.0.0.0", "--port", "7860"]
__init__.py ADDED
File without changes
api/__init__.py ADDED
File without changes
api/examples.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Endpoints for managing definition of examples.."""
2
+ from typing import List
3
+ from uuid import UUID
4
+
5
+ from fastapi import APIRouter, HTTPException
6
+
7
+
8
+ from db.models import Example
9
+
10
+ from database import get_mongo_client
11
+ from pydantic import BaseModel, Field
12
+ router = APIRouter(
13
+ prefix="/examples",
14
+ tags=["example definitions"],
15
+ responses={404: {"description": "Not found"}},
16
+ )
17
+
18
+
19
+ class CreateExample(BaseModel):
20
+ """A request to create examples for a specific report type."""
21
+ examples: List[Example] = Field(..., description="A list of examples associated with the report type.")
22
+
23
+ class CreateExampleResponse(BaseModel):
24
+ """Response for creating an example."""
25
+
26
+ result: int
27
+
28
+
29
+ @router.post("", response_model=CreateExampleResponse)
30
+ def create(
31
+ create_request: List[Example],
32
+
33
+ ) -> CreateExampleResponse:
34
+ """Endpoint to create an example."""
35
+ instance = [example.model_dump() for example in create_request]
36
+
37
+
38
+ db = get_mongo_client().Cygnus
39
+
40
+ example_collection=db["examples"]
41
+
42
+ result=example_collection.insert_many(instance)
43
+ return { "result":len(result.inserted_ids)}
44
+
45
+
46
+
47
+
48
+ @router.get("")
49
+ def list_examples(
50
+ report_type: str,
51
+ *,
52
+ limit: int = 10,
53
+ offset: int = 0,
54
+
55
+ ) -> List[Example]:
56
+ """Endpoint to get all examples."""
57
+ db = get_mongo_client().Cygnus
58
+ example_collection = db["examples"]
59
+
60
+ query = {"report_type": report_type}
61
+
62
+ examples_cursor = example_collection.find(query).skip(offset).limit(limit)
63
+ examples = [Example(**record) for record in examples_cursor]
64
+ return examples
65
+
66
+
67
+
68
+ @router.delete("/{uuid}")
69
+ def delete(
70
+ uuid: UUID
71
+ ) -> None:
72
+ """Endpoint to delete an example."""
73
+ db = get_mongo_client().Cygnus
74
+
75
+ example_collection = db["examples"]
76
+ example = example_collection.find_one({"uuid": uuid})
77
+ if example is None:
78
+ raise HTTPException(status_code=404, detail="Example not found.")
79
+ result = example_collection.delete_one({"uuid": uuid})
80
+ if result.deleted_count == 0:
81
+ raise HTTPException(status_code=404, detail="Example not found.")
82
+
83
+ @router.delete("/all")
84
+ def delete_all() -> None:
85
+ """Endpoint to delete all examples."""
86
+ db = get_mongo_client().Cygnus
87
+ example_collection = db["examples"]
88
+ result = example_collection.delete_many({})
89
+ if result.deleted_count == 0:
90
+ raise HTTPException(status_code=404, detail="No examples found to delete.")
api/extractor.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fastapi import APIRouter, File, UploadFile,HTTPException
3
+ from langchain_community.document_loaders import PDFPlumberLoader
4
+ from extraction.parsing import parse_binary_input
5
+ from database import get_mongo_client
6
+
7
+
8
+ from typing import Any, List, Optional,Dict
9
+
10
+ from retrieval import extract_entire_document, ExtractResponse
11
+
12
+
13
+ MAX_CHUNKS=7000
14
+
15
+
16
+ router = APIRouter(
17
+ prefix="/extract",
18
+ tags=["extract"],
19
+ responses={404: {"description": "Not found"},
20
+ 422: {"description": "no file provided."}},
21
+ )
22
+
23
+
24
+ @router.post("/DDR", response_model=ExtractResponse)
25
+ async def upload_ddr(
26
+ *,
27
+ file: Optional[UploadFile] = File(None)
28
+ ) -> ExtractResponse:
29
+ """Endpoint that is used with DDR extractor.
30
+
31
+ This endpoint will be expanded to support upload of binary files as well as
32
+ text files.
33
+ """
34
+ if file is None:
35
+ raise HTTPException(status_code=422, detail="No file provided.")
36
+
37
+ temp_file_path = f"./temp_{file.filename}"
38
+ with open(temp_file_path, "wb") as buffer:
39
+ buffer.write(await file.read())
40
+
41
+ # Load the PDF using PDFPlumberLoader
42
+ loader = PDFPlumberLoader(file_path=temp_file_path, dedupe=True,text_kwargs={'layout':True})
43
+ documents = loader.load()
44
+
45
+ # Clean up the temporary file
46
+ os.remove(temp_file_path)
47
+ #documents = parse_binary_input(file.file)
48
+
49
+ # TODO: Add metadata like location from original file where
50
+ # the text was extracted from
51
+ # we also can clasify what informatio exist in echa page to only extract that information
52
+ text_ = "\n".join([document.page_content for document in documents])
53
+
54
+ data_result= await extract_entire_document(text_)
55
+ # Save data_result to the database with file name as metadata
56
+ client = get_mongo_client()
57
+ db = client['Cygnus'] # Replace with your actual database name
58
+ collection = db['ddr_reports'] # Replace with your actual collection name
59
+
60
+ # Prepare the data to be inserted
61
+ data_to_insert = {
62
+ "file_name": file.filename,
63
+ "raw_data": text_,
64
+ "data_result": data_result["data"],
65
+ "content_too_long":data_result["content_too_long"]
66
+ }
67
+
68
+ # Insert the data into the collection
69
+ collection.insert_one(data_to_insert)
70
+
71
+ # Return the response
72
+ return data_result
73
+
74
+
database.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pymongo
3
+
4
+
5
+ from pymongo.mongo_client import MongoClient
6
+ from pymongo.server_api import ServerApi
7
+
8
+
9
+ client = None
10
+
11
+ def get_mongo_client() -> MongoClient:
12
+ global client
13
+ if client is None:
14
+ password = os.environ.get("PASSWORD", "hva3HaKg1S7acKmM")
15
+ uri = f"mongodb+srv://DDR:{password}@cluster0.o7h6s.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
16
+ client = MongoClient(uri, server_api=ServerApi('1'),uuidRepresentation='standard')
17
+ try:
18
+ client.admin.command('ping')
19
+ print("Pinged your deployment. You successfully connected to MongoDB!")
20
+ except Exception as e:
21
+ print(e)
22
+
23
+ return client
24
+
25
+
26
+ # Max concurrency used for extracting content from documents.
27
+ # A long document is broken into smaller chunks this controls
28
+ # how many chunks are processed concurrently.
29
+ MAX_CONCURRENCY = int(os.environ.get("MAX_CONCURRENCY", 1))
30
+
31
+ # Max number of chunks to process per documents
32
+ # When a long document is split into chunks, this controls
33
+ # how many of those chunks will be processed.
34
+ # Set to 0 or negative to disable the max chunks limit.
35
+ MAX_CHUNKS = int(os.environ.get("MAX_CHUNKS", -1))
db/models.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import uuid
2
+ from uuid import UUID
3
+ from datetime import datetime, timezone
4
+ from typing import Any, Dict, Optional, List
5
+ from pydantic import BaseModel, Field
6
+
7
+
8
+
9
+
10
+ class DDRHEADER(BaseModel):
11
+ """General Information about a Daily drilling report."""
12
+
13
+ # ^ Doc-string for the entity DDRHEADER.
14
+ # This doc-string is sent to the LLM as the description of the schema DDRHEADER,
15
+ # and it can help to improve extraction results.
16
+
17
+ # Note that:
18
+ # 1. Each field is an `optional` -- this allows the model to decline to extract it!
19
+ # 2. Each field has a `description` -- this description is used by the LLM.
20
+ # Having a good description can help improve extraction results.
21
+ well_name: Optional[str] = Field(
22
+ default='', description="name of the well tipical labels: well name , well:"
23
+ )
24
+ # add required float field maxdepth
25
+ measure_depth: Optional[str] = Field(
26
+ default='0', description="last measure depth or MD at the end of the day, usually comes as MD and in feet or meters'"
27
+ )
28
+ vertical_depth: Optional[float] = Field(
29
+ default=0, description="true vertical depth or TVD, usually comes as TVD and in ft'"
30
+ )
31
+ rig_name: Optional[str] = Field(
32
+ default='', description="name of the RIG typical labels: RIG NO. , RIG NAME"
33
+ )
34
+ operator_name: Optional[str] = Field(
35
+ default='', description="operator name or company name"
36
+ )
37
+ date_of_report: Optional[str] = Field(
38
+ default='', description="date of report, common labeled as date or Report date"
39
+ )
40
+ days_from_spud: Optional[str] = Field(
41
+ default='', description="Days from Spud,(DFS) is the number of days from the beginning of the drilling operation to the report date"
42
+ )
43
+ spud_date: Optional[datetime] = Field(
44
+ default='', description="you can find it as spud date (SD) is the date when the drilling operation begin"
45
+ )
46
+ report_num: Optional[str] = Field(
47
+ default='', description="report number or report no. or rpt #"
48
+ )
49
+ state: Optional[str] = Field(
50
+ default='', description="state name, usually county/state, for examples: Texas or California"
51
+ )
52
+ field_name: Optional[str] = Field(
53
+ default='', description="Field name where the well is located typical label: Field"
54
+ )
55
+ wellbore: Optional[str] = Field(
56
+ default='', description="branch name or wellbore name also could be trajectory Name"
57
+ )
58
+ hole_size: Optional[str] = Field(
59
+ default='', description="size of the current open hole, also know as phase"
60
+ )
61
+
62
+
63
+ class DAILYOPER(BaseModel):
64
+ """
65
+ extract a the daily summary operation .
66
+ """
67
+ time_from: Optional[str] = Field(
68
+ default='', description=" Time from, usually in the format hh:mm or h:mm, typical labels: 'From' or 'start time'"
69
+ )
70
+ time_to: Optional[str] = Field(
71
+ default='', description=" Time To , usually in the format hh:mm or h:mm, typical labels: 'to' or 'end Time'"
72
+ )
73
+
74
+ activity_code: Optional[str] = Field(
75
+ default='', description="string that codify the code of the current activity"
76
+ )
77
+ description: Optional[str] = Field(
78
+ default='', description="The description of the current operation or comments, which could take several lines"
79
+ )
80
+ class DAILYOPERATIONS (BaseModel):
81
+ """A list of daily summary operations"""
82
+ operations: List[DAILYOPER]
83
+
84
+ class FLUID(BaseModel):
85
+ """
86
+ Extract Daily drilling fluid information.
87
+ """
88
+ density: Optional[float] = Field(
89
+ default=0.0, description="Density of mud fluid, usually in g/cm³ or lb/gal or ppg"
90
+ )
91
+ fluid_name: Optional[str] = Field(
92
+ default='', description="Name of the mud fluid"
93
+ )
94
+ fluid_type: Optional[str] = Field(
95
+ default='', description="Type of the mud fluid, e.g., water-based, oil-based"
96
+ )
97
+ viscosity: Optional[float] = Field(
98
+ default=0.0, description="Viscosity of the fluid (PV), usually in cP"
99
+ )
100
+ YP: Optional[float] = Field(
101
+ default=0.0, description="Yield Point (YP) of the Mud"
102
+ )
103
+ temperature: Optional[float] = Field(
104
+ default=0.0, description="Temperature of the Mud fluid, usually in °C or °F"
105
+ )
106
+ fluid_depth: Optional[float] = Field(
107
+ default=0.0, description="Depth at which the mud fluid is measured, usually in ft or m"
108
+ )
109
+
110
+
111
+
112
+
113
+ class TimestampedModel(BaseModel):
114
+ """An abstract base model that includes the timestamp fields."""
115
+ __abstract__ = True
116
+ created_at: datetime = Field(
117
+ default_factory=lambda: datetime.now(timezone.utc),
118
+ description="The time the record was created (UTC)."
119
+ )
120
+ updated_at: datetime = Field(
121
+ default_factory=lambda: datetime.now(timezone.utc),
122
+ description="The time the record was updated (UTC)."
123
+ )
124
+
125
+ # This is our own uuid assigned to the artifact.
126
+ # By construction guaranteed to be unique no matter what.
127
+ uuid: UUID = Field(
128
+ default_factory=uuid.uuid4,
129
+ description="Unique identifier for this example."
130
+ )
131
+
132
+
133
+ class Example(TimestampedModel):
134
+ """A representation of an example.
135
+
136
+ Examples consist of content together with the expected output.
137
+
138
+ The output is a JSON object that is expected to be extracted from the content.
139
+
140
+ The JSON object should be valid according to the schema of the associated Report extractor.
141
+
142
+ The JSON object is defined by the schema of the associated Report extractor, so
143
+ it's perfectly fine for a given example to represent the extraction
144
+ of multiple instances of some object from the content since
145
+ the JSON schema can represent a list of objects.
146
+ """
147
+
148
+ __tablename__ = "examples"
149
+
150
+ text: str = Field(
151
+ ...,
152
+ description="The input portion of the example."
153
+ )
154
+ output: List[Dict[str, Any]] = Field(
155
+ ..., description="The expected output of the example. A list of objects."
156
+ )
157
+
158
+ report_type: str = Field(
159
+ ...,
160
+ description="type od report associated with the example."
161
+ )
162
+
163
+ def __repr__(self) -> str:
164
+ return f"<Example(report_type={self.report_type}, content={self.text[:20]}>"
165
+
166
+
167
+ class ReportExtractor(TimestampedModel):
168
+ __tablename__ = "reportextractors"
169
+
170
+ name: str = Field(
171
+ ...,
172
+ max_length=100,
173
+ description="The name of the extractor."
174
+ )
175
+ owner_id: str = Field(
176
+ ...,
177
+ description="Owner uuid."
178
+ )
179
+ output_schema: dict = Field(
180
+ ...,
181
+ description="JSON Schema that describes what content will be extracted from the document."
182
+ )
183
+ description: str = Field(
184
+ ...,
185
+ max_length=100,
186
+ description="Surfaced via UI to the users."
187
+ )
188
+ instruction: str = Field(
189
+ ...,
190
+ description="The prompt to the language model."
191
+ ) # TODO: This will need to evolve
192
+
193
+ examples: List[Example] = Field(
194
+ default_factory=list,
195
+ description="List of examples associated with this Reportextractor."
196
+ )
197
+ report_type: str = Field(
198
+ ...,
199
+ description="type of report ."
200
+ )
201
+
202
+ def __repr__(self) -> str:
203
+ return f"<ReportExtractor(id={self.report_type}, description={self.description})>"
204
+
205
+
206
+
extraction/parsing.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert binary input to blobs and parse them using the appropriate parser."""
2
+ from __future__ import annotations
3
+ from typing import BinaryIO, List
4
+ from fastapi import HTTPException
5
+ from langchain_community.document_loaders.parsers.pdf import PDFPlumberParser
6
+ from langchain_community.document_loaders.parsers.generic import MimeTypeBasedParser
7
+ from langchain_community.document_loaders.parsers.txt import TextParser
8
+ from langchain_community.document_loaders import Blob
9
+ from langchain_core.documents import Document
10
+
11
+ HANDLERS = {
12
+ "application/pdf": PDFPlumberParser(),
13
+ "text/plain": TextParser()
14
+
15
+ }
16
+
17
+ SUPPORTED_MIMETYPES = sorted(HANDLERS.keys())
18
+
19
+ MAX_FILE_SIZE_MB = 10 # in MB
20
+
21
+
22
+ def _guess_mimetype(file_bytes: bytes) -> str:
23
+ """Guess the mime-type of a file."""
24
+ try:
25
+ import magic
26
+ except ImportError as e:
27
+ raise ImportError(
28
+ "magic package not found, please install it with `pip install python-magic`"
29
+ ) from e
30
+
31
+ mime = magic.Magic(mime=True)
32
+ mime_type = mime.from_buffer(file_bytes)
33
+ return mime_type
34
+
35
+
36
+ def _get_file_size_in_mb(data: BinaryIO) -> float:
37
+ """Get file size in MB."""
38
+ data.seek(0, 2) # Move the cursor to the end of the file
39
+ file_size = data.tell()
40
+ file_size_in_mb = file_size / (1024 * 1024)
41
+ data.seek(0)
42
+ return file_size_in_mb
43
+
44
+
45
+ # PUBLIC API
46
+
47
+ MIMETYPE_BASED_PARSER = MimeTypeBasedParser(
48
+ handlers=HANDLERS,
49
+ fallback_parser=None,
50
+ )
51
+
52
+
53
+ def convert_binary_input_to_blob(data: BinaryIO) -> Blob:
54
+ """Convert ingestion input to blob."""
55
+ file_size_in_mb = _get_file_size_in_mb(data)
56
+
57
+ if file_size_in_mb > MAX_FILE_SIZE_MB:
58
+ raise HTTPException(
59
+ status_code=413,
60
+ detail=f"File size exceeds the maximum limit of {MAX_FILE_SIZE_MB} MB.",
61
+ )
62
+
63
+ file_data = data.read()
64
+ mimetype = "application/pdf" # _guess_mimetype(file_data)
65
+ file_name = data.name
66
+
67
+ return Blob.from_data(
68
+ data=file_data,
69
+ path=file_name,
70
+ mime_type=mimetype,
71
+ )
72
+
73
+
74
+ def parse_binary_input(data: BinaryIO) -> List[Document]:
75
+ """Parse binary input."""
76
+ blob = convert_binary_input_to_blob(data)
77
+ louder=PDFPlumberParser( dedupe=True,text_kwargs={'layout':False})
78
+ return louder.parse(blob)
main.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Entry point into the server."""
2
+ import logging
3
+ import os
4
+ import sys
5
+ from pathlib import Path
6
+ from fastapi import FastAPI
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from langserve import add_routes
9
+
10
+ from api import examples, extractor
11
+ """ from server.extraction_runnable import (
12
+ ExtractRequest,
13
+ ExtractResponse,
14
+ extraction_runnable,
15
+ )
16
+ """
17
+ logger = logging.getLogger(__name__)
18
+
19
+ app = FastAPI(
20
+ title="Cygnus Server",
21
+ version="0.0.1",
22
+ description="extraction service for drilling related reports",
23
+ openapi_tags=[
24
+ {
25
+ "name": "cygnus",
26
+ "description": "Operations related to extracting information from drilling related reports.",
27
+ }
28
+ ],
29
+ )
30
+
31
+
32
+ ROOT = Path(__file__).parent.parent
33
+
34
+ ORIGINS = os.environ.get("CORS_ORIGINS", "").split(",")
35
+
36
+ if ORIGINS:
37
+ app.add_middleware(
38
+ CORSMiddleware,
39
+ allow_origins=ORIGINS,
40
+ allow_credentials=True,
41
+ allow_methods=["*"],
42
+ allow_headers=["*"],
43
+ )
44
+
45
+
46
+ @app.get("/ready")
47
+ def ready() -> str:
48
+ return "ok"
49
+
50
+
51
+ # Include API endpoints for extractor definitions
52
+
53
+ app.include_router(examples.router)
54
+ app.include_router(extractor.router)
55
+
56
+
57
+ """ add_routes(
58
+ app,
59
+ extraction_runnable.with_types(
60
+ input_type=ExtractRequest, output_type=ExtractResponse
61
+ ),
62
+ path="/extract_text",
63
+ enabled_endpoints=["invoke", "batch"],
64
+ )
65
+ """
66
+
67
+
68
+
69
+ if __name__ == "__main__":
70
+ import uvicorn
71
+
72
+ uvicorn.run(app, host="localhost", port=8000)
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ jsonschema
4
+ langchain
5
+ langchain_community
6
+ langchain_core
7
+ langchain_groq
8
+ langchain_huggingface
9
+ langchain_mongodb
10
+ langserve
11
+ pydantic
12
+ pymongo
13
+ python_magic
14
+ typing_extensions
15
+ python-multipart
16
+ pdfplumber
17
+ tiktoken
retrieval.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from operator import itemgetter
3
+ from typing import Any, Dict, List, Optional, Sequence
4
+ import uuid
5
+ from langchain_groq import ChatGroq
6
+ from langchain.text_splitter import CharacterTextSplitter,TokenTextSplitter
7
+
8
+ from langchain_core.runnables import RunnableLambda
9
+ from db.models import DDRHEADER,DAILYOPERATIONS,FLUID,Example
10
+ from database import get_mongo_client
11
+ from langchain_huggingface import HuggingFaceEmbeddings
12
+ from typing_extensions import TypedDict
13
+ from langchain_mongodb.vectorstores import MongoDBAtlasVectorSearch
14
+ from langserve import CustomUserType
15
+ from pydantic import BaseModel, Field
16
+ from langchain_core.runnables import chain
17
+ from langchain_core.prompts import ChatPromptTemplate,MessagesPlaceholder
18
+ from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
19
+
20
+
21
+ class ExtractRequest(CustomUserType):
22
+ """Request body for the extract endpoint."""
23
+
24
+ text: str = Field(..., description="The text to extract from.")
25
+ examples: Optional[List[Example]] = Field(
26
+ None, description="Examples of extractions."
27
+ )
28
+
29
+ class ExtractResponse(TypedDict, total=False):
30
+ """Response body for the extract endpoint."""
31
+
32
+ data: Any
33
+ # content to long will be set to true if the content is too long
34
+ # and had to be truncated
35
+ content_too_long: Optional[bool]
36
+
37
+
38
+
39
+ def deduplicate(
40
+ extract_responses: Sequence[ExtractResponse],
41
+ ) -> ExtractResponse:
42
+ """Deduplicate the results.
43
+
44
+ The deduplication is done by comparing the serialized JSON of each of the results
45
+ and only keeping the unique ones.
46
+ """
47
+ unique_extracted = []
48
+ seen = set()
49
+ for response in extract_responses:
50
+ for data_item in response["data"]:
51
+ # Serialize the data item for comparison purposes
52
+ serialized = json.dumps(data_item, sort_keys=True)
53
+ if serialized not in seen:
54
+ seen.add(serialized)
55
+ unique_extracted.append(data_item)
56
+
57
+ return {
58
+ "data": unique_extracted,
59
+ }
60
+
61
+ def _make_prompt_template(
62
+ examples: Optional[Sequence[Example]],
63
+ function_name: str,
64
+ ) -> ChatPromptTemplate:
65
+ """Make a system message from instructions and examples."""
66
+ prefix = (
67
+ "You are a top-tier algorithm for extracting information from text. "
68
+ "Only extract information that is relevant to the provided text. "
69
+ "If no information is relevant, use the schema and output "
70
+ "an empty list where appropriate."
71
+ )
72
+ system_message = ("system", prefix)
73
+ prompt_components = [system_message]
74
+ if examples is not None:
75
+ few_shot_prompt = []
76
+ for example in examples:
77
+ # TODO: We'll need to refactor this at some point to
78
+ # support other encoding strategies. The function calling logic here
79
+ # has some hard-coded assumptions (e.g., name of parameters like `data`).
80
+ _id = uuid.uuid4().hex[:]
81
+ tool_call = {
82
+ "args": {"data": example.output},
83
+ "name": function_name,
84
+ "id": _id,
85
+ }
86
+ few_shot_prompt.extend(
87
+ [
88
+ HumanMessage(content=example.text),
89
+ AIMessage(content="", tool_calls=[tool_call]),
90
+ ToolMessage(
91
+ content="You have correctly called this tool.", tool_call_id=_id
92
+ ),
93
+ ]
94
+ )
95
+ prompt_components.extend(few_shot_prompt)
96
+
97
+ prompt_components.append(
98
+ (
99
+ "human",
100
+ "I need to extract information from "
101
+ "the following text: ```\n{text}\n```\n",
102
+ ),
103
+ )
104
+ return ChatPromptTemplate.from_messages(prompt_components)
105
+
106
+
107
+ @chain
108
+ async def extraction_runnable(extraction_request: ExtractRequest) -> ExtractResponse:
109
+ """An end point to extract content from a given text object."""
110
+
111
+ prompt = _make_prompt_template(
112
+ extraction_request.examples,
113
+ "DDR"
114
+ )
115
+ model = ChatGroq(
116
+ temperature=0,
117
+ groq_api_key='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',
118
+ model_name="llama3-8b-8192"
119
+ )
120
+ runnable = (prompt | model.with_structured_output(schema=DAILYOPERATIONS)).with_config(
121
+ {"run_name": "extraction"}
122
+ )
123
+
124
+ return await runnable.ainvoke({"text": extraction_request.text})
125
+
126
+
127
+
128
+ def _make_extract_requests(input_dict: Dict[str, Any]) -> List[ExtractRequest]:
129
+ docs = input_dict.pop("text")
130
+ return [ExtractRequest(text=doc.page_content, **input_dict) for doc in docs]
131
+
132
+
133
+ async def extract_from_content(
134
+ content: str,
135
+ *,
136
+ text_splitter_kwargs: Optional[Dict[str, Any]] = None,
137
+ ) -> ExtractResponse:
138
+ """Extract from potentially long-form content."""
139
+ if text_splitter_kwargs is None:
140
+ text_splitter_kwargs = {
141
+ "separator": "\n\n",
142
+ "chunk_size": 2000,
143
+ "chunk_overlap": 50,
144
+ }
145
+ text_splitter = CharacterTextSplitter(**text_splitter_kwargs)
146
+ docs = text_splitter.create_documents([content])
147
+ #doc_contents = [doc.page_content for doc in docs]
148
+
149
+
150
+ db = get_mongo_client().Cygnus
151
+ part_collection = db["pdfparts"]
152
+ embedding_function = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
153
+ vector_store = MongoDBAtlasVectorSearch(
154
+ collection=part_collection,
155
+ embedding=embedding_function,
156
+ index_name="pdf_sections",
157
+ relevance_score_fn="cosine",
158
+ )
159
+ #for doc_content in doc_contents:
160
+ # document = {"page_content": doc_content}
161
+ vector_store.add_documents(docs)
162
+
163
+ retriever=vector_store.as_retriever()
164
+
165
+ runnable = (
166
+ {
167
+ "text": itemgetter("query") | retriever,
168
+ "schema": itemgetter("schema"),
169
+ "examples": lambda x: x.get("examples")
170
+ }
171
+ | RunnableLambda(_make_extract_requests)
172
+ | extraction_runnable.abatch
173
+ )
174
+ schema = DAILYOPERATIONS
175
+ examples = []
176
+ description = content # TODO: improve this
177
+ result = await runnable.ainvoke(
178
+ {
179
+ "query": description,
180
+ "schema": schema,
181
+ "examples": examples
182
+ }
183
+ )
184
+ return deduplicate(result)
185
+
186
+
187
+
188
+ async def extract_entire_document(
189
+ content: str,
190
+
191
+ ) -> ExtractResponse:
192
+ """Extract from entire document."""
193
+
194
+ #json_schema = DAILYREPORT
195
+ #examples = get_examples_from_extractor(extractor)
196
+ text_splitter = TokenTextSplitter(
197
+ chunk_size=8192,
198
+ chunk_overlap=0
199
+ )
200
+ texts = text_splitter.split_text(content)
201
+ extraction_requests = [
202
+ ExtractRequest(
203
+ text=text,
204
+ examples=[] #examples
205
+ )
206
+ for text in texts
207
+ ]
208
+
209
+ # Limit the number of chunks to process
210
+ if len(extraction_requests) > 1:
211
+ content_too_long = True
212
+ extraction_requests = extraction_requests[: 1]
213
+ else:
214
+ content_too_long = False
215
+
216
+ prompt = ChatPromptTemplate.from_messages(
217
+ [
218
+ (
219
+ "system",
220
+ "You are an expert extraction algorithm, you are specialized in Oil Drilling Reports,"
221
+ "Only extract relevant information entities mentioned in the following passage, together with their properties, "
222
+ "If you do not know the value of an attribute asked to extract, return 'null' for the attribute's value."
223
+
224
+ ),
225
+
226
+ ("user", "{text}"),
227
+ ]
228
+ )
229
+ model = ChatGroq(
230
+ temperature=0,
231
+ groq_api_key='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',
232
+ model_name="mixtral-8x7b-32768"
233
+ )
234
+
235
+ chain = prompt | model.with_structured_output(schema=DDRHEADER)
236
+ resultado = chain.invoke({"text":extraction_requests[0].text})
237
+ try:
238
+ resultado_json = resultado.model_dump_json()
239
+ except json.JSONDecodeError as e:
240
+ raise ValueError("Failed to decode JSON from the model output") from e
241
+
242
+ chain2 = prompt | model.with_structured_output(schema=DAILYOPERATIONS)
243
+ resultado2 = chain2.invoke({"text":extraction_requests[0].text})
244
+ try:
245
+ resultado_json2 = resultado2.model_dump_json()
246
+ except json.JSONDecodeError as e:
247
+ raise ValueError("Failed to decode JSON from the model output") from e
248
+
249
+ chain3 = prompt | model.with_structured_output(schema=FLUID)
250
+ resultado3 = chain3.invoke({"text":extraction_requests[0].text})
251
+ try:
252
+ resultado_json3 = resultado3.model_dump_json()
253
+ except json.JSONDecodeError as e:
254
+ raise ValueError("Failed to decode JSON from the model output") from e
255
+ return {
256
+ "data":{"ddrheader":resultado_json,
257
+ "dailyoper":resultado_json2,
258
+ "fluid": resultado_json3
259
+ } , # deduplicate(extract_responses)["data"],
260
+ "content_too_long": content_too_long
261
+ }
262
+
validators.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict
2
+
3
+ from fastapi import HTTPException
4
+ from jsonschema import exceptions
5
+ from jsonschema.validators import Draft202012Validator
6
+
7
+
8
+ def validate_json_schema(schema: Dict[str, Any]) -> None:
9
+ """Validate a JSON schema."""
10
+ try:
11
+ Draft202012Validator.check_schema(schema)
12
+ except exceptions.ValidationError as e:
13
+ raise HTTPException(
14
+ status_code=422, detail=f"Not a valid JSON schema: {e.message}"
15
+ )