Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
23 changes: 23 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Git ignore for Freakquency Streamlit app

# Python caches and bytecode
__pycache__/
*.py[cod]

# Virtual environments
.venv/
venv/
env/

# Jupyter checkpoints
.ipynb_checkpoints/

# VS Code settings
.vscode/

# dotenv secret file
.env

# OS files
.DS_Store
Thumbs.db
Binary file added Freakquency (2).pptx
Binary file not shown.
81 changes: 81 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# Freakquency — Disease Risk Prediction & AI Recommendations

This repository contains a Streamlit web app that predicts a user's risk category for chronic diseases based on a short questionnaire and then provides AI-generated lifestyle recommendations. The app also includes a small rule-based chatbot for quick health tips.

Working Figma Prototype: https://www.figma.com/proto/6WYEfSgLrciKueygaTbeCf/freakquency?type=design&node-id=1-8950&t=Hj6XFSN527rUBWYw-0&scaling=scale-down&page-id=0%3A1&starting-point-node-id=1%3A8950

## What it does
- Collects user inputs (age, gender, BMI, blood pressure, cholesterol, glucose, physical activity, smoking, alcohol intake, family history).
- Uses a pre-trained machine learning model (`model.pkl`) and a pre-fitted scaler (`scaler.pkl`) to predict one of several disease categories (e.g., Healthy, Diabetes, Cardiovascular Disorder, Cancer, Multi-condition Cases).
- Sends a short prompt to OpenAI to generate 3 practical lifestyle recommendations based on the predicted disease category.
- Provides a minimal keyword-based chatbot for quick answers about exercise, diet, blood pressure, cholesterol, and glucose.

## Files of interest
- `app.py` — Streamlit application entrypoint.
- `model.pkl` — Trained scikit-learn model used for prediction.
- `scaler.pkl` — Feature scaler used to transform input features before prediction.
- `chronic_disease_dataset.csv` — Dataset used during development (optional for running the app).
- `llm_recommender.pkl` — (Optional) additional recommender artifact.
- `requirements.txt` — Python dependencies.

## Requirements
- Python 3.8+ recommended
- The dependencies in `requirements.txt`. Main packages include: `streamlit`, `pandas`, `numpy`, `scikit-learn`, `joblib`, `openai`.

## Setup (Windows PowerShell)

1. Create and activate a virtual environment (recommended):

```powershell
python -m venv .venv
.\.venv\Scripts\Activate.ps1
```

2. Install dependencies:

```powershell
python -m pip install --upgrade pip
pip install -r requirements.txt
```

3. Add your OpenAI API key to an environment variable. The app expects `OPENAI_API_KEY` to be available (the project uses `python-dotenv` if you prefer a `.env` file):

```powershell
$env:OPENAI_API_KEY = 'sk-...'
# or create a .env file in the same folder as app.py with:
# OPENAI_API_KEY=sk-...
```

Note: If you don't intend to use OpenAI (no API key), the app still works for predictions and the built-in fallback chatbot will answer some keyword queries. However, recommendations from OpenAI will not be available.

## Run the Streamlit app

From the `submissions/Freakquency/code/` folder run:

```powershell
streamlit run app.py
```

