Update app.py
Browse files
app.py
CHANGED
@@ -1,137 +1,42 @@
|
|
1 |
-
|
2 |
-
import
|
3 |
-
import requests
|
4 |
-
import pytz
|
5 |
-
import yaml
|
6 |
-
from tools.final_answer import FinalAnswerTool
|
7 |
-
from playwright.sync_api import sync_playwright
|
8 |
-
from bs4 import BeautifulSoup
|
9 |
-
import pandas as pd
|
10 |
-
import time
|
11 |
-
|
12 |
-
from Gradio_UI import GradioUI
|
13 |
-
|
14 |
-
# Below is an example of a tool that does nothing. Amaze us with your creativity !
|
15 |
-
@tool
|
16 |
-
def scrape_drug_reviews(drug:str)-> str: #it's import to specify the return type
|
17 |
-
#Keep this format for the description / args / args description but feel free to modify the tool
|
18 |
-
"""A tool that calls a scraping function on the drugs.com website to scrape for reviews on target dtug specified in input
|
19 |
-
Args:
|
20 |
-
drug: the name of the target drug we want to retrieve reviews for, in lower case (e.g. 'flecainide')
|
21 |
-
|
22 |
-
"""
|
23 |
-
try:
|
24 |
-
data = scrape_drugs_com_reviews(drug)
|
25 |
-
# Get current time in that timezone
|
26 |
-
return data.to_string()
|
27 |
-
except Exception as e:
|
28 |
-
return f"Error fetching reviews for the target drug you provided: '{drug}'"
|
29 |
-
|
30 |
-
|
31 |
-
async def scrape_drugs_com_reviews(drug_name, max_pages=3, delay=2):
|
32 |
-
"""
|
33 |
-
Scrapes user reviews from Drugs.com for a given drug.
|
34 |
-
"""
|
35 |
-
base_url = f"https://www.drugs.com/comments/{drug_name}/"
|
36 |
-
all_reviews = []
|
37 |
-
|
38 |
-
async with async_playwright() as p:
|
39 |
-
browser = await p.chromium.launch(headless=False)
|
40 |
-
context = await browser.new_context(
|
41 |
-
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121 Safari/537.36",
|
42 |
-
locale="en-US",
|
43 |
-
viewport={'width': 1280, 'height': 800},
|
44 |
-
device_scale_factor=1,
|
45 |
-
is_mobile=False,
|
46 |
-
has_touch=False
|
47 |
-
)
|
48 |
-
page = await context.new_page()
|
49 |
-
|
50 |
-
for page_num in range(1, max_pages + 1):
|
51 |
-
url = base_url if page_num == 1 else f"{base_url}?page={page_num}"
|
52 |
-
print(f"Scraping: {url}")
|
53 |
-
await page.goto(url, timeout=60000)
|
54 |
-
await asyncio.sleep(delay) # Give page some time to load
|
55 |
-
|
56 |
-
html = await page.content()
|
57 |
-
await asyncio.sleep(delay) # Give page some time to load
|
58 |
-
soup = BeautifulSoup(html, 'html.parser')
|
59 |
-
print(soup)
|
60 |
-
review_blocks = soup.find_all('div', class_='ddc-comment ddc-box ddc-mgb-2')
|
61 |
-
|
62 |
-
if not review_blocks:
|
63 |
-
print("No reviews found on this page.")
|
64 |
-
break
|
65 |
-
|
66 |
-
for block in review_blocks:
|
67 |
-
review_paragraph = block.find('p')
|
68 |
-
if review_paragraph:
|
69 |
-
# Remove the <b> tag from the paragraph to isolate the review text
|
70 |
-
if review_paragraph.b:
|
71 |
-
review_paragraph.b.extract() # Removes <b> so it doesn't show up in the text
|
72 |
-
# Get the cleaned text
|
73 |
-
review_text = review_paragraph.get_text(strip=True)
|
74 |
-
|
75 |
-
|
76 |
-
all_reviews.append({
|
77 |
-
|
78 |
-
"review": review_text if review_text else None,
|
79 |
-
"source": url
|
80 |
-
})
|
81 |
-
|
82 |
-
await asyncio.sleep(delay)
|
83 |
-
|
84 |
-
await browser.close()
|
85 |
-
return pd.DataFrame(all_reviews)
|
86 |
|
87 |
|
|
|
88 |
|
89 |
-
@tool
|
90 |
-
def get_current_time_in_timezone(timezone: str) -> str:
|
91 |
-
"""A tool that fetches the current local time in a specified timezone.
|
92 |
-
Args:
|
93 |
-
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
94 |
-
"""
|
95 |
-
try:
|
96 |
-
# Create timezone object
|
97 |
-
tz = pytz.timezone(timezone)
|
98 |
-
# Get current time in that timezone
|
99 |
-
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
100 |
-
return f"The current local time in {timezone} is: {local_time}"
|
101 |
-
except Exception as e:
|
102 |
-
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
103 |
|
104 |
|
105 |
final_answer = FinalAnswerTool()
|
106 |
|
107 |
-
#
|
108 |
-
|
109 |
|
110 |
-
model = HfApiModel(
|
111 |
-
max_tokens=2096,
|
112 |
-
temperature=0.5,
|
113 |
-
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
|
114 |
-
custom_role_conversions=None,
|
115 |
-
)
|
116 |
|
|
|
|
|
|
|
117 |
|
118 |
-
#
|
119 |
-
|
|
|
|
|
|
|
120 |
|
121 |
-
with open("prompts.yaml", 'r') as stream:
|
122 |
-
prompt_templates = yaml.safe_load(stream)
|
123 |
|
124 |
-
agent = CodeAgent(
|
125 |
-
model=model,
|
126 |
-
tools=[scrape_drug_reviews,final_answer], ## add your tools here (don't remove final answer)
|
127 |
-
max_steps=6,
|
128 |
-
verbosity_level=1,
|
129 |
-
grammar=None,
|
130 |
-
planning_interval=None,
|
131 |
-
name=None,
|
132 |
-
description=None,
|
133 |
-
prompt_templates=prompt_templates
|
134 |
-
)
|
135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
|
137 |
-
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
|
5 |
+
from Gradio_UI import GradioUI
|
6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
|
9 |
final_answer = FinalAnswerTool()
|
10 |
|
11 |
+
# Load your fine-tuned model from Hugging Face Hub
|
12 |
+
model = pipeline("text2text-generation", model='unica/CLiMA') # Replace with your actual model repo name
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# Define your prompt template (customize as needed)
|
16 |
+
def format_prompt(user_input):
|
17 |
+
return f"Identify causal relations in the following clinical narrative:\n\n{user_input}\n\nCausal relations:" # Modify if your model uses a different template
|
18 |
|
19 |
+
# Define prediction function
|
20 |
+
def generate_relations(text):
|
21 |
+
prompt = format_prompt(text)
|
22 |
+
result = model(prompt, max_length=512, do_sample=False)
|
23 |
+
return result[0]['generated_text']
|
24 |
|
|
|
|
|
25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
# Gradio interface
|
28 |
+
demo = gr.Interface(
|
29 |
+
fn=generate_relations,
|
30 |
+
inputs=gr.Textbox(lines=10, label="Clinical Note or Drug Review Text"),
|
31 |
+
outputs=gr.Textbox(label="Extracted Causal Relations"),
|
32 |
+
title="Causal Relation Extractor with MedLlama",
|
33 |
+
description="Paste your clinical note or drug review. This AI agent extracts drug-condition or symptom causal relations using a fine-tuned LLM.",
|
34 |
+
examples=[
|
35 |
+
["Patient reported severe headaches after starting amitriptyline."],
|
36 |
+
["Lisinopril helped reduce the patient's blood pressure but caused persistent cough."],
|
37 |
+
["After using Metformin, the patient experienced gastrointestinal discomfort."]
|
38 |
+
]
|
39 |
+
)
|
40 |
|
41 |
+
# Launch the app
|
42 |
+
demo.launch()
|