Sayed121 commited on
Commit
8b0c83a
·
verified ·
1 Parent(s): f1dc3c0

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile.txt +63 -0
  2. app-3.py +251 -0
  3. requirements-2.txt +3 -0
Dockerfile.txt ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+
4
+ # Start with CUDA base image
5
+ FROM nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04
6
+
7
+ # Avoid prompts from apt
8
+ ENV DEBIAN_FRONTEND=noninteractive
9
+
10
+ # Install system dependencies
11
+ RUN apt-get update && apt-get install -y \
12
+ software-properties-common \
13
+ && add-apt-repository ppa:deadsnakes/ppa \
14
+ && apt-get update \
15
+ && apt-get install -y \
16
+ python3.9 \
17
+ python3.9-distutils \
18
+ python3.9-dev \
19
+ python3-pip \
20
+ build-essential \
21
+ wget \
22
+ ffmpeg \
23
+ libsm6 \
24
+ libxext6 \
25
+ libgl1-mesa-glx \
26
+ && rm -rf /var/lib/apt/lists/*
27
+
28
+ # Set Python 3.9 as the default python version
29
+ RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1
30
+ RUN update-alternatives --set python3 /usr/bin/python3.9
31
+
32
+ # Install pip for Python 3.9
33
+ RUN wget https://bootstrap.pypa.io/get-pip.py && \
34
+ python3 get-pip.py && \
35
+ rm get-pip.py
36
+
37
+ # Set up a new user named "user" with user ID 1000
38
+ RUN useradd -m -u 1000 user
39
+
40
+ # Switch to the "user" user
41
+ USER user
42
+
43
+ # Set home to the user's home directory
44
+ ENV HOME=/home/user \
45
+ PATH=/home/user/.local/bin:$PATH
46
+
47
+ # Set the working directory to the user's home directory
48
+ WORKDIR $HOME/app
49
+
50
+ # Copy the requirements file with correct ownership
51
+ COPY --chown=user requirements.txt .
52
+
53
+ # Install any needed packages specified in requirements.txt
54
+ RUN pip3 install --no-cache-dir --user -r requirements.txt
55
+
56
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
57
+ COPY --chown=user . $HOME/app
58
+
59
+ # Make port 7860 available to the world outside this container
60
+ EXPOSE 7860
61
+
62
+ # Run app.py when the container launches
63
+ CMD ["python3", "-m", "streamlit", "run", "app.py", "--server.port=7860", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false"]
app-3.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import streamlit as st
2
+ # from doctr.io import DocumentFile
3
+ # from doctr.models import ocr_predictor
4
+ # import json
5
+ # from doctr.models import ocr_predictor
6
+ # import openai
7
+ # import re
8
+
9
+ # import os
10
+ # model = ocr_predictor(det_arch='db_resnet50', reco_arch='crnn_vgg16_bn', pretrained=True)
11
+
12
+ # # import the OpenAI Python library for calling the OpenAI API
13
+ # from openai import OpenAI
14
+ # import os
15
+
16
+ # # Function to extract text from PDF using OCR
17
+ # def extract_text_from_pdf(pdf_file):
18
+ # doc = DocumentFile.from_pdf(pdf_file)
19
+ # result = model(doc) # Assuming 'model' is your OCR predictor
20
+ # return result
21
+
22
+ # # Function to clean extracted text
23
+ # def clean_extracted_text(result):
24
+ # extracted_text = []
25
+ # for page in result.pages:
26
+ # for block in page.blocks:
27
+ # for line in block.lines:
28
+ # line_text = ' '.join(word.value for word in line.words)
29
+ # extracted_text.append(line_text)
30
+ # return '\n'.join(extracted_text)
31
+
32
+ # # Function to extract critical information using a language model
33
+ # def extract_critical_information(text):
34
+ # # Here you would integrate your OpenAI language model (LLM) or similar
35
+ # # For demonstration, let's assume it returns a mock JSON
36
+ # MODEL = "gpt-3.5-turbo"
37
+ # #response = client.chat.completions.create(
38
+ # response = client.chat.completions.create(
39
+ # model=MODEL,
40
+ # messages=[
41
+ # {"role": "system", "content": "You are a property deed expert for the US."},
42
+ # {"role": "user", "content": f"Given the raw information extracted using OCR from a PDF, you should extract the most important parts of the deed such as the owner's name, property number, address, and any other important factors. The OCR results are stored in the variable `result`.\n\nOCR Result:\n{text}\n\nPlease provide the extracted information in JSON format.\n\nExample JSON output:\n{{\n \"owner_name\": \"\",\n \"property_address\": \"\",\n \"legal_description\": \"\",\n \"grantor_name\": \"\",\n \"grantee_name\": \"\",\n \"deed_type\": \"\",\n \"liens_and_encumbrances\": \"\",\n \"signatures\": \"\",\n \"notarization_details\": \"\",\n \"recording_information\": \"\",\n \"consideration\": \"\",\n \"habendum_clause\": \"\",\n \"warranty_clauses\": \"\",\n \"tax_information\": \"\",\n \"title_insurance_details\": \"\"\n}}Extracted Information JSON:, Warning: Do not make up fake information"}],
43
+ # temperature=0,
44
+ # )
45
+ # extracted_info= (response.choices[0].message.content)
46
+ # return extracted_info
47
+
48
+
49
+ # def clean_and_convert_to_json(input_string):
50
+ # # Remove the markdown code block indicators and any leading/trailing whitespace
51
+ # cleaned_string = input_string.strip()
52
+ # cleaned_string = re.sub(r'^```json\s*|\s*```$', '', cleaned_string, flags=re.MULTILINE)
53
+
54
+ # # Remove any non-printable characters except newlines
55
+ # cleaned_string = ''.join(char for char in cleaned_string if char.isprintable() or char in '\n\r')
56
+
57
+ # # Ensure the string starts with { and ends with }
58
+ # cleaned_string = cleaned_string.strip()
59
+ # if not cleaned_string.startswith('{'):
60
+ # cleaned_string = '{' + cleaned_string
61
+ # if not cleaned_string.endswith('}'):
62
+ # cleaned_string = cleaned_string + '}'
63
+
64
+ # try:
65
+ # # Parse the string as JSON
66
+ # data = json.loads(cleaned_string)
67
+ # # Convert back to a JSON string with proper formatting
68
+ # cleaned_json = json.dumps(data, indent=2)
69
+ # return cleaned_json
70
+ # except json.JSONDecodeError as e:
71
+ # print(f"JSON Decode Error: {e}")
72
+ # print(f"Problematic string:\n{cleaned_string}")
73
+ # return None
74
+
75
+
76
+ # def main():
77
+ # st.title("Property Deed Information Extraction App")
78
+
79
+ # uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
80
+
81
+ # if uploaded_file is not None:
82
+ # st.write("File uploaded successfully!")
83
+
84
+ # # Process the uploaded PDF file
85
+ # result = extract_text_from_pdf(uploaded_file)
86
+ # cleaned_text = clean_extracted_text(result)
87
+ # extracted_info = extract_critical_information(cleaned_text)
88
+ # extracted_info = clean_and_convert_to_json(extracted_info)
89
+
90
+ # # Parse the JSON result
91
+ # try:
92
+ # extracted_info_json = json.loads(extracted_info)
93
+ # except json.JSONDecodeError as e:
94
+ # st.error(f"An error occurred while parsing the JSON response: {e}")
95
+ # extracted_info_json = {}
96
+
97
+ # # Display extracted information
98
+ # st.subheader("Extracted Information:")
99
+ # st.text_input("Owner Name", value=extracted_info_json.get("owner_name", ""))
100
+ # st.text_input("Property Address", value=extracted_info_json.get("property_address", ""))
101
+ # st.text_input("Legal Description", value=extracted_info_json.get("legal_description", ""))
102
+ # st.text_input("Grantor Name", value=extracted_info_json.get("grantor_name", ""))
103
+ # st.text_input("Grantee Name", value=extracted_info_json.get("grantee_name", ""))
104
+ # st.text_input("Deed Type", value=extracted_info_json.get("deed_type", ""))
105
+ # st.text_input("Liens and Encumbrances", value=extracted_info_json.get("liens_and_encumbrances", ""))
106
+ # st.text_input("Signatures", value=extracted_info_json.get("signatures", ""))
107
+ # st.text_input("Notarization Details", value=extracted_info_json.get("notarization_details", ""))
108
+ # st.text_input("Recording Information", value=extracted_info_json.get("recording_information", ""))
109
+ # st.text_input("Consideration", value=extracted_info_json.get("consideration", ""))
110
+ # st.text_input("Habendum Clause", value=extracted_info_json.get("habendum_clause", ""))
111
+ # st.text_input("Warranty Clauses", value=extracted_info_json.get("warranty_clauses", ""))
112
+ # st.text_input("Tax Information", value=extracted_info_json.get("tax_information", ""))
113
+ # st.text_input("Title Insurance Details", value=extracted_info_json.get("title_insurance_details", ""))
114
+
115
+ # if __name__ == "__main__":
116
+ # main()
117
+
118
+ import streamlit as st
119
+ from doctr.io import DocumentFile
120
+ from doctr.models import ocr_predictor
121
+ import json
122
+ import openai
123
+ import re
124
+ import os
125
+ from openai import OpenAI
126
+ model = ocr_predictor(det_arch='db_resnet50', reco_arch='crnn_vgg16_bn', pretrained=True).to('cpu')
127
+
128
+ # Set up OpenAI client
129
+
130
+
131
+ client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "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"))
132
+
133
+ # if not api_key:
134
+ # st.error("API Key is missing. Please set the OPENAI_API_KEY environment variable.")
135
+ # else:
136
+ # client = openai.OpenAI(api_key=api_key)
137
+ # st.write(f"API Key Loaded: {api_key[:4]}...")
138
+
139
+ # Function to extract text from PDF using OCR
140
+ def extract_text_from_pdf(pdf_file):
141
+ doc = DocumentFile.from_pdf(pdf_file)
142
+ result = model(doc) # Assuming 'model' is your OCR predictor
143
+ return result
144
+
145
+ # Function to clean extracted text
146
+ def clean_extracted_text(result):
147
+ extracted_text = []
148
+ for page in result.pages:
149
+ for block in page.blocks:
150
+ for line in block.lines:
151
+ line_text = ' '.join(word.value for word in line.words)
152
+ extracted_text.append(line_text)
153
+ return '\n'.join(extracted_text)
154
+
155
+ # Function to extract critical information using a language model
156
+ # def extract_critical_information(text):
157
+ # MODEL = "gpt-3.5-turbo"
158
+ # try:
159
+ # response = client.ChatCompletion.create(
160
+ # model=MODEL,
161
+ # messages=[
162
+ # {"role": "system", "content": "You are a property deed expert for the US."},
163
+ # {"role": "user", "content": f"Given the raw information extracted using OCR from a PDF, you should extract the most important parts of the deed such as the owner's name, property number, address, and any other important factors. The OCR results are stored in the variable `result`.\n\nOCR Result:\n{text}\n\nPlease provide the extracted information in JSON format.\n\nExample JSON output:\n{{\n \"owner_name\": \"\",\n \"property_address\": \"\",\n \"legal_description\": \"\",\n \"grantor_name\": \"\",\n \"grantee_name\": \"\",\n \"deed_type\": \"\",\n \"liens_and_encumbrances\": \"\",\n \"signatures\": \"\",\n \"notarization_details\": \"\",\n \"recording_information\": \"\",\n \"consideration\": \"\",\n \"habendum_clause\": \"\",\n \"warranty_clauses\": \"\",\n \"tax_information\": \"\",\n \"title_insurance_details\": \"\"\n}}Extracted Information JSON:, Warning: Do not make up fake information"}],
164
+ # temperature=0,
165
+ # )
166
+ # extracted_info = response['choices'][0]['message']['content']
167
+ # return extracted_info
168
+ # except openai.error.OpenAIError as e:
169
+ # st.error(f"OpenAI API Error: {e}")
170
+ # return None
171
+
172
+ def extract_critical_information(text):
173
+ # Here you would integrate your OpenAI language model (LLM) or similar
174
+ # For demonstration, let's assume it returns a mock JSON
175
+ MODEL = "gpt-4o-mini"
176
+ #response = client.chat.completions.create(
177
+ response = client.chat.completions.create(
178
+ model=MODEL,
179
+ messages=[
180
+ {"role": "system", "content": "You are a property deed expert for the US."},
181
+ {"role": "user", "content": f"Given the raw information extracted using OCR from a PDF, you should extract the most important parts of the deed such as the owner's name, property number, address, and any other important factors. The OCR results are stored in the variable `result`.\n\nOCR Result:\n{text}\n\nPlease provide the extracted information in JSON format.\n\nExample JSON output:\n{{\n \"owner_name\": \"\",\n \"property_address\": \"\",\n \"legal_description\": \"\",\n \"grantor_name\": \"\",\n \"grantee_name\": \"\",\n \"deed_type\": \"\",\n \"liens_and_encumbrances\": \"\",\n \"signatures\": \"\",\n \"notarization_details\": \"\",\n \"recording_information\": \"\",\n \"consideration\": \"\",\n \"habendum_clause\": \"\",\n \"warranty_clauses\": \"\",\n \"tax_information\": \"\",\n \"title_insurance_details\": \"\"\n}}Extracted Information JSON:, Warning: Do not make up fake information"}],
182
+ temperature=0,
183
+ )
184
+ extracted_info= (response.choices[0].message.content)
185
+ return extracted_info
186
+
187
+
188
+ # Function to clean and convert text to JSON
189
+ def clean_and_convert_to_json(input_string):
190
+ cleaned_string = input_string.strip()
191
+ cleaned_string = re.sub(r'^```json\s*|\s*```$', '', cleaned_string, flags=re.MULTILINE)
192
+ cleaned_string = ''.join(char for char in cleaned_string if char.isprintable() or char in '\n\r')
193
+ cleaned_string = cleaned_string.strip()
194
+ if not cleaned_string.startswith('{'):
195
+ cleaned_string = '{' + cleaned_string
196
+ if not cleaned_string.endswith('}'):
197
+ cleaned_string = cleaned_string + '}'
198
+ try:
199
+ data = json.loads(cleaned_string)
200
+ cleaned_json = json.dumps(data, indent=2)
201
+ return cleaned_json
202
+ except json.JSONDecodeError as e:
203
+ st.error(f"JSON Decode Error: {e}")
204
+ return None
205
+
206
+ # Streamlit app
207
+ def main():
208
+ st.title("Property Deed Information Extraction App")
209
+
210
+ uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
211
+
212
+ if uploaded_file is not None:
213
+ st.write("File uploaded successfully!")
214
+
215
+ result = extract_text_from_pdf(uploaded_file)
216
+ cleaned_text = clean_extracted_text(result)
217
+ extracted_info = extract_critical_information(cleaned_text)
218
+ if extracted_info:
219
+ extracted_info = clean_and_convert_to_json(extracted_info)
220
+ if extracted_info:
221
+ try:
222
+ extracted_info_json = json.loads(extracted_info)
223
+ except json.JSONDecodeError as e:
224
+ st.error(f"An error occurred while parsing the JSON response: {e}")
225
+ extracted_info_json = {}
226
+
227
+ st.subheader("Extracted Information:")
228
+ st.text_input("Owner Name", value=extracted_info_json.get("owner_name", ""))
229
+ st.text_input("Property Address", value=extracted_info_json.get("property_address", ""))
230
+ st.text_input("Legal Description", value=extracted_info_json.get("legal_description", ""))
231
+ st.text_input("Grantor Name", value=extracted_info_json.get("grantor_name", ""))
232
+ st.text_input("Grantee Name", value=extracted_info_json.get("grantee_name", ""))
233
+ st.text_input("Deed Type", value=extracted_info_json.get("deed_type", ""))
234
+ st.text_input("Liens and Encumbrances", value=extracted_info_json.get("liens_and_encumbrances", ""))
235
+ st.text_input("Signatures", value=extracted_info_json.get("signatures", ""))
236
+ st.text_input("Notarization Details", value=extracted_info_json.get("notarization_details", ""))
237
+ st.text_input("Recording Information", value=extracted_info_json.get("recording_information", ""))
238
+ st.text_input("Consideration", value=extracted_info_json.get("consideration", ""))
239
+ st.text_input("Habendum Clause", value=extracted_info_json.get("habendum_clause", ""))
240
+ st.text_input("Warranty Clauses", value=extracted_info_json.get("warranty_clauses", ""))
241
+ st.text_input("Tax Information", value=extracted_info_json.get("tax_information", ""))
242
+ st.text_input("Title Insurance Details", value=extracted_info_json.get("title_insurance_details", ""))
243
+ else:
244
+ st.error("Failed to clean and convert extracted information to JSON.")
245
+ else:
246
+ st.error("Failed to extract critical information from text.")
247
+
248
+ if __name__ == "__main__":
249
+ main()
250
+
251
+
requirements-2.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ streamlit>=1.0.0
2
+ openai
3
+ python-doctr[torch]