This will open the app in your default browser (or show a local URL in the terminal such as http://localhost:8501).

## Usage
1. Fill the questionnaire and click `Predict`.
2. The app will display the predicted disease category and a short description.
3. If OpenAI is configured, it will show 3 AI-generated lifestyle recommendations. Otherwise fallback recommendations are shown for certain keywords.
4. Use the text input at the bottom to ask the small rule-based chatbot questions (e.g., "exercise", "diet").

## Troubleshooting
- If `model.pkl` or `scaler.pkl` are missing, the app will fail at startup. Make sure both files are in the same folder as `app.py`.
- If you see OpenAI authentication errors, confirm that `OPENAI_API_KEY` is set correctly in your environment or `.env`.
- If Streamlit fails to start, ensure your Python path and virtual environment are correct and that `streamlit` is installed in the active environment.

## Security & Privacy
- Do not commit your OpenAI API key to version control. Use environment variables or a local `.env` file excluded from source control.
- This app is for demo/educational purposes only and does not replace professional medical advice.

## License
This project was created for the Oct-4 Hackathon 2025. Check the project or team repository for license details.

---
If you want, I can also add a brief CONTRIBUTING or LICENSE file, or update the README with screenshots and example inputs. What would you like next?

135 changes: 135 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import os
from dotenv import load_dotenv
from openai import OpenAI

# --- Load environment variables from .env ---
load_dotenv()

# --- Initialize OpenAI client ---
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# --- Load trained model and scaler ---
model = joblib.load("model.pkl")
scaler = joblib.load("scaler.pkl")

# --- Disease names and descriptions ---
disease_info = {
0: {"name": "Healthy", "description": "No major chronic conditions detected. Maintain a balanced lifestyle to stay healthy."},
1: {"name": "Diabetes", "description": "Elevated glucose levels detected. Monitor diet, exercise regularly, and consult your doctor."},
2: {"name": "Cardiovascular Disorder", "description": "Potential risk of heart or vascular conditions. Keep track of blood pressure, cholesterol, and physical activity."},
3: {"name": "Cancer", "description": "Risk factors indicate possible cancer conditions. Regular screenings and medical consultation are advised."},
4: {"name": "Multi-condition Cases", "description": "Multiple risk factors detected. Follow a comprehensive health plan and consult a healthcare professional."}
}

# --- Minimal chatbot responses (fallback) ---
chat_responses = {
"exercise": "Regular exercise helps reduce risk for multiple diseases.",
"diet": "A balanced diet can reduce cholesterol and glucose levels.",
"blood pressure": "Monitoring your blood pressure regularly is important.",
"cholesterol": "Check cholesterol levels regularly and maintain a healthy diet.",
"glucose": "Keep glucose levels in check and maintain balanced meals."
}

def generate_recommendations(disease_name, description):
prompt = f"""
The user has been predicted to have: {disease_name}.
Description: {description}.
Suggest 3 practical lifestyle recommendations for this user.
Keep them short, actionable, and easy to understand.
Format each recommendation as a bullet point.
"""
response = client.chat.completions.create(
model="gpt-4o-mini", # you can switch to gpt-4 or gpt-3.5 if needed
messages=[
{"role": "system", "content": "You are a helpful health assistant."},
{"role": "user", "content": prompt}
],
max_tokens=200,
temperature=0.7
)

text = response.choices[0].message.content.strip()

# Clean and split into neat bullet points
recs = [
line.strip("-•1234567890. ").strip()
for line in text.split("\n")
if line.strip()
]
return recs

# --- Streamlit UI ---
st.title("Freakquency - Disease Risk Prediction & AI Recommendations")
st.write("Fill out the questionnaire below to see your predicted disease and AI-generated lifestyle recommendations.")

# --- Streamlit Form ---
with st.form("health_form"):
age = st.number_input("Age", min_value=0, max_value=120, value=30)
gender = st.selectbox("Gender", ["Male", "Female", "Other"])
bmi = st.number_input("BMI", min_value=10.0, max_value=50.0, value=25.0)
blood_pressure = st.number_input("Blood Pressure", min_value=50, max_value=200, value=120)
cholesterol_level = st.number_input("Cholesterol Level", min_value=100, max_value=400, value=180)
glucose_level = st.number_input("Glucose Level", min_value=50, max_value=300, value=100)
physical_activity = st.number_input("Physical Activity (hours/week)", min_value=0, max_value=50, value=2)
smoking_status = st.selectbox("Smoking Status", ["Never", "Former", "Current"])
alcohol_intake = st.selectbox("Alcohol Intake", ["None", "Moderate", "High"])
family_history = st.selectbox("Family History of Disease?", ["No", "Yes"])

submit_button = st.form_submit_button(label="Predict")

# --- Preprocess and Predict ---
if submit_button:
# Map categorical values to numeric
gender_map = {"Male": 0, "Female": 1, "Other": 2}
smoking_map = {"Never": 0, "Former": 1, "Current": 2}
alcohol_map = {"None": 0, "Moderate": 1, "High": 2}
family_map = {"No": 0, "Yes": 1}

input_data = np.array([[
age,
gender_map[gender],
bmi,
blood_pressure,
cholesterol_level,
glucose_level,
physical_activity,
smoking_map[smoking_status],
alcohol_map[alcohol_intake],
family_map[family_history]
]])

# Scale features
input_scaled = scaler.transform(input_data)

# Predict disease class
prediction = model.predict(input_scaled)[0]
disease = disease_info[prediction]

# Display prediction in a card-like format
with st.container():
st.markdown("### Predicted Disease Category")
st.markdown(f"**{disease['name']}**")
st.write(disease["description"])

st.markdown("### AI-Generated Lifestyle Recommendations")
ai_recs = generate_recommendations(disease['name'], disease['description'])
for rec in ai_recs:
st.write(f"- {rec}")

# --- Minimal Chatbot ---
st.subheader("Ask a health-related question:")
user_input = st.text_input("Type your question here...")

if user_input:
response_given = False
for key, resp in chat_responses.items():
if key in user_input.lower():
st.write(resp)
response_given = True
break
if not response_given:
st.write("Sorry, I don't have advice for that yet. Try asking about exercise, diet, or blood pressure.")
Loading