jzou19950715 commited on
Commit
d3c9017
·
verified ·
1 Parent(s): 50e3198

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -21
app.py CHANGED
@@ -145,6 +145,7 @@ class InformationExtractor:
145
 
146
  for attempt in range(retries):
147
  try:
 
148
  with openai.ChatCompletion.create(
149
  model="gpt-4o-mini", # or "gpt-4" or any other available model
150
  messages=[
@@ -211,7 +212,41 @@ class InformationExtractor:
211
  analysis = json.loads(raw_content)
212
  extracted_items = []
213
 
214
- for item in analysis.get("extracted_
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  def process_message(self, message: str, api_key: str) -> Dict[str, Any]:
216
  """
217
  Process a user message:
@@ -232,7 +267,7 @@ class InformationExtractor:
232
  # Always return a dictionary so that the UI can parse it
233
  try:
234
  if not message.strip():
235
- # Return a 5-element tuple anyway (the UI needs 5 outputs)
236
  return {
237
  "response": "Please enter a message.",
238
  "extracted_info": [],
@@ -278,7 +313,11 @@ class InformationExtractor:
278
  "categories_covered": self.state.categories_covered,
279
  "current_focus": self.state.current_focus
280
  },
281
- "analysis_text": "Successfully extracted new information." if new_info else "No new information extracted.",
 
 
 
 
282
  "history_message": f"Added user message '{message}' and assistant response to history."
283
  }
284
 
@@ -474,8 +513,7 @@ def create_gradio_interface() -> gr.Blocks:
474
  """
475
  result = extractor.process_message(user_input, key)
476
 
477
- # Update chat history
478
- # We will append the user message + assistant response
479
  history.append({"role": "user", "content": user_input})
480
  history.append({"role": "assistant", "content": result["response"]})
481
 
@@ -514,19 +552,15 @@ def create_gradio_interface() -> gr.Blocks:
514
 
515
  # Flatten everything for a final analysis string
516
  flat_items = []
517
- for cat_items in content["extracted_information"].values():
518
- flat_items.extend(cat_items)
519
-
520
- final_analysis = format_extraction_summary([
521
- {
522
- "text": i["text"],
523
- "confidence": i["confidence"],
524
- "category": cat
525
- }
526
- for cat in content["extracted_information"].keys()
527
- for i in content["extracted_information"][cat]
528
- ])
529
-
530
  return filename, content_preview, "Report generated successfully!", final_analysis
531
  else:
532
  return None, {"error": gen_result["error"]}, "Error generating report.", "No analysis."
@@ -573,9 +607,14 @@ def create_gradio_interface() -> gr.Blocks:
573
  clear.click(
574
  fn=clear_interface,
575
  outputs=[
576
- chatbot, progress, categories_covered,
577
- current_focus, extracted_info, file_output,
578
- analysis_text, msg
 
 
 
 
 
579
  ]
580
  )
581
 
 
145
 
146
  for attempt in range(retries):
147
  try:
148
+ # We use a context manager for the create call
149
  with openai.ChatCompletion.create(
150
  model="gpt-4o-mini", # or "gpt-4" or any other available model
151
  messages=[
 
212
  analysis = json.loads(raw_content)
213
  extracted_items = []
214
 
215
+ # This line must NOT be truncated or it will cause a syntax error
216
+ for item in analysis.get("extracted_items", []):
217
+ new_info = ExtractedInfo(
218
+ text=item.get("text", ""),
219
+ category=item.get("category", "misc"),
220
+ confidence=float(item.get("confidence", 0.0)),
221
+ metadata=item.get("metadata", {})
222
+ )
223
+ extracted_items.append(new_info)
224
+
225
+ return extracted_items
226
+
227
+ except json.JSONDecodeError as e:
228
+ logger.error(f"Error parsing extraction response: {str(e)}")
229
+ return []
230
+ except Exception as e:
231
+ logger.error(f"Error during information extraction: {str(e)}")
232
+ return []
233
+
234
+ def _update_completion_status(self) -> None:
235
+ """
236
+ Update completion status based on categories covered and confidence levels.
237
+ """
238
+ total_categories = len(self.extraction_categories)
239
+ covered_categories = len(self.state.categories_covered)
240
+ base_completion = (covered_categories / total_categories) * 100 if total_categories > 0 else 0
241
+
242
+ if self.state.extracted_items:
243
+ avg_confidence = sum(item.confidence for item in self.state.extracted_items) / len(self.state.extracted_items)
244
+ adjusted_completion = base_completion * avg_confidence
245
+ else:
246
+ adjusted_completion = 0.0
247
+
248
+ # Cap at 100%
249
+ self.state.completion_percentage = min(adjusted_completion, 100.0)
250
  def process_message(self, message: str, api_key: str) -> Dict[str, Any]:
251
  """
252
  Process a user message:
 
267
  # Always return a dictionary so that the UI can parse it
268
  try:
269
  if not message.strip():
270
+ # Return placeholders if message is empty
271
  return {
272
  "response": "Please enter a message.",
273
  "extracted_info": [],
 
313
  "categories_covered": self.state.categories_covered,
314
  "current_focus": self.state.current_focus
315
  },
316
+ "analysis_text": (
317
+ "Successfully extracted new information."
318
+ if new_info else
319
+ "No new information extracted."
320
+ ),
321
  "history_message": f"Added user message '{message}' and assistant response to history."
322
  }
323
 
 
513
  """
514
  result = extractor.process_message(user_input, key)
515
 
516
+ # Update chat history: append the user message + assistant response
 
517
  history.append({"role": "user", "content": user_input})
518
  history.append({"role": "assistant", "content": result["response"]})
519
 
 
552
 
553
  # Flatten everything for a final analysis string
554
  flat_items = []
555
+ for cat_key, cat_items in content["extracted_information"].items():
556
+ for item_data in cat_items:
557
+ flat_items.append({
558
+ "category": cat_key,
559
+ "confidence": item_data["confidence"],
560
+ "text": item_data["text"]
561
+ })
562
+
563
+ final_analysis = format_extraction_summary(flat_items)
 
 
 
 
564
  return filename, content_preview, "Report generated successfully!", final_analysis
565
  else:
566
  return None, {"error": gen_result["error"]}, "Error generating report.", "No analysis."
 
607
  clear.click(
608
  fn=clear_interface,
609
  outputs=[
610
+ chatbot,
611
+ progress,
612
+ categories_covered,
613
+ current_focus,
614
+ extracted_info,
615
+ file_output,
616
+ analysis_text,
617
+ msg
618
  ]
619
  )
620