visproj's picture
Update app.py
dbdf25d verified
from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
import datetime
import requests
import pytz
import yaml
from tools.final_answer import FinalAnswerTool
from huggingface_hub import login
import os
from pytrends.request import TrendReq
import pandas as pd
from Gradio_UI import GradioUI
from typing import Optional, Dict, Any
def get_rxcui(drug_name: str) -> str:
"""Fetches the RxCUI (RxNorm Concept Unique Identifier) for a given drug name."""
url = f"https://rxnav.nlm.nih.gov/REST/rxcui.json?name={drug_name}&search=1"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
if "idGroup" in data and "rxnormId" in data["idGroup"]:
return data["idGroup"]["rxnormId"][0] # Return first RxCUI
return None # Return None if RxCUI is not found
def get_drug_interactions(rxcui: str) -> list:
"""Fetches all known drug interactions for a given RxCUI."""
url = f"https://rxnav.nlm.nih.gov/REST/interaction/interaction.json?rxcui={rxcui}"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
interactions = []
if "interactionTypeGroup" in data:
for group in data["interactionTypeGroup"]:
for interaction in group.get("interactionType", []):
for pair in interaction.get("interactionPair", []):
interacting_rxcuis = [concept["minConceptItem"]["rxcui"] for concept in pair.get("interactionConcept", [])]
interactions.append((interacting_rxcuis, pair.get("description", "No description available")))
return interactions
return None # Return None if no interaction data is found
@tool
def drug_interaction_checker(drug_1: str, drug_2: str) -> str:
"""Checks for potential interactions between two medications using the NLM Interaction API.
Args:
drug_1: The name of the first drug.
drug_2: The name of the second drug.
"""
rxcui_1 = get_rxcui(drug_1)
rxcui_2 = get_rxcui(drug_2)
if not rxcui_1 or not rxcui_2:
return "❌ Could not find RxCUI for one or both drugs."
# Get interactions for both drugs
interactions_1 = get_drug_interactions(rxcui_1)
interactions_2 = get_drug_interactions(rxcui_2)
# Check if drug_2's RxCUI appears in drug_1's interaction list
if interactions_1:
for interacting_rxcuis, description in interactions_1:
if rxcui_2 in interacting_rxcuis:
return f"⚠️ Drug Interaction Warning: {description}"
# Check if drug_1's RxCUI appears in drug_2's interaction list (redundancy check)
if interactions_2:
for interacting_rxcuis, description in interactions_2:
if rxcui_1 in interacting_rxcuis:
return f"⚠️ Drug Interaction Warning: {description}"
return "✅ No significant interaction found for these drugs."
@tool
def market_trend_analyzer(product_keyword: str) -> str:
"""Analyzes market trends for a given product keyword using Google Trends and Statista.
Args:
product_keyword: The product or keyword to analyze.
"""
try:
# Google Trends analysis
pytrends = TrendReq(hl='en-US', tz=360)
pytrends.build_payload([product_keyword], timeframe='today 12-m')
interest_over_time = pytrends.interest_over_time()
# Calculate trend metrics
current_interest = interest_over_time[product_keyword].iloc[-1]
avg_interest = interest_over_time[product_keyword].mean()
trend_direction = "Increasing" if current_interest > avg_interest else "Decreasing"
# Statista data (you'd need to replace this with actual API calls if available)
statista_url = f"https://www.statista.com/search/?q={product_keyword}&Search=&qKat=search"
statista_response = requests.get(statista_url)
statista_data = f"Statista search results: {statista_url}"
# Compile report
report = f"Market Trend Analysis for '{product_keyword}':\n\n"
report += f"Google Trends:\n"
report += f"- Current Interest: {current_interest:.2f}\n"
report += f"- Average Interest (12 months): {avg_interest:.2f}\n"
report += f"- Trend Direction: {trend_direction}\n\n"
report += f"Statista Data:\n{statista_data}\n"
return report
except Exception as e:
return f"❌ Error analyzing market trends: {str(e)}"
@tool
def sig_expander(sig: str) -> str:
"""Expands a prescription SIG shorthand into human-readable patient instructions.
Args:
sig: A prescription instruction in shorthand (e.g., '1 tab po qd').
"""
sig_map = {
"1 tab po qd": "Take 1 tablet by mouth once daily.",
"1 tab po bid": "Take 1 tablet by mouth twice daily.",
"1 tab po tid": "Take 1 tablet by mouth three times daily.",
"1 tab po qid": "Take 1 tablet by mouth four times daily.",
"1 tab po prn": "Take 1 tablet by mouth as needed.",
"1 tab po q12h": "Take 1 tablet by mouth every 12 hours.",
"1 tab po q8h": "Take 1 tablet by mouth every 8 hours.",
"2 tab po qd": "Take 2 tablets by mouth once daily."
}
return sig_map.get(sig.lower(), "❌ No direct match found. Please clarify.")
@tool
def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
#Keep this format for the description / args / args description but feel free to modify the tool
"""A tool that does nothing yet
Args:
arg1: the first argument
arg2: the second argument
"""
return "What magic will you build ?"
@tool
def healthcare_software_trend_analyzer(product_keyword: str, timeframe: str = 'today 5-y', geo: str = '') -> str:
"""Analyzes market trends for healthcare software products using Google Trends.
Args:
product_keyword: The healthcare software product or category to analyze.
timeframe: The time range for analysis (default: 'today 5-y' for 5 years).
geo: Geographic region for analysis (default: '' for worldwide).
"""
HEALTHCARE_SOFTWARE_CATEGORIES = [
"Electronic Health Records", "Telemedicine", "Healthcare Analytics",
"Medical Billing Software", "Practice Management Software",
"Remote Patient Monitoring", "Healthcare CRM", "Medical Imaging Software","Sig", "Patient Instructions"
]
try:
# Suggest category if not in list
if product_keyword not in HEALTHCARE_SOFTWARE_CATEGORIES:
suggestion = f"\nNote: '{product_keyword}' is not in our list of common healthcare software categories. Consider using one of these: {', '.join(HEALTHCARE_SOFTWARE_CATEGORIES)}\n"
else:
suggestion = ""
# Google Trends analysis
pytrends = TrendReq(hl='en-US', tz=360)
pytrends.build_payload([product_keyword], timeframe=timeframe, geo=geo)
interest_over_time = pytrends.interest_over_time()
# Calculate trend metrics
current_interest = interest_over_time[product_keyword].iloc[-1]
avg_interest = interest_over_time[product_keyword].mean()
trend_direction = "Increasing" if current_interest > avg_interest else "Decreasing"
# Compile report
report = f"Healthcare Software Market Trend Analysis for '{product_keyword}':\n"
report += f"Timeframe: {timeframe}\n"
report += f"Region: {geo if geo else 'Worldwide'}\n\n"
report += f"Google Trends Analysis:\n"
report += f"- Current Interest: {current_interest:.2f}\n"
report += f"- Average Interest: {avg_interest:.2f}\n"
report += f"- Trend Direction: {trend_direction}\n"
report += suggestion
return report
except Exception as e:
return f"❌ Error analyzing healthcare software market trends: {str(e)}"
@tool
def get_current_time_in_timezone(timezone: str) -> str:
"""A tool that fetches the current local time in a specified timezone.
Args:
timezone: A string representing a valid timezone (e.g., 'America/New_York').
"""
try:
# Create timezone object
tz = pytz.timezone(timezone)
# Get current time in that timezone
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
return f"The current local time in {timezone} is: {local_time}"
except Exception as e:
return f"Error fetching time for timezone '{timezone}': {str(e)}"
login(os.environ["HF_TOKEN"])
final_answer = FinalAnswerTool()
model = HfApiModel(
max_tokens=2096,
temperature=0.5,
model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
custom_role_conversions=None,
)
# Import tool from Hub
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
with open("prompts.yaml", 'r') as stream:
prompt_templates = yaml.safe_load(stream)
agent = CodeAgent(
model=model,
tools=[final_answer, healthcare_software_trend_analyzer], ## add your tools here (don't remove final answer)
max_steps=6,
verbosity_level=1,
grammar=None,
planning_interval=None,
name=None,
description=None,
prompt_templates=prompt_templates
)
GradioUI(agent).launch()