Spaces:
Sleeping
Sleeping
File size: 9,403 Bytes
9b5b26a c19d193 6aae614 cde070e 0ebfe01 4d87c5c 24a7fc2 9b5b26a 363bdbd 9b5b26a 5fdabc0 e633fef 84ba017 5e39015 1704348 9b5b26a 588ed58 54f78b6 cb6a5cb 54f78b6 cb6a5cb 84ba017 1704348 84ba017 1704348 622c19c 1704348 a50a85b 1704348 6ca77e6 4d87c5c 622c19c a38f356 5fdabc0 622c19c 113eccf 9b5b26a f344a77 73429d3 f344a77 dbdf25d 6c1dedd fd8c72f 6c1dedd cfdd778 6c1dedd 4d87c5c 9b5b26a 8c01ffb b6fc528 8c01ffb 6aae614 a0b5179 b2124c6 a0b5179 f45e7d5 8c01ffb 9b5b26a 8c01ffb 861422e 9b5b26a 8c01ffb 8fe992b 73429d3 8c01ffb 861422e 8fe992b 9b5b26a 8c01ffb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | 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() |