Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
2225176
Update README.md
YashSonar20 Jan 23, 2025
37ece12
Update README.md
leiliani Jan 23, 2025
0685cab
Created using Colab
YashSonar20 Jan 23, 2025
acb5dbd
Created using Colab
YashSonar20 Jan 23, 2025
228035b
Delete BNFO301_Lab2_StudentVersion_2025.ipynb
YashSonar20 Jan 23, 2025
4457636
Update README.md
YashSonar20 Jan 28, 2025
5a2c7c6
Added report.qmd
YashSonar20 Feb 21, 2025
6afbee6
formatting
leiliani Feb 27, 2025
3b8b1d1
specifications
leiliani Feb 27, 2025
cebdafb
specifications
leiliani Feb 27, 2025
95db8b4
report changes
leiliani Mar 1, 2025
22e0f8e
introduction
leiliani Mar 1, 2025
07b3040
intro edits
leiliani Mar 1, 2025
7b7503d
formatting
leiliani Mar 1, 2025
40d8173
edits
leiliani Mar 1, 2025
2f1bd5c
html
leiliani Mar 1, 2025
d258ea1
link edit
leiliani Mar 1, 2025
4696a83
AI Tools
leiliani Mar 2, 2025
ab012c4
Final Edits
leiliani Mar 2, 2025
79e5a59
PDF file
leiliani Mar 2, 2025
bca9883
Create report2.qmd
leiliani Mar 11, 2025
6946140
Rename report2.qmd to AI_Software_Design_Report.qmd
leiliani Mar 11, 2025
26aacb0
Scaffold
leiliani Mar 11, 2025
2659805
Edits
leiliani Mar 12, 2025
e51446f
Created using Colab
YashSonar20 Mar 26, 2025
6e5e3f2
added function to normalize names before comparing them
yang-thomas Mar 26, 2025
5d9c3e3
fixed how normalizename func is called in analyze_interaction
yang-thomas Mar 26, 2025
e42630c
cross-referencing w/ openFDA database
yang-thomas Mar 27, 2025
8ad138d
Update CMSC_355_Deliverable_3_test_code.ipynb
ayushpurankar200 Apr 9, 2025
e4447b1
Create test.txt
yang-thomas Apr 16, 2025
79cb527
frontend
yang-thomas Apr 16, 2025
c1c1ff4
Create test2.txt
yang-thomas Apr 16, 2025
4014e02
Delete AiMedTrackApp directory
yang-thomas Apr 16, 2025
80b1af6
created directory for main project
yang-thomas Apr 16, 2025
8b97a86
Add files via upload
yang-thomas Apr 16, 2025
b27d3e7
Create text.txt
yang-thomas Apr 16, 2025
3fe691a
Merge branch 'deHank:main' into main
YashSonar20 Apr 26, 2025
1aefa61
Merge pull request #1 from ayushpurankar200/patch-1
YashSonar20 Apr 26, 2025
de8ae83
Update README.md
YashSonar20 Apr 26, 2025
1351b5e
Update README.md
YashSonar20 Apr 26, 2025
f1f9494
readme edits
leiliani Apr 26, 2025
2a0ce4b
edits
leiliani Apr 26, 2025
b3309cf
readme edits
leiliani Apr 26, 2025
eba99d8
slides link
leiliani Apr 26, 2025
b3717dc
readme edits
leiliani Apr 27, 2025
bdc7af9
readme edits
leiliani Apr 27, 2025
9b52bc3
readme edits
leiliani Apr 27, 2025
d237aa2
Add files via upload
yang-thomas Apr 27, 2025
92f3f17
Add files via upload
yang-thomas Apr 27, 2025
b5a5078
readme edits
leiliani Apr 27, 2025
729e4b3
readme edit
leiliani Apr 27, 2025
73ce184
readme edit
leiliani Apr 27, 2025
9248f9f
readme edits
leiliani Apr 27, 2025
998677d
readme
leiliani Apr 27, 2025
e27add0
Add files via upload
leiliani Apr 27, 2025
84f4ba2
Update README.md
YashSonar20 Apr 27, 2025
8d4692d
readme edits
leiliani Apr 27, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
136 changes: 136 additions & 0 deletions AiMedTracker/backend/ai_funcs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# ai code - openrouter

import requests
import json
import os
import traceback
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Get API key from environment variable
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
OPENROUTER_API_URL = "https://openrouter.ai/api/v1/chat/completions"

