Spaces:
Running
Running
seapoe1809
commited on
Upload 3 files
Browse filesconnects to open source darnahi app
- darnabot.py +967 -0
- motivation.json +103 -0
- requirements.txt +10 -0
darnabot.py
ADDED
@@ -0,0 +1,967 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
# *
|
5 |
+
# *
|
6 |
+
# * This program is free software: you can redistribute it and/or modify
|
7 |
+
# * it under the terms of the GNU General Public License as published by
|
8 |
+
# * the Free Software Foundation, either version 3 of the License, or
|
9 |
+
# * (at your option) any later version.
|
10 |
+
# *
|
11 |
+
# * This program is distributed in the hope that it will be useful,
|
12 |
+
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
|
13 |
+
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
14 |
+
# * GNU General Public License for more details.
|
15 |
+
# *
|
16 |
+
# * You should have received a copy of the GNU General Public License
|
17 |
+
# * along with this program. If not, see <http://www.gnu.org/licenses/>.
|
18 |
+
# */
|
19 |
+
#uses chromaminer to chunk and embed and then uses function to extract relevant component
|
20 |
+
import os, subprocess
|
21 |
+
import re
|
22 |
+
import json
|
23 |
+
import random
|
24 |
+
import requests
|
25 |
+
import gradio as gr
|
26 |
+
import chromadb
|
27 |
+
import sqlite3
|
28 |
+
import base64
|
29 |
+
from io import BytesIO
|
30 |
+
from datetime import datetime
|
31 |
+
from fpdf import FPDF
|
32 |
+
import threading
|
33 |
+
from threading import local
|
34 |
+
from reportlab.pdfgen import canvas
|
35 |
+
from reportlab.lib.pagesizes import letter
|
36 |
+
import tempfile
|
37 |
+
from PIL import Image
|
38 |
+
import io
|
39 |
+
from ollama import AsyncClient
|
40 |
+
import asyncio
|
41 |
+
####NEW
|
42 |
+
#install pytesseract
|
43 |
+
#install pdf2image pip install reportlab PyPDF2 nltk wordcloud unidecode
|
44 |
+
#pdfplumber ollama
|
45 |
+
|
46 |
+
#from transformers import pipeline
|
47 |
+
#set model
|
48 |
+
model="mistral-nemo"
|
49 |
+
directory = ""
|
50 |
+
folderpath= ""
|
51 |
+
basic_info=""
|
52 |
+
|
53 |
+
|
54 |
+
|
55 |
+
|
56 |
+
conversation_memory = []
|
57 |
+
|
58 |
+
async def chat(messages):
|
59 |
+
|
60 |
+
async for part in await AsyncClient().chat(model=f'{model}', messages=messages, stream=True):
|
61 |
+
chunk=part['message']['content']
|
62 |
+
yield chunk
|
63 |
+
|
64 |
+
|
65 |
+
#this truncates the words for use by Chroma to build context
|
66 |
+
def truncate_words(documents):
|
67 |
+
truncated_documents = []
|
68 |
+
for doc in documents:
|
69 |
+
doc=str(doc)
|
70 |
+
words = doc.split()[:300] # Truncate to 300 words
|
71 |
+
truncated_documents.append(' '.join(words))
|
72 |
+
return truncated_documents
|
73 |
+
|
74 |
+
def generate_context_and_sources(
|
75 |
+
query: str,
|
76 |
+
collection_name: str = "documents_collection",
|
77 |
+
persist_directory: str = "chroma_storage"
|
78 |
+
) -> (str, str):
|
79 |
+
print(persist_directory)
|
80 |
+
context, sources = "No data available", "No sources available."
|
81 |
+
try:
|
82 |
+
# Check if persist_directory exists; if not
|
83 |
+
if not os.path.exists(persist_directory):
|
84 |
+
print(f"Directory '{persist_directory}' does not exist. Skipping.")
|
85 |
+
return context, sources
|
86 |
+
|
87 |
+
chroma_client = chromadb.PersistentClient(path=persist_directory)
|
88 |
+
collection = chroma_client.get_collection(name=collection_name)
|
89 |
+
|
90 |
+
results = collection.query(query_texts=[query], n_results=3, include=["documents", "metadatas"])
|
91 |
+
sources = "\n".join(
|
92 |
+
[
|
93 |
+
f"{result.get('filename', 'Unknown filename')}: batch {result.get('batch_number', 'Unknown batch')}"
|
94 |
+
for result in results["metadatas"][0] # type: ignore
|
95 |
+
]
|
96 |
+
)
|
97 |
+
truncated_documents = truncate_words(results["documents"])
|
98 |
+
context = "".join(truncated_documents)
|
99 |
+
|
100 |
+
except Exception as e:
|
101 |
+
print(f"Error accessing collection or processing query: {e}")
|
102 |
+
return context, sources
|
103 |
+
|
104 |
+
#set global directory
|
105 |
+
def set_user_directory(request: gr.Request):
|
106 |
+
global directory
|
107 |
+
referer= request.headers.get('referer')
|
108 |
+
if "user=1" in referer:
|
109 |
+
# Admin user
|
110 |
+
directory = "../Health_files/ocr_files/Darna_tesseract/"
|
111 |
+
elif "user=2" in referer:
|
112 |
+
# Non-admin user
|
113 |
+
directory = "../Health_files2/ocr_files/Darna_tesseract/"
|
114 |
+
else:
|
115 |
+
# Handle unexpected user types
|
116 |
+
directory = "/"
|
117 |
+
print(f"Current ocr directory: {directory}")
|
118 |
+
|
119 |
+
def set_user_health_files_directory(request: gr.Request):
|
120 |
+
global folderpath
|
121 |
+
referer= request.headers.get('referer')
|
122 |
+
if "user=1" in referer:
|
123 |
+
# Admin user
|
124 |
+
folderpath = "../Health_files/"
|
125 |
+
elif "user=2" in referer:
|
126 |
+
# Non-admin user
|
127 |
+
folderpath = "../Health_files2/"
|
128 |
+
else:
|
129 |
+
# Handle unexpected user types
|
130 |
+
folderpath = "/"
|
131 |
+
print(f"Current folderpath: {folderpath}")
|
132 |
+
|
133 |
+
|
134 |
+
#function to ananlyze the input query using re and make some assessment on where to get context
|
135 |
+
def analyze_query(query, directory):
|
136 |
+
#pattern for keyword
|
137 |
+
darna_pattern = r'(?:darnahi|darna|server|hello)\s*[:=]?\s*'
|
138 |
+
darna_match = re.search(darna_pattern, query, re.IGNORECASE)
|
139 |
+
darna_value = darna_match.group().strip() if darna_match else None
|
140 |
+
|
141 |
+
med_pattern = r'(?:meds|medication|medications|medicine|medicine|drug|drugs)\s*[:=]?\s*'
|
142 |
+
med_match = re.search(med_pattern, query, re.IGNORECASE)
|
143 |
+
med_value = med_match.group().strip() if med_match else None
|
144 |
+
|
145 |
+
summary_pattern = r'(?:medical|clinical|advice|advise|weight|diet)\s*[:=]?\s*'
|
146 |
+
summary_match = re.search(summary_pattern, query, re.IGNORECASE)
|
147 |
+
summary_value = summary_match.group().strip() if summary_match else None
|
148 |
+
|
149 |
+
past_medical_history_pattern = r'(?:history|procedure|procedures|surgery|pastmedical|pmh|past-medical|past-history)\s*[:=]?\s*'
|
150 |
+
past_medical_history_match = re.search(past_medical_history_pattern, query, re.IGNORECASE)
|
151 |
+
past_medical_history_value = past_medical_history_match.group().strip() if past_medical_history_match else None
|
152 |
+
|
153 |
+
xmr_pattern = r'(?:monero|xmr|crypto|cryptocurrency|privacy|XMR|MOnero)\s*[:=]?\s*'
|
154 |
+
xmr_match = re.search(xmr_pattern, query, re.IGNORECASE)
|
155 |
+
xmr_value = xmr_match.group().strip() if xmr_match else None
|
156 |
+
|
157 |
+
json_file_path= f'{directory}/wordcloud_summary.json'
|
158 |
+
|
159 |
+
try:
|
160 |
+
with open(json_file_path, 'r', encoding='utf-8') as file:
|
161 |
+
existing_data = json.load(file)
|
162 |
+
except FileNotFoundError:
|
163 |
+
existing_data = {}
|
164 |
+
|
165 |
+
result = ""
|
166 |
+
if darna_value is not None:
|
167 |
+
print(darna_value)
|
168 |
+
key='darnahi'
|
169 |
+
result += existing_data.get(key, " ")[:150]
|
170 |
+
if med_value is not None:
|
171 |
+
print(med_value)
|
172 |
+
key = 'darnahi_medications'
|
173 |
+
result += existing_data.get(key, " ")[:350]
|
174 |
+
if summary_value is not None:
|
175 |
+
print(summary_value)
|
176 |
+
key = 'darnahi_summary'
|
177 |
+
result += existing_data.get(key, "No data found for 'summary' key.")[:350]
|
178 |
+
if past_medical_history_value is not None:
|
179 |
+
print(past_medical_history_value)
|
180 |
+
key = 'darnahi_past_medical_history'
|
181 |
+
result += existing_data.get(key, " ")[:150]
|
182 |
+
if xmr_value is not None:
|
183 |
+
print(xmr_value)
|
184 |
+
key = 'darnahi_xmr'
|
185 |
+
result += existing_data.get(key, " ")[:150]
|
186 |
+
|
187 |
+
# Check if no pattern matched
|
188 |
+
if not (darna_match or med_match or summary_match or xmr_match or past_medical_history_match):
|
189 |
+
|
190 |
+
collection_name="documents_collection"
|
191 |
+
context, sources = generate_context_and_sources(query, collection_name, os.path.join(directory, 'chroma_storage'))
|
192 |
+
|
193 |
+
print(context, sources)
|
194 |
+
result = context[:150]
|
195 |
+
if result is None:
|
196 |
+
result={''}
|
197 |
+
|
198 |
+
print(result)
|
199 |
+
return result
|
200 |
+
|
201 |
+
|
202 |
+
|
203 |
+
#generate a chat function using the query and context
|
204 |
+
async def my_function(query, request: gr.Request, chat_history):
|
205 |
+
#pass userID
|
206 |
+
global conversation_memory
|
207 |
+
history ="<history>\n".join(conversation_memory)
|
208 |
+
if len(history) > 300:
|
209 |
+
history = history[-400:]
|
210 |
+
|
211 |
+
print(history)
|
212 |
+
referer= request.headers.get('referer')
|
213 |
+
if "user=2" in referer:
|
214 |
+
#non admin user
|
215 |
+
directory="../Health_files2/ocr_files/Darna_tesseract/"
|
216 |
+
print(directory)
|
217 |
+
elif "user=1" in referer:
|
218 |
+
#admin
|
219 |
+
directory="../Health_files/ocr_files/Darna_tesseract/"
|
220 |
+
print(directory)
|
221 |
+
else:
|
222 |
+
directory="/"
|
223 |
+
print("default dir")
|
224 |
+
|
225 |
+
#chroma rag
|
226 |
+
context=analyze_query(query, directory)
|
227 |
+
context=f'<context>{context}</context>'
|
228 |
+
|
229 |
+
messages = [
|
230 |
+
{"role": "user", "content": "You are Darnabot. End with a followup"},
|
231 |
+
{"role": "assistant", "content": "I am 'Darnabot', AI health assistant with domain expertise. How can I help?"},
|
232 |
+
{"role": "user", "content": f"'Darnabot' answer query: {query} using context: {context}. Also here is history of previous conversation with user but ignore if not relevant to query: {history}"},
|
233 |
+
]
|
234 |
+
|
235 |
+
|
236 |
+
|
237 |
+
full_response=""
|
238 |
+
async for content in chat(messages):
|
239 |
+
full_response += content
|
240 |
+
yield chat_history + [(query, full_response)]
|
241 |
+
|
242 |
+
|
243 |
+
conversation_memory.append(f"<history> {full_response}</history>")
|
244 |
+
conversation_memory = conversation_memory[-4:]
|
245 |
+
|
246 |
+
def clear_conversation():
|
247 |
+
global conversation_memory
|
248 |
+
conversation_memory = []
|
249 |
+
gr.ClearButton([msg, chatbot])
|
250 |
+
return "", None
|
251 |
+
|
252 |
+
################################
|
253 |
+
"""
|
254 |
+
#run ai to analyze records
|
255 |
+
#from analyze import *
|
256 |
+
import logging
|
257 |
+
import json
|
258 |
+
import subprocess
|
259 |
+
from typing import List, Tuple
|
260 |
+
|
261 |
+
def stepwise_error_handling_analyze(deidentify_words, folderpath: str, ocr_files: str, age: int, sex: str) -> List[Tuple[str, str]]:
|
262 |
+
logging.basicConfig(filename='error_log.txt', level=logging.ERROR,
|
263 |
+
format='%(asctime)s - %(levelname)s - %(message)s')
|
264 |
+
|
265 |
+
steps = [
|
266 |
+
("Extract and write LForms data", lambda: extract_and_write_lforms_data(folderpath)),
|
267 |
+
("Process OCR files", lambda: process_ocr_files(ocr_files)),
|
268 |
+
("Collate images", lambda: collate_images(ocr_files, f"{ocr_files}/Darna_tesseract")),
|
269 |
+
("Deidentify records", deidentify_records(ocr_files, deidentify_words)),
|
270 |
+
("Generate recommendations", lambda: generate_recommendations(folderpath, age=age, sex=sex)),
|
271 |
+
("Process PDF files", lambda: process_pdf_files(ocr_files)),
|
272 |
+
("Process directory summary", lambda: process_directory_summary(ocr_files, ['HPI', 'history', 'summary'])),
|
273 |
+
("Create wordcloud", lambda: preprocess_and_create_wordcloud(process_directory_summary(ocr_files, ['HPI', 'history', 'summary']), f'{ocr_files}/Darna_tesseract/')),
|
274 |
+
("Process directory meds", lambda: process_directory_meds(ocr_files, ['medications', 'MEDICATIONS:', 'medicine', 'meds'])),
|
275 |
+
("Load screening text", lambda: load_text_from_json_screening(f'{ocr_files}/Darna_tesseract/combined_output.json', ['RECS', 'RECOMMENDATIONS'])),
|
276 |
+
("Process directory PMH", lambda: process_directory_pmh(ocr_files, ['PMH', 'medical', 'past medical history', 'surgical', 'past'])),
|
277 |
+
("Generate wordcloud summary", lambda: wordcloud_summary(
|
278 |
+
("darnahi_summary", "darnahi_past_medical_history", "darnahi_medications", "darnahi_screening"),
|
279 |
+
(process_directory_summary(ocr_files, ['HPI', 'history', 'summary']),
|
280 |
+
process_directory_pmh(ocr_files, ['PMH', 'medical', 'past medical history', 'surgical', 'past']),
|
281 |
+
process_directory_meds(ocr_files, ['medications', 'MEDICATIONS:', 'medicine', 'meds']),
|
282 |
+
load_text_from_json_screening(f'{ocr_files}/combined_output.json', ['RECS', 'RECOMMENDATIONS'])),
|
283 |
+
f'{ocr_files}/Darna_tesseract/'
|
284 |
+
)),
|
285 |
+
#("Chromadb embed", lambda: chromadb_embed(ocr_files)),
|
286 |
+
#("Clean up directory", lambda: subprocess.run(f'find {ocr_files} -maxdepth 1 -type f -exec rm {{}} +', shell=True))
|
287 |
+
]
|
288 |
+
|
289 |
+
results = []
|
290 |
+
|
291 |
+
for step_name, step_function in steps:
|
292 |
+
try:
|
293 |
+
step_function()
|
294 |
+
results.append((step_name, "Success"))
|
295 |
+
except Exception as e:
|
296 |
+
error_message = f"Error in {step_name}: {str(e)}"
|
297 |
+
logging.error(error_message)
|
298 |
+
results.append((step_name, f"Error: {str(e)}"))
|
299 |
+
|
300 |
+
return results
|
301 |
+
|
302 |
+
def extract_and_write_lforms_data(folderpath: str):
|
303 |
+
with open(f'{folderpath}/summary/chart.json', 'r') as file:
|
304 |
+
json_data = json.load(file)
|
305 |
+
|
306 |
+
extracted_info = extract_lforms_data(json.dumps(json_data))
|
307 |
+
json_output = json.dumps(extracted_info, indent=4)
|
308 |
+
write_text_to_pdf(folderpath, str(extracted_info))
|
309 |
+
with open(f'{folderpath}/ocr_files/fhir_output.json', 'w', encoding='utf-8') as f:
|
310 |
+
f.write(json_output)
|
311 |
+
|
312 |
+
"""
|
313 |
+
|
314 |
+
def extract_lforms_data(json_data):
|
315 |
+
if isinstance(json_data, str):
|
316 |
+
data = json.loads(json_data)
|
317 |
+
else:
|
318 |
+
data = json_data
|
319 |
+
|
320 |
+
extracted_info = {
|
321 |
+
"date_of_birth": None,
|
322 |
+
"sex": None,
|
323 |
+
"allergies": [],
|
324 |
+
"past_medical_history": [],
|
325 |
+
"medications": []
|
326 |
+
}
|
327 |
+
|
328 |
+
for item in data.get("items", []):
|
329 |
+
if item.get("question") == "ABOUT ME":
|
330 |
+
for subitem in item.get("items", []):
|
331 |
+
if subitem.get("question") == "DATE OF BIRTH":
|
332 |
+
extracted_info["date_of_birth"] = subitem.get("value")
|
333 |
+
elif subitem.get("question") == "BIOLOGICAL SEX":
|
334 |
+
extracted_info["sex"] = subitem.get("value", {}).get("text")
|
335 |
+
|
336 |
+
elif item.get("question") == "ALLERGIES":
|
337 |
+
for allergy_item in item.get("items", []):
|
338 |
+
if allergy_item.get("question") == "Allergies and Other Dangerous Reactions":
|
339 |
+
for subitem in allergy_item.get("items", []):
|
340 |
+
if subitem.get("question") == "Name" and "value" in subitem:
|
341 |
+
extracted_info["allergies"].append(subitem["value"]["text"])
|
342 |
+
|
343 |
+
elif item.get("question") == "PAST MEDICAL HISTORY:":
|
344 |
+
for condition_item in item.get("items", []):
|
345 |
+
if condition_item.get("question") == "PAST MEDICAL HISTORY" and "value" in condition_item:
|
346 |
+
condition = extract_condition(condition_item)
|
347 |
+
if condition:
|
348 |
+
extracted_info["past_medical_history"].append(condition)
|
349 |
+
|
350 |
+
elif item.get("question") == "MEDICATIONS:":
|
351 |
+
medication = {}
|
352 |
+
for med_item in item.get("items", []):
|
353 |
+
if med_item.get("question") == "MEDICATIONS":
|
354 |
+
medication["name"] = extract_med_value(med_item)
|
355 |
+
elif med_item.get("question") == "Strength":
|
356 |
+
medication["strength"] = extract_med_value(med_item)
|
357 |
+
elif med_item.get("question") == "Instructions":
|
358 |
+
medication["instructions"] = extract_med_value(med_item)
|
359 |
+
if medication:
|
360 |
+
extracted_info["medications"].append(medication)
|
361 |
+
|
362 |
+
return extracted_info
|
363 |
+
|
364 |
+
|
365 |
+
def extract_condition(condition_item):
|
366 |
+
if isinstance(condition_item.get("value"), dict):
|
367 |
+
return condition_item["value"].get("text", "")
|
368 |
+
elif isinstance(condition_item.get("value"), str):
|
369 |
+
return condition_item["value"]
|
370 |
+
return ""
|
371 |
+
|
372 |
+
def extract_med_value(med_item):
|
373 |
+
if "value" not in med_item:
|
374 |
+
return ""
|
375 |
+
value = med_item["value"]
|
376 |
+
if isinstance(value, str):
|
377 |
+
return value
|
378 |
+
elif isinstance(value, dict):
|
379 |
+
return value.get("text", "")
|
380 |
+
return ""
|
381 |
+
##run analyze located in ../dir
|
382 |
+
def analyze(request: gr.Request, deidentify_words):
|
383 |
+
set_user_health_files_directory(request)
|
384 |
+
if not folderpath:
|
385 |
+
print("folderpath value is empty. Skipping.")
|
386 |
+
return
|
387 |
+
# Set up environment variables
|
388 |
+
env_vars = os.environ.copy()
|
389 |
+
env_vars['FOLDERPATH'] = folderpath
|
390 |
+
if deidentify_words:
|
391 |
+
content = f"\nignore_words = '{deidentify_words}'\n"
|
392 |
+
file_path_variables2 = "../variables/variables2.py"
|
393 |
+
try:
|
394 |
+
with open(file_path_variables2, 'a') as file:
|
395 |
+
file.write(content)
|
396 |
+
print(f"Successfully appended deidentify_words to {file_path_variables2}")
|
397 |
+
except IOError as e:
|
398 |
+
error_message = f"IOError writing to variables2.py: {str(e)}"
|
399 |
+
print(error_message)
|
400 |
+
return error_message
|
401 |
+
except Exception as e:
|
402 |
+
error_message = f"Unexpected error writing to variables2.py: {str(e)}"
|
403 |
+
print(error_message)
|
404 |
+
return error_message
|
405 |
+
# Get the absolute path to the current script's directory
|
406 |
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
407 |
+
|
408 |
+
# Set up the paths
|
409 |
+
venv_dir = os.path.abspath(os.path.join(current_dir, '..', 'darnavenv'))
|
410 |
+
venv_python = os.path.join(venv_dir, 'bin', 'python3.10')
|
411 |
+
analyze_script = os.path.abspath(os.path.join(current_dir, '..', 'analyze.py'))
|
412 |
+
|
413 |
+
command = [venv_python, analyze_script]
|
414 |
+
|
415 |
+
try:
|
416 |
+
result = subprocess.run(command, env=env_vars, check=True, text=True, capture_output=True)
|
417 |
+
print("Running Analyzer output:", result.stdout)
|
418 |
+
return "🟢 Analysis completed successfully"
|
419 |
+
except subprocess.CalledProcessError as e:
|
420 |
+
print("Error running analyze.py:", e)
|
421 |
+
print("Error output:", e.stderr)
|
422 |
+
|
423 |
+
|
424 |
+
##fetch age/sex in analyze module
|
425 |
+
def fetch_age_sex(request: gr.Request):
|
426 |
+
set_user_health_files_directory(request)
|
427 |
+
if not folderpath:
|
428 |
+
print("Directory value is empty. Skipping.")
|
429 |
+
return None, None, gr.update(visible=False), gr.update(visible=False)
|
430 |
+
|
431 |
+
ocr_files = f"{folderpath}/ocr_files"
|
432 |
+
try:
|
433 |
+
with open(f'{folderpath}/summary/chart.json', 'r') as file:
|
434 |
+
json_data = json.load(file)
|
435 |
+
|
436 |
+
extracted_info = extract_lforms_data(json.dumps(json_data))
|
437 |
+
sex = extracted_info.get('sex', None)
|
438 |
+
dob_str = extracted_info.get('date_of_birth', None)
|
439 |
+
|
440 |
+
age = None
|
441 |
+
if dob_str is not None:
|
442 |
+
try:
|
443 |
+
dob = datetime.strptime(dob_str, '%Y-%m-%d')
|
444 |
+
today = datetime.now()
|
445 |
+
age = today.year - dob.year
|
446 |
+
|
447 |
+
# Adjust age if birthday hasn't occurred this year
|
448 |
+
if (today.month, today.day) < (dob.month, dob.day):
|
449 |
+
age -= 1
|
450 |
+
except ValueError as e:
|
451 |
+
print(f"Error parsing date: {e}")
|
452 |
+
|
453 |
+
# Check if both age and sex are not None
|
454 |
+
if age is not None and sex is not None:
|
455 |
+
content = f"age = '{age}'\nsex = '{sex}'\n"
|
456 |
+
file_path_variables2 = f"../variables/variables2.py"
|
457 |
+
try:
|
458 |
+
with open(file_path_variables2, 'w') as file:
|
459 |
+
file.write(content)
|
460 |
+
except Exception as e:
|
461 |
+
print(f"Error writing to variables2.py: {str(e)}")
|
462 |
+
return None, None, gr.update(visible=False), gr.update(visible=False)
|
463 |
+
|
464 |
+
return f"Age: {age}\n Sex: {sex}\n", "🟢 Ready to analyze", gr.update(visible=True), gr.update(visible=True)
|
465 |
+
else:
|
466 |
+
return None, "🔴 Please update your age and sex in Darnahi Chartit", gr.update(visible=False), gr.update(visible=False)
|
467 |
+
|
468 |
+
except Exception as e:
|
469 |
+
return None, f"An error occurred: {str(e)}", gr.update(visible=False), gr.update(visible=False)
|
470 |
+
|
471 |
+
|
472 |
+
|
473 |
+
|
474 |
+
|
475 |
+
####AI File server
|
476 |
+
def list_files(directory):
|
477 |
+
files = []
|
478 |
+
try:
|
479 |
+
# List files in the main directory
|
480 |
+
files.extend([f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))])
|
481 |
+
|
482 |
+
# List files in the AI wordcloud subdirectory
|
483 |
+
wordcloud_dir = os.path.join(directory, "wordclouds")
|
484 |
+
if os.path.isdir(wordcloud_dir):
|
485 |
+
wordcloud_files = [os.path.join("wordclouds", f) for f in os.listdir(wordcloud_dir) if os.path.isfile(os.path.join(wordcloud_dir, f))]
|
486 |
+
files.extend(wordcloud_files)
|
487 |
+
|
488 |
+
return files
|
489 |
+
except OSError as e:
|
490 |
+
#print(f"Pick a directory to list {directory}: {e}")
|
491 |
+
return []
|
492 |
+
|
493 |
+
def display_file(filename):
|
494 |
+
if not filename or isinstance(filename, gr.components.Dropdown):
|
495 |
+
return None, None
|
496 |
+
|
497 |
+
try:
|
498 |
+
file_path = os.path.join(directory, filename)
|
499 |
+
if os.path.exists(file_path):
|
500 |
+
if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
|
501 |
+
return None, file_path
|
502 |
+
else:
|
503 |
+
with open(file_path, 'r') as file:
|
504 |
+
content = file.read()
|
505 |
+
return content, None
|
506 |
+
else:
|
507 |
+
print(f"File not found: {file_path}")
|
508 |
+
return None, None
|
509 |
+
except Exception as e:
|
510 |
+
print(f"Error displaying file {filename}: {e}")
|
511 |
+
return None, None
|
512 |
+
|
513 |
+
def refresh_file_list(request: gr.Request):
|
514 |
+
#checks for RAG dir and also refreshes list of files
|
515 |
+
set_user_directory(request)
|
516 |
+
|
517 |
+
file_choices = list_files(directory)
|
518 |
+
|
519 |
+
if os.path.isdir(os.path.join(directory, "chroma_storage")):
|
520 |
+
status = "🟢 RAG database successfully setup for Darnabot User"
|
521 |
+
else:
|
522 |
+
status = "🔴 RAG database needs to be set up for Darnabot User"
|
523 |
+
|
524 |
+
return gr.Dropdown(choices=file_choices), status
|
525 |
+
|
526 |
+
def update_display(filename):
|
527 |
+
if isinstance(filename, gr.components.Dropdown):
|
528 |
+
filename = filename.value
|
529 |
+
if not filename:
|
530 |
+
return gr.update(value="No file selected", visible=True), gr.update(value=None, visible=False)
|
531 |
+
|
532 |
+
content, image_path = display_file(filename)
|
533 |
+
if image_path:
|
534 |
+
return gr.update(value=None, visible=False), gr.update(value=image_path, visible=True)
|
535 |
+
elif content is not None:
|
536 |
+
return gr.update(value=content, visible=True), gr.update(value=None, visible=False)
|
537 |
+
else:
|
538 |
+
return gr.update(value="Error displaying file", visible=True), gr.update(value=None, visible=False)
|
539 |
+
|
540 |
+
|
541 |
+
##SYMPTOM LOGGER
|
542 |
+
|
543 |
+
# Create a thread-local storage
|
544 |
+
local = threading.local()
|
545 |
+
|
546 |
+
# Function to get and connect to relevant database connection for current thread
|
547 |
+
def get_db():
|
548 |
+
if folderpath is None:
|
549 |
+
print("folderpath value is empty. Skipping. Please connect to your Darnahi Account.")
|
550 |
+
return None
|
551 |
+
|
552 |
+
try:
|
553 |
+
db_path = f"{folderpath}/summary/medical_records.db"
|
554 |
+
conn = sqlite3.connect(db_path)
|
555 |
+
return conn
|
556 |
+
except sqlite3.Error as e:
|
557 |
+
print(f"An error occurred while connecting to the database: {e}")
|
558 |
+
return None
|
559 |
+
|
560 |
+
|
561 |
+
def close_db():
|
562 |
+
if hasattr(local, "db") and local.db is not None:
|
563 |
+
local.db.close()
|
564 |
+
local.db = None
|
565 |
+
|
566 |
+
# Initialize the database
|
567 |
+
def init_db(request: gr.Request):
|
568 |
+
|
569 |
+
if folderpath is None:
|
570 |
+
print("folderpath value is empty. Skipping. Please connect to your Darnahi Account.")
|
571 |
+
return
|
572 |
+
|
573 |
+
global get_basic
|
574 |
+
get_basic(folderpath)
|
575 |
+
|
576 |
+
db = get_db()
|
577 |
+
if db is None:
|
578 |
+
return
|
579 |
+
|
580 |
+
try:
|
581 |
+
with db:
|
582 |
+
cursor = db.cursor()
|
583 |
+
cursor.execute('''
|
584 |
+
CREATE TABLE IF NOT EXISTS records (
|
585 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
586 |
+
date TEXT,
|
587 |
+
age INTEGER,
|
588 |
+
sex TEXT,
|
589 |
+
symptom TEXT,
|
590 |
+
past_medical_history TEXT,
|
591 |
+
medications TEXT,
|
592 |
+
image BLOB,
|
593 |
+
comment TEXT
|
594 |
+
)
|
595 |
+
''')
|
596 |
+
print("Database initialized successfully.")
|
597 |
+
except sqlite3.Error as e:
|
598 |
+
print(f"An error occurred while initializing the database: {e}")
|
599 |
+
finally:
|
600 |
+
if db:
|
601 |
+
db.close()
|
602 |
+
|
603 |
+
|
604 |
+
def get_basic(folderpath):
|
605 |
+
# This function gets chartit summary
|
606 |
+
with open(f'{folderpath}/summary/chart.json', 'r') as file:
|
607 |
+
json_data = json.load(file)
|
608 |
+
|
609 |
+
extracted_info = extract_lforms_data(json.dumps(json_data))
|
610 |
+
json_output = json.dumps(extracted_info, indent=4)
|
611 |
+
write_text_to_pdf(folderpath, str(extracted_info))
|
612 |
+
with open(f'{folderpath}/ocr_files/fhir_output.json', 'w', encoding='utf-8') as f:
|
613 |
+
f.write(json_output)
|
614 |
+
return extracted_info
|
615 |
+
|
616 |
+
#duplicate as AI module but seems to relevant to keep
|
617 |
+
def calculate_age(dob):
|
618 |
+
if dob is not None:
|
619 |
+
today = datetime.now()
|
620 |
+
born = datetime.strptime(dob, "%Y-%m-%d")
|
621 |
+
|
622 |
+
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
|
623 |
+
return "Please update Chartit in you account"
|
624 |
+
|
625 |
+
|
626 |
+
|
627 |
+
#create PDF with container and margins
|
628 |
+
class PDF(FPDF):
|
629 |
+
def header(self):
|
630 |
+
self.set_font('Arial', 'B', 12)
|
631 |
+
self.cell(0, 10, 'Medical Record', 0, 1, 'C')
|
632 |
+
self.ln(10)
|
633 |
+
|
634 |
+
def footer(self):
|
635 |
+
self.set_y(-15)
|
636 |
+
self.set_font('Arial', 'I', 8)
|
637 |
+
self.cell(0, 10, f'Page {self.page_no()}/{{nb}}', 0, 0, 'C')
|
638 |
+
|
639 |
+
def create_pdf(record, image_data):
|
640 |
+
pdf = PDF()
|
641 |
+
pdf.alias_nb_pages()
|
642 |
+
pdf.add_page()
|
643 |
+
pdf.set_font("Arial", size=12)
|
644 |
+
pdf.set_auto_page_break(auto=True, margin=15)
|
645 |
+
|
646 |
+
# Set margin so that the comments dont go past margin
|
647 |
+
pdf.set_left_margin(10)
|
648 |
+
|
649 |
+
for key, value in record.items():
|
650 |
+
if key != 'image' and key != 'comment':
|
651 |
+
pdf.cell(0, 10, txt=f"{key}: {value}", ln=True)
|
652 |
+
|
653 |
+
pdf.ln(10)
|
654 |
+
pdf.set_font("Arial", 'B', size=12)
|
655 |
+
pdf.cell(0, 10, txt="Comment:", ln=True)
|
656 |
+
pdf.set_font("Arial", size=12)
|
657 |
+
pdf.multi_cell(0, 10, txt=record['comment'])
|
658 |
+
|
659 |
+
if image_data:
|
660 |
+
try:
|
661 |
+
image_bytes = base64.b64decode(image_data)
|
662 |
+
|
663 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
|
664 |
+
temp_file.write(image_bytes)
|
665 |
+
temp_file_path = temp_file.name
|
666 |
+
|
667 |
+
pdf.add_page()
|
668 |
+
pdf.image(temp_file_path, x=10, y=30, w=190)
|
669 |
+
|
670 |
+
os.unlink(temp_file_path)
|
671 |
+
except Exception as e:
|
672 |
+
pdf.ln(10)
|
673 |
+
pdf.cell(0, 10, txt=f"Error processing image: {e}", ln=True)
|
674 |
+
|
675 |
+
summary_dir = os.path.join(folderpath, "summary")
|
676 |
+
ocr_dir = os.path.join(folderpath, "ocr_files")
|
677 |
+
|
678 |
+
|
679 |
+
filename = os.path.join(summary_dir, f"record_{record['date'].replace(':', '-')}.pdf")
|
680 |
+
filename2 = os.path.join(ocr_dir, f"record_{record['date'].replace(':', '-')}.pdf")
|
681 |
+
|
682 |
+
pdf.output(filename)
|
683 |
+
pdf.output(filename2)
|
684 |
+
return filename, filename2
|
685 |
+
|
686 |
+
def write_text_to_pdf(directory, text):
|
687 |
+
pdf_buffer = BytesIO()
|
688 |
+
c = canvas.Canvas(pdf_buffer, pagesize=letter)
|
689 |
+
text_object = c.beginText(72, 750) # Start 1 inch from top
|
690 |
+
for line in text.split('\n'):
|
691 |
+
text_object.textLine(line)
|
692 |
+
c.drawText(text_object)
|
693 |
+
c.save()
|
694 |
+
|
695 |
+
# Save the PDF
|
696 |
+
with open(f'{directory}/ocr_files/fhir_data.pdf', 'wb') as f:
|
697 |
+
f.write(pdf_buffer.getvalue())
|
698 |
+
|
699 |
+
def submit_record(symptom, outputd, comment, file):
|
700 |
+
basic_info = get_basic(folderpath)
|
701 |
+
age = calculate_age(basic_info['date_of_birth'])
|
702 |
+
final_comment = outputd if outputd is not None else (comment if comment is not None else "")
|
703 |
+
|
704 |
+
record = {
|
705 |
+
'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
706 |
+
'age': age,
|
707 |
+
'sex': basic_info['sex'],
|
708 |
+
'symptom': symptom,
|
709 |
+
'past_medical_history': json.dumps(basic_info['past_medical_history']),
|
710 |
+
'medications': json.dumps(basic_info['medications']),
|
711 |
+
'comment': final_comment
|
712 |
+
}
|
713 |
+
|
714 |
+
image_data = None
|
715 |
+
if file:
|
716 |
+
try:
|
717 |
+
# Read /encode file as base64
|
718 |
+
with open(file.name, "rb") as image_file:
|
719 |
+
image_data = base64.b64encode(image_file.read()).decode('utf-8')
|
720 |
+
except Exception as e:
|
721 |
+
return f"🔴 Error processing image: {e}"
|
722 |
+
|
723 |
+
with get_db() as conn:
|
724 |
+
cursor = conn.cursor()
|
725 |
+
cursor.execute('''
|
726 |
+
INSERT INTO records (date, age, sex, symptom, past_medical_history, medications, image, comment)
|
727 |
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
728 |
+
''', (record['date'], record['age'], record['sex'], record['symptom'], record['past_medical_history'], record['medications'], image_data, final_comment))
|
729 |
+
conn.commit()
|
730 |
+
|
731 |
+
pdf_filename = create_pdf(record, image_data)
|
732 |
+
|
733 |
+
return f"🟢 Record submitted successfully. {pdf_filename}"
|
734 |
+
|
735 |
+
def fetch_records():
|
736 |
+
with get_db() as conn:
|
737 |
+
cursor = conn.cursor()
|
738 |
+
cursor.execute("SELECT id, date, symptom FROM records ORDER BY date DESC")
|
739 |
+
records = cursor.fetchall()
|
740 |
+
if not records:
|
741 |
+
return gr.Dropdown(choices=["No records available"], value="No records available")
|
742 |
+
choices = [f"{r[0]} - {r[1]} - {r[2]}" for r in records]
|
743 |
+
return gr.Dropdown(choices=choices, value=choices[0])
|
744 |
+
|
745 |
+
def display_record(selected_record):
|
746 |
+
if not selected_record or selected_record == "No records available":
|
747 |
+
return "Please select a record to display", None
|
748 |
+
|
749 |
+
record_id = int(selected_record.split(' - ')[0])
|
750 |
+
with get_db() as conn:
|
751 |
+
cursor = conn.cursor()
|
752 |
+
cursor.execute("SELECT * FROM records WHERE id = ?", (record_id,))
|
753 |
+
record = cursor.fetchone()
|
754 |
+
|
755 |
+
if not record:
|
756 |
+
return "Record not found", None
|
757 |
+
|
758 |
+
columns = ['id', 'date', 'age', 'sex', 'symptom', 'past_medical_history', 'medications', 'image', 'comment']
|
759 |
+
record_dict = {columns[i]: record[i] for i in range(len(columns))}
|
760 |
+
|
761 |
+
display_text = "\n".join([f"{k}: {v}" for k, v in record_dict.items() if k != 'image'])
|
762 |
+
|
763 |
+
if record_dict['image']:
|
764 |
+
try:
|
765 |
+
image_data = base64.b64decode(record_dict['image'])
|
766 |
+
img = Image.open(io.BytesIO(image_data))
|
767 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
|
768 |
+
img.save(temp_file.name, 'PNG')
|
769 |
+
temp_file_path = temp_file.name
|
770 |
+
return display_text, temp_file_path
|
771 |
+
except Exception as e:
|
772 |
+
return f"{display_text}\n\nError displaying image: {e}", None
|
773 |
+
else:
|
774 |
+
return display_text, None
|
775 |
+
|
776 |
+
#toggle visibility and connect to relevant DB
|
777 |
+
def toggle_visibility(choice, request: gr.Request):
|
778 |
+
set_user_health_files_directory(request)
|
779 |
+
close_db()
|
780 |
+
init_db(request)
|
781 |
+
|
782 |
+
if choice == "new":
|
783 |
+
return gr.Row.update(visible=True), gr.Row.update(visible=False)
|
784 |
+
else:
|
785 |
+
return gr.Row.update(visible=False), gr.Row.update(visible=True)
|
786 |
+
|
787 |
+
#Using ai to write a note
|
788 |
+
class HealthMotivator:
|
789 |
+
async def get_motivation(self, symptom_info):
|
790 |
+
messages = [
|
791 |
+
{"role": "system", "content": "You are Darnabot, medical transcriber. Write a brief note with input and suggested first aid management only. Suggest doctor if complicated."},
|
792 |
+
{"role": "user", "content": f"Generate a brief note input: {symptom_info} only. Do not make up information."},
|
793 |
+
]
|
794 |
+
|
795 |
+
try:
|
796 |
+
OLLAMA_HOST = os.environ.get('OLLAMA_HOST', 'http://localhost:11434')
|
797 |
+
async for part in await AsyncClient(host=OLLAMA_HOST).chat(model=f'{model}', messages=messages, stream=True):
|
798 |
+
yield part['message']['content']
|
799 |
+
except Exception as e:
|
800 |
+
yield f"Remember to take care of your health. Please see links below! Also download {model} from ollama. (Error: {str(e)})"
|
801 |
+
|
802 |
+
|
803 |
+
|
804 |
+
motivator = HealthMotivator()
|
805 |
+
|
806 |
+
async def symptom_note(symptom, symptom_info):
|
807 |
+
basic_info = get_basic(folderpath)
|
808 |
+
age = calculate_age(basic_info['date_of_birth'])
|
809 |
+
symptom_info = {
|
810 |
+
'date': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
811 |
+
'age': age,
|
812 |
+
'sex': basic_info['sex'],
|
813 |
+
'symptom': symptom,
|
814 |
+
'past_medical_history': json.dumps(basic_info['past_medical_history']),
|
815 |
+
'medications': json.dumps(basic_info['medications']),
|
816 |
+
'comment': symptom_info
|
817 |
+
}
|
818 |
+
|
819 |
+
motivation = "See a doctor for Advice. This is only information. "
|
820 |
+
async for chunk in motivator.get_motivation(symptom_info):
|
821 |
+
motivation += chunk
|
822 |
+
yield motivation
|
823 |
+
|
824 |
+
#######################GRADIO UI
|
825 |
+
|
826 |
+
with gr.Blocks(theme='Taithrah/Minimal', css= "footer{display:none !important}") as demo:
|
827 |
+
with open('motivation.json', 'r') as file:
|
828 |
+
proverbs = json.load(file)
|
829 |
+
random_key = random.choice(list(proverbs.keys()))
|
830 |
+
proverb = proverbs[random_key]
|
831 |
+
gr.Markdown(f"""<div style='text-align: center; font-size: 1rem;'>
|
832 |
+
<i>{proverb}</i>
|
833 |
+
</div>
|
834 |
+
""")
|
835 |
+
with gr.Tab("DARNABOT"):
|
836 |
+
chatbot = gr.Chatbot(label="DARNAHI CONCIERGE 🛎️")
|
837 |
+
msg = gr.Textbox(label="Ask DARNABOT:", placeholder="How can I help?")
|
838 |
+
with gr.Row():
|
839 |
+
btn1 = gr.Button("Ask")
|
840 |
+
Clear = gr.ClearButton([msg, chatbot])
|
841 |
+
|
842 |
+
|
843 |
+
btn1.click(my_function, inputs=[msg, chatbot], outputs=[chatbot])
|
844 |
+
Clear.click(clear_conversation, outputs=[msg, chatbot])
|
845 |
+
|
846 |
+
|
847 |
+
with gr.Tab("RUN AI"):
|
848 |
+
|
849 |
+
gr.Markdown("## This section will run AI tools on your medical records and do the following\n 1. Calculate Age using Darnahi Chartit Data\n 2. Scan through your previously uploaded records once\n 3. Run Image recognition on it once\n 4. Generate Age and Sex based Recommendations using USPTF recommendations\n 5. Create summaries from your uploaded records that you can explore or download from file server tab\n 6. Create Wordclouds\n 7. Create structured and Unstructured RAG for Darnabot to use so as to tailor its answers using your uploaded chunked data. \n\n")
|
850 |
+
with gr.Row():
|
851 |
+
fetch_button = gr.Button("Fetch Age and Sex")
|
852 |
+
with gr.Column(visible=False) as analysis_column:
|
853 |
+
deidentify_words = gr.Textbox(label="Enter information to deidentify", placeholder="names|email|address|phone")
|
854 |
+
analyze_button = gr.Button("Deidentify and Analyze")
|
855 |
+
|
856 |
+
output1 = gr.Textbox(label="Age and Sex")
|
857 |
+
output2 = gr.Textbox(label="Alert")
|
858 |
+
|
859 |
+
fetch_button.click(
|
860 |
+
fn=fetch_age_sex,
|
861 |
+
inputs=[],
|
862 |
+
outputs=[output1, output2, analysis_column, analyze_button]
|
863 |
+
)
|
864 |
+
|
865 |
+
analyze_button.click(
|
866 |
+
fn=analyze,
|
867 |
+
inputs=[deidentify_words],
|
868 |
+
outputs=[output2]
|
869 |
+
)
|
870 |
+
|
871 |
+
with gr.Accordion(label="EXPLORE AI FILES)", open=False):
|
872 |
+
|
873 |
+
with gr.Row():
|
874 |
+
with gr.Row():
|
875 |
+
file_list = gr.Dropdown(label="Select a file", choices=list_files(directory))
|
876 |
+
refresh_button = gr.Button("Refresh List")
|
877 |
+
status_text = gr.Textbox(label="Database Status", interactive=False)
|
878 |
+
|
879 |
+
with gr.Row():
|
880 |
+
display_area = gr.Textbox(label="Explore Content", visible=True)
|
881 |
+
display_area2 = gr.Image(label="Image", visible=True)
|
882 |
+
|
883 |
+
|
884 |
+
file_list.change(
|
885 |
+
fn=update_display,
|
886 |
+
inputs=[file_list],
|
887 |
+
outputs=[display_area, display_area2]
|
888 |
+
)
|
889 |
+
|
890 |
+
refresh_button.click(
|
891 |
+
fn=refresh_file_list,
|
892 |
+
inputs=[],
|
893 |
+
outputs=[file_list, status_text]
|
894 |
+
)
|
895 |
+
with gr.Accordion(label="OTHER INFORMATIONAL LINKS)", open=False):
|
896 |
+
|
897 |
+
gr.HTML("""
|
898 |
+
<iframe src="https://www.uspreventiveservicestaskforce.org/webview/#!/" width="100%" height="580px"></iframe>
|
899 |
+
""")
|
900 |
+
|
901 |
+
gr.Markdown("## Are you up to date on Immunizations?\n See Immunization suggestions:")
|
902 |
+
gr.HTML("""
|
903 |
+
<iframe src="https://www2a.cdc.gov/nip/adultimmsched/#print"
|
904 |
+
width="100%" height="500px"></iframe>
|
905 |
+
""")
|
906 |
+
|
907 |
+
|
908 |
+
|
909 |
+
|
910 |
+
|
911 |
+
with gr.Tab("⛨SYMPTOM LOGGER"):
|
912 |
+
with gr.Row():
|
913 |
+
create_new = gr.Button("Create New")
|
914 |
+
fetch_previous = gr.Button("Fetch Previous")
|
915 |
+
|
916 |
+
with gr.Column(visible=False) as new_record_row:
|
917 |
+
with gr.Row():
|
918 |
+
symptom = gr.Dropdown(["pain", "rash", "diarrhea", "discharge", "wound", "other"], label="Symptom")
|
919 |
+
comment = gr.Textbox(label="Details", placeholder="Rash since 2 days with discharge")
|
920 |
+
with gr.Row():
|
921 |
+
file = gr.File(label="Attach Image (optional)")
|
922 |
+
result = gr.Textbox(label="Alert")
|
923 |
+
|
924 |
+
outputd = gr.Markdown(label="Darnabot:")
|
925 |
+
|
926 |
+
|
927 |
+
with gr.Row():
|
928 |
+
btnw = gr.Button("GENERATE")
|
929 |
+
submit_btn = gr.Button("Save")
|
930 |
+
btnw.click(symptom_note, inputs=(symptom, comment), outputs=[outputd])
|
931 |
+
|
932 |
+
|
933 |
+
|
934 |
+
|
935 |
+
with gr.Column(visible=False) as explore_records_row:
|
936 |
+
with gr.Row():
|
937 |
+
records_dropdown = gr.Dropdown(label="Select Record", choices=["No records available"])
|
938 |
+
with gr.Column():
|
939 |
+
fetch_btn = gr.Button("Refresh List")
|
940 |
+
display_btn = gr.Button("Display Selected Record")
|
941 |
+
with gr.Row():
|
942 |
+
record_display = gr.Textbox(label="Record Details")
|
943 |
+
image_display = gr.Image(label="Attached Image")
|
944 |
+
|
945 |
+
create_new.click(
|
946 |
+
toggle_visibility,
|
947 |
+
inputs=gr.Text(value="new", visible=False),
|
948 |
+
outputs=[new_record_row, explore_records_row]
|
949 |
+
)
|
950 |
+
|
951 |
+
fetch_previous.click(
|
952 |
+
toggle_visibility,
|
953 |
+
inputs=gr.Text(value="previous", visible=False),
|
954 |
+
outputs=[new_record_row, explore_records_row]
|
955 |
+
)
|
956 |
+
|
957 |
+
submit_btn.click(submit_record, inputs=[symptom, outputd, comment, file], outputs=result)
|
958 |
+
fetch_btn.click(fetch_records, outputs=records_dropdown)
|
959 |
+
display_btn.click(display_record, inputs=[records_dropdown], outputs=[record_display, image_display])
|
960 |
+
|
961 |
+
|
962 |
+
|
963 |
+
if __name__ == "__main__":
|
964 |
+
|
965 |
+
demo.launch(server_name='0.0.0.0', server_port=3012, share=False)
|
966 |
+
|
967 |
+
|
motivation.json
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"1": "Teach a man to fish and you feed him for a lifetime. - Chinese Proverb",
|
3 |
+
"2": "The only thing to fear is fear itself. - Franklin D. Roosevelt",
|
4 |
+
"3": "Life is what happens when you're busy making other plans. - John Lennon",
|
5 |
+
"4": "In the end, we only regret the chances we didn't take. - Lewis Carroll",
|
6 |
+
"5": "Success is not final, failure is not fatal: It is the courage to continue that counts. - Winston Churchill",
|
7 |
+
"6": "You miss 100% of the shots you don't take. - Wayne Gretzky",
|
8 |
+
"7": "Whether you think you can or you think you can't, you're right. - Henry Ford",
|
9 |
+
"8": "I have not failed. I've just found 10,000 ways that won't work. - Thomas A. Edison",
|
10 |
+
"9": "The future belongs to those who believe in the beauty of their dreams. - Eleanor Roosevelt",
|
11 |
+
"10": "The best time to plant a tree was 20 years ago. The second best time is now. - Chinese Proverb",
|
12 |
+
"11": "It does not matter how slowly you go as long as you do not stop. - Confucius",
|
13 |
+
"12": "Everything you've ever wanted is on the other side of fear. - George Addair",
|
14 |
+
"13": "Dream big and dare to fail. - Norman Vaughan",
|
15 |
+
"14": "The journey of a thousand miles begins with one step. - Lao Tzu",
|
16 |
+
"15": "What we think, we become. - Buddha",
|
17 |
+
"16": "The best revenge is massive success. - Frank Sinatra",
|
18 |
+
"17": "Life is 10% what happens to us and 90% how we react to it. - Charles R. Swindoll",
|
19 |
+
"18": "Be yourself; everyone else is already taken. - Oscar Wilde",
|
20 |
+
"19": "The mind is everything. What you think you become. - Buddha",
|
21 |
+
"20": "An unexamined life is not worth living. - Socrates",
|
22 |
+
"21": "Eighty percent of success is showing up. - Woody Allen",
|
23 |
+
"22": "Your time is limited, don’t waste it living someone else’s life. - Steve Jobs",
|
24 |
+
"23": "Winning isn’t everything, but wanting to win is. - Vince Lombardi",
|
25 |
+
"24": "I am not a product of my circumstances. I am a product of my decisions. - Stephen Covey",
|
26 |
+
"25": "Every child is an artist. The problem is how to remain an artist once he grows up. - Pablo Picasso",
|
27 |
+
"26": "You can never cross the ocean until you have the courage to lose sight of the shore. - Christopher Columbus",
|
28 |
+
"27": "Either you run the day, or the day runs you. - Jim Rohn",
|
29 |
+
"28": "The two most important days in your life are the day you are born and the day you find out why. - Mark Twain",
|
30 |
+
"29": "Whatever you can do, or dream you can, begin it. Boldness has genius, power and magic in it. - Johann Wolfgang von Goethe",
|
31 |
+
"30": "The best way to predict the future is to invent it. - Alan Kay",
|
32 |
+
"31": "If you want to lift yourself up, lift up someone else. - Booker T. Washington",
|
33 |
+
"32": "You miss 100% of the shots you don’t take. - Wayne Gretzky",
|
34 |
+
"33": "It is never too late to be what you might have been. - George Eliot",
|
35 |
+
"34": "A person who never made a mistake never tried anything new. - Albert Einstein",
|
36 |
+
"35": "The person who says it cannot be done should not interrupt the person who is doing it. - Chinese Proverb",
|
37 |
+
"36": "Great minds discuss ideas; average minds discuss events; small minds discuss people. - Eleanor Roosevelt",
|
38 |
+
"37": "A truly rich man is one whose children run into his arms when his hands are empty. - Unknown",
|
39 |
+
"38": "It is not what we get, but who we become, what we contribute… that gives meaning to our lives. - Tony Robbins",
|
40 |
+
"39": "The best and most beautiful things in the world cannot be seen or even touched - they must be felt with the heart. - Helen Keller",
|
41 |
+
"40": "Happiness is not something readymade. It comes from your own actions. - Dalai Lama",
|
42 |
+
"41": "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough. - Oprah Winfrey",
|
43 |
+
"42": "Remember that not getting what you want is sometimes a wonderful stroke of luck. - Dalai Lama",
|
44 |
+
"43": "The only way to do great work is to love what you do. - Steve Jobs",
|
45 |
+
"44": "If you can't explain it simply, you don't understand it well enough. - Albert Einstein",
|
46 |
+
"45": "Believe you can and you're halfway there. - Theodore Roosevelt",
|
47 |
+
"46": "Everything you've ever wanted is on the other side of fear. - George Addair",
|
48 |
+
"47": "Start where you are. Use what you have. Do what you can. - Arthur Ashe",
|
49 |
+
"48": "Fall seven times and stand up eight. - Japanese Proverb",
|
50 |
+
"49": "When I let go of what I am, I become what I might be. - Lao Tzu",
|
51 |
+
"50": "Life is not measured by the number of breaths we take, but by the moments that take our breath away. - Maya Angelou",
|
52 |
+
"51": "Happiness is not by chance, but by choice. - Jim Rohn",
|
53 |
+
"52": "Life is really simple, but we insist on making it complicated. - Confucius",
|
54 |
+
"53": "Life is a succession of lessons which must be lived to be understood. - Ralph Waldo Emerson",
|
55 |
+
"54": "Not all those who wander are lost. - J.R.R. Tolkien",
|
56 |
+
"55": "You only live once, but if you do it right, once is enough. - Mae West",
|
57 |
+
"56": "The only impossible journey is the one you never begin. - Tony Robbins",
|
58 |
+
"57": "Go confidently in the direction of your dreams! Live the life you've imagined. - Henry David Thoreau",
|
59 |
+
"58": "Life is what we make it, always has been, always will be. - Grandma Moses",
|
60 |
+
"59": "You have brains in your head. You have feet in your shoes. You can steer yourself any direction you choose. - Dr. Seuss",
|
61 |
+
"60": "Too many of us are not living our dreams because we are living our fears. - Les Brown",
|
62 |
+
"61": "I would rather die of passion than of boredom. - Vincent van Gogh",
|
63 |
+
"62": "A man is but the product of his thoughts. What he thinks, he becomes. - Mahatma Gandhi",
|
64 |
+
"63": "Every moment is a fresh beginning. - T.S. Eliot",
|
65 |
+
"64": "I attribute my success to this: I never gave or took any excuse. - Florence Nightingale",
|
66 |
+
"65": "The most difficult thing is the decision to act, the rest is merely tenacity. - Amelia Earhart",
|
67 |
+
"66": "Every strike brings me closer to the next home run. - Babe Ruth",
|
68 |
+
"67": "Life is 10% what happens to me and 90% of how I react to it. - Charles Swindoll",
|
69 |
+
"68": "To succeed in life, you need two things: ignorance and confidence. - Mark Twain",
|
70 |
+
"69": "Only put off until tomorrow what you are willing to die having left undone. - Pablo Picasso",
|
71 |
+
"70": "The two most powerful warriors are patience and time. - Leo Tolstoy",
|
72 |
+
"71": "The only limit to our realization of tomorrow will be our doubts of today. - Franklin D. Roosevelt",
|
73 |
+
"72": "Speak less than you know; have more than you show. - William Shakespeare",
|
74 |
+
"73": "Do not go where the path may lead, go instead where there is no path and leave a trail. - Ralph Waldo Emerson",
|
75 |
+
"74": "The only way to have a friend is to be one. - Ralph Waldo Emerson",
|
76 |
+
"75": "The only person you are destined to become is the person you decide to be. - Ralph Waldo Emerson",
|
77 |
+
"76": "Go for it now. The future is promised to no one. - Wayne Dyer",
|
78 |
+
"77": "Don’t count the days, make the days count. - Muhammad Ali",
|
79 |
+
"78": "Change your thoughts and you change your world. - Norman Vincent Peale",
|
80 |
+
"79": "Strive not to be a success, but rather to be of value. - Albert Einstein",
|
81 |
+
"80": "Two roads diverged in a wood, and I—I took the one less traveled by, And that has made all the difference. - Robert Frost",
|
82 |
+
"81": "I am not a product of my circumstances. I am a product of my decisions. - Stephen Covey",
|
83 |
+
"82": "When everything seems to be going against you, remember that the airplane takes off against the wind, not with it. - Henry Ford",
|
84 |
+
"83": "It’s not the years in your life that count. It’s the life in your years. - Abraham Lincoln",
|
85 |
+
"84": "Change your life today. Don’t gamble on the future, act now, without delay. - Simone de Beauvoir",
|
86 |
+
"85": "Life shrinks or expands in proportion to one's courage. - Anaïs Nin",
|
87 |
+
"86": "If you want to live a happy life, tie it to a goal, not to people or things. - Albert Einstein",
|
88 |
+
"87": "Never let the fear of striking out keep you from playing the game. - Babe Ruth",
|
89 |
+
"88": "Money and success don’t change people; they merely amplify what is already there. - Will Smith",
|
90 |
+
"89": "Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma – which is living with the results of other people’s thinking. - Steve Jobs",
|
91 |
+
"90": "Not how long, but how well you have lived is the main thing. - Seneca",
|
92 |
+
"91": "If life were predictable it would cease to be life, and be without flavor. - Eleanor Roosevelt",
|
93 |
+
"92": "The whole secret of a successful life is to find out what is one's destiny to do, and then do it. - Henry Ford",
|
94 |
+
"93": "In order to write about life first you must live it. - Ernest Hemingway",
|
95 |
+
"94": "The big lesson in life, baby, is never be scared of anyone or anything. - Frank Sinatra",
|
96 |
+
"95": "Curiosity about life in all of its aspects, I think, is still the secret of great creative people. - Leo Burnett",
|
97 |
+
"96": "Life is not a problem to be solved, but a reality to be experienced. - Søren Kierkegaard",
|
98 |
+
"97": "The unexamined life is not worth living. - Socrates",
|
99 |
+
"98": "Turn your wounds into wisdom. - Oprah Winfrey",
|
100 |
+
"99": "The way to get started is to quit talking and begin doing. - Walt Disney",
|
101 |
+
"100": "The purpose of our lives is to be happy. - Dalai Lama"
|
102 |
+
}
|
103 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pip-tools
|
2 |
+
requests
|
3 |
+
gradio
|
4 |
+
chromadb
|
5 |
+
ollama
|
6 |
+
Pillow
|
7 |
+
reportlab
|
8 |
+
unidecode
|
9 |
+
fpdf
|
10 |
+
|