vikramvasudevan commited on
Commit
9e2bd6f
·
verified ·
1 Parent(s): 5c03fad

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. graph.py +7 -2
  2. home.py +3 -1
  3. modules/db.py +1 -0
  4. modules/models.py +5 -3
  5. ui.py +110 -59
graph.py CHANGED
@@ -227,8 +227,13 @@ async def fn_standardize_current_report_node(state: SheamiState):
227
  )
228
  # logger.info("Parsed text using OCR: %s", report.report_contents)
229
  run_stats_details = await get_db().get_run_stats_by_id(id=state["run_id"])
230
- run_stats_details["source_file_contents"][state["current_index"]] = report.report_contents.replace("\\n","\n")
231
- await get_db().update_run_stats(run_id=state["run_id"], source_file_contents=run_stats_details["source_file_contents"])
 
 
 
 
 
232
  result = await call_llm(report=report, ocr=True)
233
  if not result.lab_results:
234
  state["messages"].append(
 
227
  )
228
  # logger.info("Parsed text using OCR: %s", report.report_contents)
229
  run_stats_details = await get_db().get_run_stats_by_id(id=state["run_id"])
230
+ run_stats_details["source_file_contents"][state["current_index"]] = (
231
+ report.report_contents.replace("\\n", "\n")
232
+ )
233
+ await get_db().update_run_stats(
234
+ run_id=state["run_id"],
235
+ source_file_contents=run_stats_details["source_file_contents"],
236
+ )
237
  result = await call_llm(report=report, ocr=True)
238
  if not result.lab_results:
239
  state["messages"].append(
home.py CHANGED
@@ -76,6 +76,8 @@ def get_status_icon(status):
76
  status = "✅"
77
  if status == "inprogress":
78
  status = "⌛"
 
 
79
  return status
80
 
81
 
@@ -616,7 +618,7 @@ def build_home_page():
616
  inputs=[report_id_in],
617
  outputs=download_final_report_btn,
618
  )
619
- with gr.Tab("⬆ Upload History"):
620
  gr.Markdown("Click on any row to view more details")
621
  with Modal(visible=False) as run_stats_modal:
622
  gr.Markdown("## Run Stats Details")
 
76
  status = "✅"
77
  if status == "inprogress":
78
  status = "⌛"
79
+ if status == "failed":
80
+ status = "❌"
81
  return status
82
 
83
 
 
618
  inputs=[report_id_in],
619
  outputs=download_final_report_btn,
620
  )
621
+ with gr.Tab("⬆ Upload History"):
622
  gr.Markdown("Click on any row to view more details")
623
  with Modal(visible=False) as run_stats_modal:
624
  gr.Markdown("## Run Stats Details")
modules/db.py CHANGED
@@ -322,6 +322,7 @@ class SheamiDB:
322
  "source_file_names",
323
  "source_file_contents",
324
  "status",
 
325
  ]:
326
  update_fields[key] = value
327
 
 
322
  "source_file_names",
323
  "source_file_contents",
324
  "status",
325
+ "message"
326
  ]:
327
  update_fields[key] = value
328
 
modules/models.py CHANGED
@@ -57,7 +57,7 @@ class StandardizedReport(BaseModel):
57
 
58
  @dataclass
59
  class HealthReport:
60
- report_file_name_with_path : str
61
  report_file_name: str
62
  report_contents: str
63
 
@@ -78,10 +78,12 @@ class SheamiMilestone:
78
 
79
  @property
80
  def status_icon(self) -> str:
81
- if self.status == "started":
82
  return "⏳"
83
  elif self.status == "completed":
84
  return "✅"
 
 
85
  else:
86
  return self.status
87
 
@@ -104,4 +106,4 @@ class SheamiState(TypedDict):
104
  overall_units_processed: int
105
  overall_units_total: int
106
  milestones: list[SheamiMilestone]
107
- interpretation_html : str
 
57
 
58
  @dataclass
59
  class HealthReport:
60
+ report_file_name_with_path: str
61
  report_file_name: str
62
  report_contents: str
63
 
 
78
 
79
  @property
80
  def status_icon(self) -> str:
81
+ if self.status == "started" or self.status == "inprogress":
82
  return "⏳"
83
  elif self.status == "completed":
84
  return "✅"
85
+ elif self.status == "failed":
86
+ return "❌"
87
  else:
88
  return self.status
89
 
 
106
  overall_units_processed: int
107
  overall_units_total: int
108
  milestones: list[SheamiMilestone]
109
+ interpretation_html: str
ui.py CHANGED
@@ -1,10 +1,13 @@
1
  import asyncio
 
 
2
  from typing import TypedDict
3
  import gradio as gr
4
  import uuid
5
  import os
6
  import pandas as pd
7
  from tqdm.auto import tqdm
 
8
  from config import SheamiConfig
9
  from graph import create_graph
10
  from modules.models import HealthReport, SheamiMilestone, SheamiState
