vkumartr commited on
Commit
9734810
·
verified ·
1 Parent(s): 75d34db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -35
app.py CHANGED
@@ -142,32 +142,32 @@ Use the correct currency and amounts for each invoice field.
142
  For each line item, provide the Description, Tax Percentage, Tax Amount, and Amount.
143
  If certain values are missing or not applicable, leave them empty or set them as null where necessary.
144
  This JSON format will be used to store and manage invoices in a structured and uniform way. Please ensure only return JSON format. No extra content should not provide."""
145
- # try:
146
- # response = openai.ChatCompletion.create(
147
- # model="gpt-4o-mini",
148
- # messages=[
149
- # {"role": "system", "content": system_prompt},
150
- # {"role": "user", "content": f"{text}"}
151
- # ],
152
- # temperature=0.5,
153
- # max_tokens=16384
154
- # )
155
- # content = response.choices[0].message.content.strip()
156
- # print("Before content:", content)
157
- # cleaned_content = re.sub(r'^.*```json\n', '', content) # Remove '```json\n' at the beginning
158
- # cleaned_content = re.sub(r'\n```$', '', cleaned_content) # Remove '\n```' at the end
159
-
160
- # # Step 2: Parse the cleaned content as JSON
161
- # try:
162
- # parsed_content = json.loads(cleaned_content)
163
- # return parsed_content
164
- # except json.JSONDecodeError as e:
165
- # print("Error parsing JSON:", e)
166
- # # Optionally, print the cleaned content to debug
167
- # print("Cleaned content:", cleaned_content)
168
- # return None
169
- # except Exception as e:
170
- # return f"Error in summarization: {str(e)}"
171
 
172
  # Dependency to check API Key
173
  def verify_api_key(api_key: str = Header(...)):
@@ -179,13 +179,18 @@ def read_root():
179
  return {"message": "Welcome to the Invoice Summarization API!"}
180
 
181
  @app.get("/ocr/extraction")
182
- def ocr_from_s3(api_key: str = Depends(verify_api_key), file_key: str = Query(..., description="S3 file key for the file")):
 
 
 
 
 
183
  """
184
- Perform OCR on a file (PDF or Image) stored in S3 and summarize the text using GPT.
185
  """
186
  try:
187
  # Fetch file from S3
188
- file_data, content_type, document_type, entityrefkey = fetch_file_from_s3_file(file_key)
189
 
190
  extracted_text = []
191
  base64Data = base64.b64encode(file_data).decode('utf-8')
@@ -202,11 +207,7 @@ def ocr_from_s3(api_key: str = Depends(verify_api_key), file_key: str = Query(..
202
  # Process each page in the PDF
203
  for page_number in range(len(pdf_document)):
204
  page = pdf_document[page_number]
205
- # Render the page as an image
206
- pix = page.get_pixmap()
207
- image = Image.open(io.BytesIO(pix.tobytes("png"))).convert("RGB")
208
- # Convert Pillow image to NumPy array
209
- image_np = np.array(image)
210
  pdf_document.close()
211
  base64DataResp = f"data:application/pdf;base64,{base64Data}"
212
  else:
@@ -219,10 +220,10 @@ def ocr_from_s3(api_key: str = Depends(verify_api_key), file_key: str = Query(..
219
  summary = summarize_text(full_text)
220
 
221
  return {
222
- "entityrefkey": entityrefkey,
223
  "file_key": file_key,
224
  "file_type": content_type,
225
  "document_type": document_type,
 
226
  "base64DataResp": base64DataResp,
227
  "extracted_text": full_text,
228
  "summary": summary
 
142
  For each line item, provide the Description, Tax Percentage, Tax Amount, and Amount.
143
  If certain values are missing or not applicable, leave them empty or set them as null where necessary.
144
  This JSON format will be used to store and manage invoices in a structured and uniform way. Please ensure only return JSON format. No extra content should not provide."""
145
+ try:
146
+ response = openai.ChatCompletion.create(
147
+ model="gpt-4o-mini",
148
+ messages=[
149
+ {"role": "system", "content": system_prompt},
150
+ {"role": "user", "content": f"{text}"}
151
+ ],
152
+ temperature=0.5,
153
+ max_tokens=16384
154
+ )
155
+ content = response.choices[0].message.content.strip()
156
+ print("Before content:", content)
157
+ cleaned_content = re.sub(r'^.*```json\n', '', content) # Remove '```json\n' at the beginning
158
+ cleaned_content = re.sub(r'\n```$', '', cleaned_content) # Remove '\n```' at the end
159
+
160
+ # Step 2: Parse the cleaned content as JSON
161
+ try:
162
+ parsed_content = json.loads(cleaned_content)
163
+ return parsed_content
164
+ except json.JSONDecodeError as e:
165
+ print("Error parsing JSON:", e)
166
+ # Optionally, print the cleaned content to debug
167
+ print("Cleaned content:", cleaned_content)
168
+ return None
169
+ except Exception as e:
170
+ return f"Error in summarization: {str(e)}"
171
 
172
  # Dependency to check API Key
173
  def verify_api_key(api_key: str = Header(...)):
 
179
  return {"message": "Welcome to the Invoice Summarization API!"}
180
 
181
  @app.get("/ocr/extraction")
182
+ def ocr_from_s3(
183
+ api_key: str = Depends(verify_api_key),
184
+ file_key: str = Query(..., description="S3 file key for the file"),
185
+ document_type: str = Query(..., description="Type of document"),
186
+ entity_ref_key: str = Query(..., description="Entity Reference Key")
187
+ ):
188
  """
189
+ (PDF or Image) stored in S3 and summarize the text using GPT.
190
  """
191
  try:
192
  # Fetch file from S3
193
+ file_data, content_type = fetch_file_from_s3_file(file_key)
194
 
195
  extracted_text = []
196
  base64Data = base64.b64encode(file_data).decode('utf-8')
 
207
  # Process each page in the PDF
208
  for page_number in range(len(pdf_document)):
209
  page = pdf_document[page_number]
210
+ extracted_text.append(page.get_text("text")) # Extract text from PDF
 
 
 
 
211
  pdf_document.close()
212
  base64DataResp = f"data:application/pdf;base64,{base64Data}"
213
  else:
 
220
  summary = summarize_text(full_text)
221
 
222
  return {
 
223
  "file_key": file_key,
224
  "file_type": content_type,
225
  "document_type": document_type,
226
+ "entity_ref_key": entity_ref_key,
227
  "base64DataResp": base64DataResp,
228
  "extracted_text": full_text,
229
  "summary": summary