def generate_llm_response(prompt, model="openai/gpt-3.5-turbo"):
"""
Generate a response using the OpenRouter API.

Args:
prompt (str): The input prompt for the LLM
model (str): The model to use (default: openai/gpt-3.5-turbo)

Returns:
str: The generated response
"""
if not OPENROUTER_API_KEY:
print("Error: OPENROUTER_API_KEY environment variable not set")
return "Error: API key not configured. Please contact support."

headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"HTTP-Referer": "https://github.com/your-username/AiInteractionApp",
"X-Title": "AI Drug Interaction App",
"Content-Type": "application/json"
}

data = {
"model": model,
"messages": [
{"role": "system", "content": "You are a helpful AI assistant that provides information about drug interactions and medications."},
{"role": "user", "content": prompt}
],
"temperature": 0.7,
"max_tokens": 1000,
"timeout": 120
}

try:
print(f"Sending prompt to OpenRouter API: {prompt[:200]}...")
print(f"Using model: {model}")

response = requests.post(
OPENROUTER_API_URL,
headers=headers,
json=data,
timeout=120
)

if response.status_code != 200:
error_msg = f"API Error: {response.status_code} - {response.text}"
print(error_msg)
return f"Error analyzing interaction: {error_msg}"

response_json = response.json()

if "choices" not in response_json or not response_json["choices"]:
print("No choices in response")
return "Error: No response from AI model. Please try again."

result = response_json["choices"][0]["message"]["content"]
print(f"Received response from OpenRouter API: {result[:200]}...")
return result

except requests.exceptions.Timeout:
print("Request timed out after 120 seconds")
return "Error: The AI model is taking longer than expected to respond. Please try again in a few moments."
except requests.exceptions.RequestException as e:
print(f"Request error: {str(e)}")
return f"Error: Could not connect to AI service. Please try again."
except Exception as e:
print(f"Unexpected error: {str(e)}")
print(f"Full traceback: {traceback.format_exc()}")
return "Error: An unexpected error occurred. Please try again."

def analyze_interaction(med1, med2):
"""
Use LLM to analyze potential interactions between two medications.

Args:
med1 (str): First medication name
med2 (str): Second medication name

Returns:
str: Analysis of potential interactions
"""
prompt = f"""Analyze the potential interactions between {med1} and {med2}.

Consider:
1. Common side effects when taken together
2. Potential drug interactions and their severity
3. Contraindications or warnings
4. Recommendations for patients taking both medications

Provide a concise, patient-friendly summary that explains:
- The main interaction concern
- Key warnings or precautions
- What patients should do if they're taking both medications

Format the response in a clear, easy-to-read manner with bullet points where appropriate.
Keep the response brief but informative."""

return generate_llm_response(prompt)

def get_medication_info(medication):
"""
Use LLM to get detailed information about a medication.

Args:
medication (str): Medication name

Returns:
str: Detailed information about the medication
"""
prompt = f"""Provide detailed information about {medication}.
Include:
1. Common uses
2. Typical dosage
3. Common side effects
4. Important warnings
5. Drug interactions

Format the response in a clear, easy-to-read manner."""

return generate_llm_response(prompt)

11 changes: 11 additions & 0 deletions AiMedTracker/backend/data/users.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"users": {
"u1": {
"email": "pat@example.com",
"password": "pass123",
"type": "patient",
"name": "Thomas Yang",
"medications": []
}
}
}
207 changes: 207 additions & 0 deletions AiMedTracker/backend/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,207 @@
from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import os
import requests
from user_funcs import create_user, verify_user, get_user, update_user, delete_user
from ai_funcs import analyze_interaction, get_medication_info

app = Flask(__name__)
CORS(app) # This allows your React frontend to make requests to this backend


def normalize_name(name):
return name.strip().lower()

def check_name(medication):
"""
Check if a medication exists in the FDA database and return information.
"""
medication = medication.strip().lower()
print(f"Checking medication: {medication}")

# Search for both generic and brand names
url = f"https://api.fda.gov/drug/label.json?search=openfda.generic_name:{medication}+OR+openfda.brand_name:{medication}&limit=1"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()

if "results" not in data or len(data["results"]) == 0:
print(f"Medication not found: {medication}")
return medication.capitalize() + " not found."

result = data["results"][0]
openfda = result.get("openfda", {})

# Get medication names
generic_names = openfda.get("generic_name", [])
brand_names = openfda.get("brand_name", [])

generic_name = generic_names[0] if generic_names else medication
brand_name = brand_names[0] if brand_names else ""

# Build response message
info = f"{generic_name.capitalize()} found."
if brand_name and brand_name.lower() != generic_name.lower():
info += f" Brand name: {brand_name}."