@@ -54,53 +57,44 @@ async def process_reports(user_email: str, patient_id: str, files: list):
54
  # Streaming node progress
55
  buffer = ""
56
  final_state = state
57
- async for msg_packet in workflow.astream(
58
- state, config=config, stream_mode="values"
59
- ):
60
- final_state = msg_packet
61
- # try:
62
- # print("units_processed = ", msg_packet["units_processed"])
63
- # except Exception as e:
64
- # print("units_processed not available in: ", msg_packet.keys() , e)
65
- units_processed = (
66
- msg_packet["units_processed"] if "units_processed" in msg_packet else 0
67
- )
68
- units_total = msg_packet["units_total"] if "units_total" in msg_packet else 6
69
- process_desc = (
70
- msg_packet["process_desc"]
71
- if "process_desc" in msg_packet
72
- else "Working on it ..."
73
- )
 
 
 
74
 
75
- overall_units_processed = (
76
- msg_packet["overall_units_processed"]
77
- if "overall_units_processed" in msg_packet
78
- else 0
79
- )
80
- overall_units_total = (
81
- msg_packet["overall_units_total"]
82
- if "overall_units_total" in msg_packet
83
- else 0
84
- )
85
 
86
- if "messages" in msg_packet and msg_packet["messages"]:
87
- # Either show all so far, or just latest message
88
- all_but_last = msg_packet["messages"][:-1]
89
- last_message = msg_packet["messages"][-1]
90
- buffer = "\n".join(all_but_last)
91
 
92
- yield construct_process_message(
93
- message=buffer,
94
- current_step=process_desc,
95
- units_processed=units_processed,
96
- units_total=units_total,
97
- overall_units_processed=overall_units_processed,
98
- overall_units_total=overall_units_total,
99
- milestones=msg_packet["milestones"],
100
- )
101
- buffer += "\n"
102
- for c in last_message:
103
- buffer += c
104
  yield construct_process_message(
105
  message=buffer,
106
  current_step=process_desc,
@@ -110,21 +104,66 @@ async def process_reports(user_email: str, patient_id: str, files: list):
110
  overall_units_total=overall_units_total,
111
  milestones=msg_packet["milestones"],
112
  )
113
- await asyncio.sleep(0.005)
114
- await asyncio.sleep(0.1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
- buffer += (
117
- "\n\n"
118
- f"✅ Processed {len(files)} reports.\n"
119
- "Please download the output file from below within 5 min."
120
- )
121
- yield construct_process_message(
122
- message=buffer,
123
- final_output=gr.update(value=final_state["pdf_path"], visible=True),
124
- milestones=final_state["milestones"],
125
- reports_output=msg_packet["standardized_reports"],
126
- trends_output=msg_packet["trends_json"],
127
- )
128
 
129
 
130
  def generate_milestones_data(
@@ -177,6 +216,7 @@ def construct_process_message(
177
  milestones: list[SheamiMilestone] = [],
178
  reports_output=None,
179
  trends_output=None,
 
180
  ):
181
  try:
182
  if units_total > 0:
@@ -200,6 +240,15 @@ def construct_process_message(
200
  else f"<div class='transparent_div'>{message}</div>"
201
  )
202
 
 
 
 
 
 
 
 
 
 
203
  return (
204
  formatted_message, # logs_textbox
205
  disable_component() if not final_output else enable_component(), # run_btn
@@ -212,6 +261,7 @@ def construct_process_message(
212
  *render_patient_state(
213
  reports_output, trends_output
214
  ), # reports_output, trends_output
 
215
  )
216
 
217
 
@@ -422,7 +472,7 @@ def get_gradio_block(
422
  with gr.Tab(
423
  "Report Download", id="my_final_report_container"
424
  ) as final_report_container:
425
- gr.Markdown("# ✅Your health trends report is ready!")
426
  with gr.Row(equal_height=False):
427
  pdf_download = gr.DownloadButton(
428
  label="Download 📊",
@@ -489,6 +539,7 @@ def get_gradio_block(
489
  milestone_df,
490
  reports_output,
491
  trends_output,
 
492
  ],
493
  queue=True,
494
  ).then(
 
1
  import asyncio
2
+ from datetime import datetime
3
+ import traceback
4
  from typing import TypedDict
5
  import gradio as gr
6
  import uuid
7
  import os
8
  import pandas as pd
9
  from tqdm.auto import tqdm
10
+ from common import get_db
11
  from config import SheamiConfig
12
  from graph import create_graph
13
  from modules.models import HealthReport, SheamiMilestone, SheamiState
 
57
  # Streaming node progress
58
  buffer = ""
59
  final_state = state
60
+ try:
61
+ async for msg_packet in workflow.astream(
62
+ state, config=config, stream_mode="values"
63
+ ):
64
+ final_state = msg_packet
65
+ # try:
66
+ # print("units_processed = ", msg_packet["units_processed"])
67
+ # except Exception as e:
68
+ # print("units_processed not available in: ", msg_packet.keys() , e)
69
+ units_processed = (
70
+ msg_packet["units_processed"] if "units_processed" in msg_packet else 0
71
+ )
72
+ units_total = (
73
+ msg_packet["units_total"] if "units_total" in msg_packet else 6
74
+ )
75
+ process_desc = (
76
+ msg_packet["process_desc"]
77
+ if "process_desc" in msg_packet
78
+ else "Working on it ..."
79
+ )
80
 
81
+ overall_units_processed = (
82
+ msg_packet["overall_units_processed"]
83
+ if "overall_units_processed" in msg_packet
84
+ else 0
85
+ )
86
+ overall_units_total = (
87
+ msg_packet["overall_units_total"]
88
+ if "overall_units_total" in msg_packet
89
+ else 0
90
+ )
91
 
92
+ if "messages" in msg_packet and msg_packet["messages"]:
93
+ # Either show all so far, or just latest message
94
+ all_but_last = msg_packet["messages"][:-1]
95
+ last_message = msg_packet["messages"][-1]
96
+ buffer = "\n".join(all_but_last)
97
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  yield construct_process_message(
99
  message=buffer,
100
  current_step=process_desc,
 
104
  overall_units_total=overall_units_total,
105
  milestones=msg_packet["milestones"],
106
  )
107
+ buffer += "\n"
108
+ for c in last_message:
109
+ buffer += c
110
+ yield construct_process_message(
111
+ message=buffer,
112
+ current_step=process_desc,
113
+ units_processed=units_processed,
114
+ units_total=units_total,
115
+ overall_units_processed=overall_units_processed,
116
+ overall_units_total=overall_units_total,
117
+ milestones=msg_packet["milestones"],
118
+ )
119
+ await asyncio.sleep(0.005)
120
+ await asyncio.sleep(0.1)
121
+
122
+ buffer += (
123
+ "\n\n"
124
+ f"✅ Processed {len(files)} reports.\n"
125
+ "Please download the output file from below within 5 min."
126
+ )
127
+ except Exception as e:
128
+ print("Error processing stream", e)
129
+ traceback.print_exc()
130
+ buffer += f"\n\n❌ Error processing reports. {e}"
131
+
132
+ final_state["milestones"][-1].status = "failed"
133
+ final_state["milestones"][-1].end_time = datetime.now()
134
+ # update latest milestone status as failed
135
+ await get_db().add_or_update_milestone(
136
+ run_id=final_state["run_id"],
137
+ milestone=final_state["milestones"][-1].step_name,
138
+ status="failed",
139
+ end=True,
140
+ )
141
+
142
+ # update run status with failed
143
+ await get_db().update_run_stats(
144
+ run_id=final_state["run_id"], status="failed", message=f"{e}"
145
+ )
146
+ finally:
147
+ print("In finally ...", final_state["pdf_path"])
148
+ if final_state["pdf_path"]:
149
+ yield construct_process_message(
150
+ message=buffer,
151
+ final_output=gr.update(value=final_state["pdf_path"], visible=True),
152
+ milestones=final_state["milestones"],
153
+ reports_output=msg_packet["standardized_reports"],
154
+ trends_output=msg_packet["trends_json"],
155
+ )
156
+ else:
157
+ print("Yielding error message")
158
+ yield construct_process_message(
159
+ message=buffer,
160
+ final_output=gr.update(visible=False),
161
+ milestones=final_state["milestones"],
162
+ reports_output=msg_packet["standardized_reports"],
163
+ trends_output=msg_packet["trends_json"],
164
+ error=True
165
+ )
166
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
 
169
  def generate_milestones_data(
 
216
  milestones: list[SheamiMilestone] = [],
217
  reports_output=None,
218
  trends_output=None,
219
+ error=False
220
  ):
221
  try:
222
  if units_total > 0:
 
240
  else f"<div class='transparent_div'>{message}</div>"
241
  )
242
 
243
+ final_message = ""
244
+ if final_output:
245
+ if error:
246
+ final_message = "❌ There was an error processing your request. Please try after sometime."
247
+ else:
248
+ final_message = "✅ Your health trends report is ready for download!"
249
+ else:
250
+ final_message = ""
251
+
252
  return (
253
  formatted_message, # logs_textbox
254
  disable_component() if not final_output else enable_component(), # run_btn
 
261
  *render_patient_state(
262
  reports_output, trends_output
263
  ), # reports_output, trends_output
264
+ final_message # final_message
265
  )
266
 
267
 
 
472
  with gr.Tab(
473
  "Report Download", id="my_final_report_container"
474
  ) as final_report_container:
475
+ final_message = gr.Markdown()
476
  with gr.Row(equal_height=False):
477
  pdf_download = gr.DownloadButton(
478
  label="Download 📊",
 
539
  milestone_df,
540
  reports_output,
541
  trends_output,
542
+ final_message
543
  ],
544
  queue=True,
545
  ).then(