print(f"Medication found: {info}")
return info

except Exception as e:
print(f"Error checking FDA database: {str(e)}")
return medication.capitalize() + " not found (Error)."

def check_if_medication_exists(medication):
"""Simple helper function to check if a medication exists in the FDA database"""
medication = medication.strip().lower()
url = f"https://api.fda.gov/drug/label.json?search=openfda.generic_name:{medication}+OR+openfda.brand_name:{medication}&limit=1"
try:
response = requests.get(url)
if response.status_code != 200:
print(f"FDA API error: {response.status_code}")
return False

data = response.json()
if "results" not in data:
print("No results field in FDA API response")
return False

exists = len(data["results"]) > 0
print(f"Medication {medication} {'exists' if exists else 'does not exist'} in FDA database")
return exists
except Exception as e:
print(f"Error checking FDA database: {str(e)}")
return False


@app.route('/api/check-interaction', methods=['POST'])
def check_interaction():
data = request.get_json()
med1 = data.get('medication1', '').strip()
med2 = data.get('medication2', '').strip()

if not med1 or not med2:
return jsonify({'success': False, 'message': 'Both medications are required'})

# First check if medications exist in FDA database
med1_exists = check_if_medication_exists(med1)
med2_exists = check_if_medication_exists(med2)

if not med1_exists or not med2_exists:
return jsonify({
'success': False,
'message': 'One or both medications not found in FDA database'
})

# Use LLM to analyze the interaction
analysis = analyze_interaction(med1, med2)
print(f"AI Analysis result: {analysis}")

# Check if the analysis starts with "Error:" to indicate an error message
if analysis and analysis.startswith("Error:"):
return jsonify({
'success': False,
'message': analysis
})

if not analysis:
return jsonify({
'success': False,
'message': 'Error analyzing medication interaction'
})

# Return the analysis with success status
response = {
'success': True,
'message': 'Interaction analysis completed',
'analysis': analysis
}
print(f"Sending response: {response}")
return jsonify(response)


@app.route('/api/check-medication', methods=['POST'])
def check_medication():
data = request.json
medication = data.get('medicationName')

if not medication:
return jsonify({
"success": False,
"error": "Medication name is required"
}), 400

print(f"Received medication check request for: {medication}")
result = check_name(medication)

# Check if the result contains "not found" to determine if the medication exists
exists = "not found" not in result.lower()

response = {
"success": True,
"exists": exists,
"message": result
}

print(f"Sending response: {response}")
return jsonify(response)

@app.route('/api/signup', methods=['POST'])
def signup():
try:
data = request.get_json()
user = create_user(data)
return jsonify({"success": True, "user": user}), 201
except ValueError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
return jsonify({"success": False, "error": "An error occurred during signup"}), 500

@app.route('/api/login', methods=['POST'])
def login():
try:
data = request.get_json()
user = verify_user(data['email'], data['password'])
if user:
return jsonify({"success": True, "user": user}), 200
return jsonify({"success": False, "error": "Invalid credentials"}), 401
except Exception as e:
return jsonify({"success": False, "error": "An error occurred during login"}), 500

@app.route('/api/user/<email>', methods=['GET'])
def get_user_profile(email):
try:
user = get_user(email)
if user:
# Remove password from response
user_copy = user.copy()
user_copy.pop('password', None)
return jsonify({"success": True, "user": user_copy}), 200
return jsonify({"success": False, "error": "User not found"}), 404
except Exception as e:
return jsonify({"success": False, "error": "An error occurred"}), 500

@app.route('/api/user/<email>', methods=['PUT'])
def update_user_profile(email):
try:
data = request.get_json()
user = update_user(email, data)
return jsonify({"success": True, "user": user}), 200
except ValueError as e:
return jsonify({"success": False, "error": str(e)}), 400
except Exception as e:
return jsonify({"success": False, "error": "An error occurred"}), 500

@app.route('/api/user/<email>', methods=['DELETE'])
def delete_user_profile(email):
try:
if delete_user(email):
return jsonify({"success": True}), 200
return jsonify({"success": False, "error": "User not found"}), 404
except Exception as e:
return jsonify({"success": False, "error": "An error occurred"}), 500

if __name__ == '__main__':
app.run(debug=True, port=5001)
4 changes: 4 additions & 0 deletions AiMedTracker/backend/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
flask==3.0.2
flask-cors==4.0.0
requests==2.31.0
python-dotenv==1.0.0
1 change: 1 addition & 0 deletions AiMedTracker/backend/text.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

Loading