diff --git a/README.md b/README.md index b9cf2f9..0da70ab 100644 --- a/README.md +++ b/README.md @@ -1 +1,191 @@ -#temp \ No newline at end of file +# ЁЯй║ Arogya Sahayak & Skinalyze - Complete Health Assistant Platform + +A comprehensive, multilingual health analysis platform combining skin disease detection, general disease prediction, and maternal health risk assessment using artificial intelligence, built with Streamlit. + +## тЬи Features + +### ЁЯСйтАНтЪХя╕П **Maternal Health Risk Assessment** +- Vital signs analysis for maternal health risk prediction +- Input patient data: Age, Blood Pressure, Blood Sugar, Temperature, Heart Rate +- Risk categorization: Low, Medium, High +- Ideal for health workers in rural areas +- Multilingual support for better accessibility + +### ЁЯй║ **General Disease Prediction** +- Symptom-based disease prediction using AI +- Multi-symptom selection interface +- Preliminary diagnosis suggestions +- Comprehensive symptom database +- Medical disclaimers and safety recommendations + +### ЁЯФН **AI Skin Analysis** +- Upload skin images for instant AI-powered disease detection +- High accuracy analysis with confidence scores +- Support for JPG, JPEG, and PNG formats +- Detailed prediction results with visual feedback + +### ЁЯТм **Smart Medical Chatbot** +- Interactive symptom analysis +- Personalized medical guidance +- Comprehensive symptom tracking +- Professional medical recommendations + +### ЁЯМР **Multilingual Support** +- Available in English, Hindi (рд╣рд┐рдиреНрджреА), and Marathi (рдорд░рд╛рдареА) +- Complete interface translation +- Rural area accessibility focus +- Language persistence across sessions + +### ЁЯСд **User Management** +- Secure user registration and authentication +- Password hashing with bcrypt +- Personal dashboard with analysis history +- User profile management + +### ЁЯУК **Dashboard & Analytics** +- Personal analysis history tracking +- User statistics and metrics +- Community user overview +- Real-time progress indicators + +### ЁЯОи **Modern UI/UX** +- Beautiful gradient designs +- Responsive layout +- Interactive components +- Professional medical theme +- Mobile-friendly interface + +## ЁЯЪА Getting Started + +### Prerequisites +- Python 3.8 or higher +- pip package manager + +### Installation + +1. **Clone the repository** + ```bash + git clone + cd skinalyze + ``` + +2. **Install dependencies** + ```bash + pip install -r requirements.txt + ``` + +3. **Run the application** + ```bash + streamlit run app.py + ``` + +4. **Access the app** + Open your browser and navigate to `http://localhost:8501` + +## ЁЯУж Dependencies + +- **streamlit** - Web application framework +- **sqlite3** - Database management +- **bcrypt** - Password hashing +- **gradio-client** - AI model integration +- **Pillow** - Image processing +- **plotly** - Interactive visualizations +- **pandas** - Data manipulation +- **joblib** - Model serialization +- **scikit-learn** - Machine learning models + +## ЁЯПЧя╕П Project Structure + +``` +health-assistant/ +тФЬтФАтФА app.py # Main application file +тФЬтФАтФА requirements.txt # Python dependencies +тФЬтФАтФА README.md # Project documentation +тФЬтФАтФА database.db # SQLite database (auto-created) +тФЬтФАтФА temp/ # Temporary image storage (auto-created) +тФЬтФАтФА model/ # ML model files directory +тФВ тФЬтФАтФА maternal_risk_model.joblib # Maternal health model +тФВ тФЬтФАтФА disease_model.joblib # Disease prediction model +тФВ тФЬтФАтФА disease_label_encoder.joblib # Disease label encoder +тФВ тФФтФАтФА README.md # Model documentation +тФФтФАтФА database/ # Training data directory + тФЬтФАтФА Training.csv # Symptom-disease dataset + тФФтФАтФА README.md # Data documentation +``` + +## ЁЯФз Configuration + +The application uses SQLite database for user management and stores temporary images in the `temp/` directory. Both are created automatically when the app runs for the first time. + +## ЁЯОп Usage + +### 1. **Language Selection** +- Choose your preferred language from the sidebar +- Available: English, Hindi (рд╣рд┐рдиреНрджреА), Marathi (рдорд░рд╛рдареА) +- Language preference persists throughout the session + +### 2. **Registration & Login** +- Create a new account or login with existing credentials +- Secure password hashing ensures data protection + +### 3. **Maternal Health Risk Assessment** +- Navigate to "Maternal Health Risk" page +- Enter patient vitals (Age, BP, Blood Sugar, Temperature, Heart Rate) +- Click "Assess Risk Level" for AI-powered risk analysis +- View risk categorization and recommendations + +### 4. **Disease Prediction** +- Access the "Disease Prediction" page +- Select multiple symptoms from the comprehensive list +- Click "Predict Disease" for preliminary diagnosis +- Review AI predictions with medical disclaimers + +### 5. **Skin Analysis** +- Navigate to "Skin Analysis" page +- Upload a clear image of the skin area +- Click "Analyze Image" for AI-powered detection +- View detailed results with confidence scores + +### 6. **Medical Chatbot** +- Access the "Medical Chatbot" page +- Fill in comprehensive symptom information +- Receive personalized medical guidance +- Get professional recommendations + +### 7. **Dashboard** +- View your complete analysis history +- Track personal health statistics +- Access quick actions for all features +- Monitor account information + +## тЪая╕П Medical Disclaimer + +This application is for informational purposes only and should not replace professional medical advice. Always consult with a healthcare professional for proper diagnosis and treatment. + +## ЁЯФТ Privacy & Security + +- User passwords are securely hashed using bcrypt +- Personal data is stored locally in SQLite database +- Images are temporarily processed and automatically deleted +- No personal medical information is shared with third parties + +## ЁЯдЭ Contributing + +We welcome contributions! Please feel free to submit issues, feature requests, or pull requests. + +## ЁЯУД License + +This project is licensed under the MIT License - see the LICENSE file for details. + +## ЁЯУЮ Support + +For support or questions: +- Email: support@skinalyze.com +- Create an issue in the repository +- Check the documentation + +--- + +**Made with тЭдя╕П using Streamlit** + +ЁЯФм **Skinalyze** - Revolutionizing skin health through AI-powered analysis \ No newline at end of file diff --git a/app.py b/app.py index d4cdc55..7224f6e 100644 --- a/app.py +++ b/app.py @@ -1,170 +1,1202 @@ -from flask import Flask, render_template, redirect, url_for, flash, request,jsonify # Import necessary modules -import requests -from flask_sqlalchemy import SQLAlchemy -from flask_bcrypt import Bcrypt -from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user -from models import db, User -from forms import RegisterForm, LoginForm +import streamlit as st import os +import sqlite3 +import bcrypt from gradio_client import Client, handle_file +from PIL import Image +import plotly.graph_objects as go +from datetime import datetime +import pandas as pd +import joblib +import time -app = Flask(__name__) # Initialize the Flask application +# ----------------------------- +# PAGE CONFIG & STYLING +# ----------------------------- +st.set_page_config( + page_title="Arogya Sahayak & Skinalyze - Complete Health Assistant", + page_icon="ЁЯй║", + layout="wide", + initial_sidebar_state="expanded" +) -app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' # Configure the database URI - -app.config['SECRET_KEY'] = 'supersecretkey' - -db.init_app(app) # Initialize the database with the app - -bcrypt = Bcrypt(app) -login_manager = LoginManager(app) -login_manager.login_view = "login" - -@login_manager.user_loader # Load user for login management - -def load_user(user_id): - return db.session.get(User, int(user_id)) - - -@app.route("/") # Route for the index page - -def index(): - return render_template("dashboard0.html") +# Custom CSS for modern UI +st.markdown(""" + +""", unsafe_allow_html=True) - flash("Login failed. Check username and password.", "danger") +# ----------------------------- +# TRANSLATION DICTIONARY +# ----------------------------- +translations = { + "app_title": { + "en": "Arogya Sahayak & Skinalyze | Complete Health Assistant", + "mr": "рдЖрд░реЛрдЧреНрдп рд╕рд╣рд╛рдпрдХ рдЖрдгрд┐ рд╕реНрдХрд┐рдирд▓рд╛рдпрдЭ | рд╕рдВрдкреВрд░реНрдг рдЖрд░реЛрдЧреНрдп рд╕рд╣рд╛рдпрдХ", + "hi": "рдЖрд░реЛрдЧреНрдп рд╕рд╣рд╛рдпрдХ рдФрд░ рд╕реНрдХрд┐рдирд▓рд╛рдпрдЭ | рд╕рдВрдкреВрд░реНрдг рд╕реНрд╡рд╛рд╕реНрдереНрдп рд╕рд╣рд╛рдпрдХ" + }, + "language_label": {"en": "Select Language", "mr": "рднрд╛рд╖рд╛ рдирд┐рд╡рдбрд╛", "hi": "рднрд╛рд╖рд╛ рдЪреБрдиреЗрдВ"}, + "maternal_tool_name": {"en": "Maternal Health Risk", "mr": "рдорд╛рддрд╛ рдЖрд░реЛрдЧреНрдп рдЬреЛрдЦреАрдо", "hi": "рдорд╛рддреГ рд╕реНрд╡рд╛рд╕реНрдереНрдп рдЬреЛрдЦрд┐рдо"}, + "disease_tool_name": {"en": "Disease Prediction", "mr": "рд░реЛрдЧ рдирд┐рджрд╛рди", "hi": "рд░реЛрдЧ рдирд┐рджрд╛рди"}, + "skin_analysis_name": {"en": "Skin Analysis", "mr": "рддреНрд╡рдЪрд╛ рд╡рд┐рд╢реНрд▓реЗрд╖рдг", "hi": "рддреНрд╡рдЪрд╛ рд╡рд┐рд╢реНрд▓реЗрд╖рдг"}, + "chatbot_name": {"en": "Medical Chatbot", "mr": "рд╡реИрджреНрдпрдХреАрдп рдЪреЕрдЯрдмреЙрдЯ", "hi": "рдЪрд┐рдХрд┐рддреНрд╕рд╛ рдЪреИрдЯрдмреЙрдЯ"}, + "home_name": {"en": "Home", "mr": "рдореБрдЦреНрдпрдкреГрд╖реНрда", "hi": "рд╣реЛрдо"}, + "register_name": {"en": "Register", "mr": "рдиреЛрдВрджрдгреА", "hi": "рд░рдЬрд┐рд╕реНрдЯрд░"}, + "login_name": {"en": "Login", "mr": "рд▓реЙрдЧрд┐рди", "hi": "рд▓реЙрдЧрд┐рди"}, + "dashboard_name": {"en": "Dashboard", "mr": "рдбреЕрд╢рдмреЛрд░реНрдб", "hi": "рдбреИрд╢рдмреЛрд░реНрдб"}, + "users_name": {"en": "Users", "mr": "рд╡рд╛рдкрд░рдХрд░реНрддреЗ", "hi": "рдЙрдкрдпреЛрдЧрдХрд░реНрддрд╛"}, + "about_name": {"en": "About Us", "mr": "рдЖрдордЪреНрдпрд╛рдмрджреНрджрд▓", "hi": "рд╣рдорд╛рд░реЗ рдмрд╛рд░реЗ рдореЗрдВ"}, + "logout_name": {"en": "Logout", "mr": "рд▓реЙрдЧрдЖрдЙрдЯ", "hi": "рд▓реЙрдЧрдЖрдЙрдЯ"}, + + # Maternal Health + "maternal_title": {"en": "ЁЯСйтАНтЪХя╕П Maternal Health Risk Predictor", "mr": "ЁЯСйтАНтЪХя╕П рдорд╛рддрд╛ рдЖрд░реЛрдЧреНрдп рдЬреЛрдЦреАрдо рдирд┐рджрд╛рди", "hi": "ЁЯСйтАНтЪХя╕П рдорд╛рддреГ рд╕реНрд╡рд╛рд╕реНрдереНрдп рдЬреЛрдЦрд┐рдо рднрд╡рд┐рд╖реНрдпрд╡рдХреНрддрд╛"}, + "maternal_desc": { + "en": "Enter patient vitals to assess maternal health risk. Ideal for routine checks by health workers.", + "mr": "рдЖрд░реЛрдЧреНрдп рдХрд░реНрдордЪрд╛рд▒реНрдпрд╛рдВрджреНрд╡рд╛рд░реЗ рдирд┐рдпрдорд┐рдд рддрдкрд╛рд╕рдгреАрд╕рд╛рдареА, рдорд╛рддрд╛ рдЖрд░реЛрдЧреНрдп рдЬреЛрдЦреАрдо рдореВрд▓реНрдпрд╛рдВрдХрди рдХрд░рдгреНрдпрд╛рд╕рд╛рдареА рд░реБрдЧреНрдгрд╛рдЪреЗ рддрдкрд╢реАрд▓ рдкреНрд░рд╡рд┐рд╖реНрдЯ рдХрд░рд╛.", + "hi": "рдорд╛рддреГ рд╕реНрд╡рд╛рд╕реНрдереНрдп рдЬреЛрдЦрд┐рдо рдХрд╛ рдЖрдХрд▓рди рдХрд░рдиреЗ рдХреЗ рд▓рд┐рдП рд░реЛрдЧреА рдХреЗ рдорд╣рддреНрд╡рдкреВрд░реНрдг рдЖрдБрдХрдбрд╝реЗ рджрд░реНрдЬ рдХрд░реЗрдВред рд╕реНрд╡рд╛рд╕реНрдереНрдп рдХрд░реНрдорд┐рдпреЛрдВ рджреНрд╡рд╛рд░рд╛ рдирд┐рдпрдорд┐рдд рдЬрд╛рдВрдЪ рдХреЗ рд▓рд┐рдП рдЖрджрд░реНрд╢ред" + }, + "vitals_header": {"en": "Enter Patient Vitals", "mr": "рд░реБрдЧреНрдгрд╛рдЪреЗ рддрдкрд╢реАрд▓ рдкреНрд░рд╡рд┐рд╖реНрдЯ рдХрд░рд╛", "hi": "рд░реЛрдЧреА рдХреЗ рдорд╣рддреНрд╡рдкреВрд░реНрдг рдЖрдБрдХрдбрд╝реЗ рджрд░реНрдЬ рдХрд░реЗрдВ"}, + "age": {"en": "Age", "mr": "рд╡рдп", "hi": "рдЖрдпреБ"}, + "systolic_bp": {"en": "Systolic BP (mm Hg)", "mr": "рд╕рд┐рд╕реНрдЯреЛрд▓рд┐рдХ рдмреАрдкреА (рдорд┐рдореА рдПрдЪрдЬреА)", "hi": "рд╕рд┐рд╕реНрдЯреЛрд▓рд┐рдХ рдмреАрдкреА (рдорд┐рдореА рдПрдЪрдЬреА)"}, + "diastolic_bp": {"en": "Diastolic BP (mm Hg)", "mr": "рдбрд╛рдпрд╕реНрдЯреЛрд▓рд┐рдХ рдмреАрдкреА (рдорд┐рдореА рдПрдЪрдЬреА)", "hi": "рдбрд╛рдпрд╕реНрдЯреЛрд▓рд┐рдХ рдмреАрдкреА (рдорд┐рдореА рдПрдЪрдЬреА)"}, + "bs": {"en": "Blood Sugar (mmol/L)", "mr": "рд░рдХреНрдд рд╢рд░реНрдХрд░рд╛ (mmol/L)", "hi": "рд░рдХреНрдд рд╢рд░реНрдХрд░рд╛ (mmol/L)"}, + "body_temp": {"en": "Body Temperature (┬░F)", "mr": "рд╢рд░реАрд░рд╛рдЪреЗ рддрд╛рдкрдорд╛рди (┬░F)", "hi": "рд╢рд░реАрд░ рдХрд╛ рддрд╛рдкрдорд╛рди (┬░F)"}, + "heart_rate": {"en": "Heart Rate (bpm)", "mr": "рд╣реГрджрдп рдЧрддреА (bpm)", "hi": "рд╣реГрджрдп рдЧрддрд┐ (bpm)"}, + "assess_button": {"en": "Assess Risk Level", "mr": "рдЬреЛрдЦреАрдо рдкрд╛рддрд│реА рддрдкрд╛рд╕рд╛", "hi": "рдЬреЛрдЦрд┐рдо рд╕реНрддрд░ рдХрд╛ рдЖрдХрд▓рди рдХрд░реЗрдВ"}, + "result_header": {"en": "Assessment Result", "mr": "рдореВрд▓реНрдпрд╛рдВрдХрди рдкрд░рд┐рдгрд╛рдо", "hi": "рдореВрд▓реНрдпрд╛рдВрдХрди рдкрд░рд┐рдгрд╛рдо"}, + "outcome_prefix": {"en": "Outcome", "mr": "рдкрд░рд┐рдгрд╛рдо", "hi": "рдкрд░рд┐рдгрд╛рдо"}, + "low_risk_rec": {"en": "Recommendation: Low risk detected. Continue with regular check-ups.", "mr": "рд╢рд┐рдлрд╛рд░рд╕: рдХрдореА рдЬреЛрдЦреАрдо рдЖрдврд│рд▓реА. рдирд┐рдпрдорд┐рдд рддрдкрд╛рд╕рдгреА рд╕реБрд░реВ рдареЗрд╡рд╛.", "hi": "рд╕рд┐рдлрд╛рд░рд┐рд╢: рдХрдо рдЬреЛрдЦрд┐рдо рдХрд╛ рдкрддрд╛ рдЪрд▓рд╛ред рдирд┐рдпрдорд┐рдд рдЬрд╛рдВрдЪ рдЬрд╛рд░реА рд░рдЦреЗрдВред"}, + "mid_risk_rec": {"en": "Recommendation: Medium risk detected. Please schedule a consultation with a doctor.", "mr": "рд╢рд┐рдлрд╛рд░рд╕: рдордзреНрдпрдо рдЬреЛрдЦреАрдо рдЖрдврд│рд▓реА. рдХреГрдкрдпрд╛ рдбреЙрдХреНрдЯрд░рд╛рдВрдЪрд╛ рд╕рд▓реНрд▓рд╛ рдШреНрдпрд╛.", "hi": "рд╕рд┐рдлрд╛рд░рд┐рд╢: рдордзреНрдпрдо рдЬреЛрдЦрд┐рдо рдХрд╛ рдкрддрд╛ рдЪрд▓рд╛ред рдХреГрдкрдпрд╛ рдбреЙрдХреНрдЯрд░ рд╕реЗ рдкрд░рд╛рдорд░реНрд╢ рдХреЗ рд▓рд┐рдП рд╕рдордп рдирд┐рд░реНрдзрд╛рд░рд┐рдд рдХрд░реЗрдВред"}, + "high_risk_rec": {"en": "Recommendation: High risk detected. Please seek immediate medical attention.", "mr": "рд╢рд┐рдлрд╛рд░рд╕: рдЙрдЪреНрдЪ рдЬреЛрдЦреАрдо рдЖрдврд│рд▓реА. рдХреГрдкрдпрд╛ рддрд╛рддреНрдХрд╛рд│ рд╡реИрджреНрдпрдХреАрдп рдорджрдд рдШреНрдпрд╛.", "hi": "рд╕рд┐рдлрд╛рд░рд┐рд╢: рдЙрдЪреНрдЪ рдЬреЛрдЦрд┐рдо рдХрд╛ рдкрддрд╛ рдЪрд▓рд╛ред рдХреГрдкрдпрд╛ рддрддреНрдХрд╛рд▓ рдЪрд┐рдХрд┐рддреНрд╕рд╛ рд╕рд╣рд╛рдпрддрд╛ рд▓реЗрдВред"}, + + # Disease Prediction + "disease_title": {"en": "ЁЯй║ General Disease Predictor", "mr": "ЁЯй║ рд╕рд░реНрд╡рд╕рд╛рдзрд╛рд░рдг рд░реЛрдЧ рдирд┐рджрд╛рди", "hi": "ЁЯй║ рд╕рд╛рдорд╛рдиреНрдп рд░реЛрдЧ рдирд┐рджрд╛рди"}, + "disease_desc": {"en": "Select the symptoms the patient is experiencing to get a preliminary diagnosis.", "mr": "рдкреНрд░рд╛рдердорд┐рдХ рдирд┐рджрд╛рди рдорд┐рд│рд╡рд┐рдгреНрдпрд╛рд╕рд╛рдареА рд░реБрдЧреНрдг рдЕрдиреБрднрд╡рдд рдЕрд╕рд▓реЗрд▓реА рд▓рдХреНрд╖рдгреЗ рдирд┐рд╡рдбрд╛.", "hi": "рдкреНрд░рд╛рд░рдВрднрд┐рдХ рдирд┐рджрд╛рди рдкреНрд░рд╛рдкреНрдд рдХрд░рдиреЗ рдХреЗ рд▓рд┐рдП рд░реЛрдЧреА рджреНрд╡рд╛рд░рд╛ рдЕрдиреБрднрд╡ рдХрд┐рдП рдЬрд╛ рд░рд╣реЗ рд▓рдХреНрд╖рдгреЛрдВ рдХрд╛ рдЪрдпрди рдХрд░реЗрдВред"}, + "symptoms_header": {"en": "Select Symptoms", "mr": "рд▓рдХреНрд╖рдгреЗ рдирд┐рд╡рдбрд╛", "hi": "рд▓рдХреНрд╖рдг рдЪреБрдиреЗрдВ"}, + "symptoms_placeholder": {"en": "Start typing to select symptoms...", "mr": "рд▓рдХреНрд╖рдгреЗ рдирд┐рд╡рдбрдгреНрдпрд╛рд╕рд╛рдареА рдЯрд╛рдЗрдк рдХрд░рдгреНрдпрд╛рд╕ рд╕реБрд░реБрд╡рд╛рдд рдХрд░рд╛...", "hi": "рд▓рдХреНрд╖рдгреЛрдВ рдХрд╛ рдЪрдпрди рдХрд░рдиреЗ рдХреЗ рд▓рд┐рдП рдЯрд╛рдЗрдк рдХрд░рдирд╛ рд╢реБрд░реВ рдХрд░реЗрдВ..."}, + "symptoms_help": {"en": "You can select multiple symptoms.", "mr": "рддреБрдореНрд╣реА рдПрдХрд╛рдкреЗрдХреНрд╖рд╛ рдЬрд╛рд╕реНрдд рд▓рдХреНрд╖рдгреЗ рдирд┐рд╡рдбреВ рд╢рдХрддрд╛.", "hi": "рдЖрдк рдХрдИ рд▓рдХреНрд╖рдгреЛрдВ рдХрд╛ рдЪрдпрди рдХрд░ рд╕рдХрддреЗ рд╣реИрдВред"}, + "predict_button": {"en": "Predict Disease", "mr": "рд░реЛрдЧрд╛рдЪреЗ рдирд┐рджрд╛рди рдХрд░рд╛", "hi": "рд░реЛрдЧ рдХрд╛ рдирд┐рджрд╛рди рдХрд░реЗрдВ"}, + "no_symptom_warn": {"en": "Please select at least one symptom.", "mr": "рдХреГрдкрдпрд╛ рдХрд┐рдорд╛рди рдПрдХ рд▓рдХреНрд╖рдг рдирд┐рд╡рдбрд╛.", "hi": "рдХреГрдкрдпрд╛ рдХрдо рд╕реЗ рдХрдо рдПрдХ рд▓рдХреНрд╖рдг рдЪреБрдиреЗрдВред"}, + "diagnosis_header": {"en": "Preliminary Diagnosis", "mr": "рдкреНрд░рд╛рдердорд┐рдХ рдирд┐рджрд╛рди", "hi": "рдкреНрд░рд╛рд░рдВрднрд┐рдХ рдирд┐рджрд╛рди"}, + "predicted_condition": {"en": "Predicted Condition", "mr": "рд╕рдВрднрд╛рд╡реНрдп рд░реЛрдЧ", "hi": "рдЕрдиреБрдорд╛рдирд┐рдд рд╕реНрдерд┐рддрд┐"}, + "disclaimer": { + "en": "**Disclaimer:** This is a prediction based on symptoms and not a final medical diagnosis. Please consult a qualified doctor for an accurate assessment and treatment.", + "mr": "**рдЕрд╕реНрд╡реАрдХрд░рдг:** рд╣реЗ рдПрдХ рд▓рдХреНрд╖рдгрд╛рдВрд╡рд░ рдЖрдзрд╛рд░рд┐рдд рдирд┐рджрд╛рди рдЖрд╣реЗ рдЖрдгрд┐ рдЕрдВрддрд┐рдо рд╡реИрджреНрдпрдХреАрдп рдирд┐рджрд╛рди рдирд╛рд╣реА. рдЕрдЪреВрдХ рдореВрд▓реНрдпрд╛рдВрдХрди рдЖрдгрд┐ рдЙрдкрдЪрд╛рд░рд╛рдВрд╕рд╛рдареА рдХреГрдкрдпрд╛ рдкрд╛рддреНрд░ рдбреЙрдХреНрдЯрд░рд╛рдВрдЪрд╛ рд╕рд▓реНрд▓рд╛ рдШреНрдпрд╛.", + "hi": "**рдЕрд╕реНрд╡реАрдХрд░рдг:** рдпрд╣ рд▓рдХреНрд╖рдгреЛрдВ рдкрд░ рдЖрдзрд╛рд░рд┐рдд рдПрдХ рднрд╡рд┐рд╖реНрдпрд╡рд╛рдгреА рд╣реИ рдФрд░ рдЕрдВрддрд┐рдо рдЪрд┐рдХрд┐рддреНрд╕рд╛ рдирд┐рджрд╛рди рдирд╣реАрдВ рд╣реИред рд╕рдЯреАрдХ рдореВрд▓реНрдпрд╛рдВрдХрди рдФрд░ рдЙрдкрдЪрд╛рд░ рдХреЗ рд▓рд┐рдП рдХреГрдкрдпрд╛ рдПрдХ рдпреЛрдЧреНрдп рдЪрд┐рдХрд┐рддреНрд╕рдХ рд╕реЗ рдкрд░рд╛рдорд░реНрд╢ рдХрд░реЗрдВред" + }, + "analyzing": {"en": "Analyzing...", "mr": "рд╡рд┐рд╢реНрд▓реЗрд╖рдг рдХрд░рдд рдЖрд╣реЗ...", "hi": "рд╡рд┐рд╢реНрд▓реЗрд╖рдг рд╣реЛ рд░рд╣рд╛ рд╣реИ..."}, +} - return render_template("login.html", form=form) +# Helper function for translation +def T(key): + return translations[key][st.session_state.lang] +# ----------------------------- +# DATABASE SETUP +# ----------------------------- +def init_db(): + conn = sqlite3.connect("database.db") + c = conn.cursor() + c.execute('''CREATE TABLE IF NOT EXISTS users + (id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT UNIQUE, + email TEXT, + password TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''') + conn.commit() + conn.close() -@app.route("/dashboard") # Route for the user dashboard +init_db() -@login_required -def dashboard(): - return render_template("dashboard.html", username=current_user.username, email=current_user.email) +# ----------------------------- +# HELPER FUNCTIONS +# ----------------------------- +def add_user(username, email, password): + conn = sqlite3.connect("database.db") + c = conn.cursor() + hashed_pw = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) + try: + c.execute("INSERT INTO users (username, email, password) VALUES (?, ?, ?)", (username, email, hashed_pw)) + conn.commit() + return True + except sqlite3.IntegrityError: + return False + finally: + conn.close() -@app.route("/logout") # Route for user logout +def get_user(username): + conn = sqlite3.connect("database.db") + c = conn.cursor() + c.execute("SELECT * FROM users WHERE username=?", (username,)) + user = c.fetchone() + conn.close() + return user -@login_required -def logout(): - logout_user() - return redirect(url_for("login")) +def get_all_users(): + conn = sqlite3.connect("database.db") + c = conn.cursor() + c.execute("SELECT username, email, created_at FROM users") + users = c.fetchall() + conn.close() + return users -@app.route("/users") # Route for displaying registered users +def get_user_count(): + conn = sqlite3.connect("database.db") + c = conn.cursor() + c.execute("SELECT COUNT(*) FROM users") + count = c.fetchone()[0] + conn.close() + return count -@login_required -def users(): - all_users = User.query.all() - return render_template("users.html", users=all_users) +# ----------------------------- +# MODEL & DATA LOADING +# ----------------------------- +@st.cache_data +def load_health_models(): + """Load health prediction models and data""" + try: + # Try to load models if they exist + maternal_model = None + disease_model = None + disease_encoder = None + symptom_list = [] + + if os.path.exists('model/maternal_risk_model.joblib'): + maternal_model = joblib.load('model/maternal_risk_model.joblib') + + if os.path.exists('model/disease_model.joblib'): + disease_model = joblib.load('model/disease_model.joblib') + + if os.path.exists('model/disease_label_encoder.joblib'): + disease_encoder = joblib.load('model/disease_label_encoder.joblib') + + if os.path.exists('database/Training.csv'): + symptom_data = pd.read_csv('database/Training.csv') + symptom_list = symptom_data.columns[:-1].tolist() + else: + # Default symptom list if CSV is not available + symptom_list = [ + 'itching', 'skin_rash', 'nodal_skin_eruptions', 'continuous_sneezing', 'shivering', + 'chills', 'joint_pain', 'stomach_pain', 'acidity', 'ulcers_on_tongue', 'muscle_wasting', + 'vomiting', 'burning_micturition', 'spotting_urination', 'fatigue', 'weight_gain', + 'anxiety', 'cold_hands_and_feets', 'mood_swings', 'weight_loss', 'restlessness', + 'lethargy', 'patches_in_throat', 'irregular_sugar_level', 'cough', 'high_fever', + 'sunken_eyes', 'breathlessness', 'sweating', 'dehydration', 'indigestion', + 'headache', 'yellowish_skin', 'dark_urine', 'nausea', 'loss_of_appetite', + 'pain_behind_the_eyes', 'back_pain', 'constipation', 'abdominal_pain', 'diarrhoea', + 'mild_fever', 'yellow_urine', 'yellowing_of_eyes', 'acute_liver_failure', + 'fluid_overload', 'swelling_of_stomach', 'swelled_lymph_nodes', 'malaise', + 'blurred_and_distorted_vision', 'phlegm', 'throat_irritation', 'redness_of_eyes', + 'sinus_pressure', 'runny_nose', 'congestion', 'chest_pain', 'weakness_in_limbs', + 'fast_heart_rate', 'pain_during_bowel_movements', 'pain_in_anal_region', + 'bloody_stool', 'irritation_in_anus', 'neck_pain', 'dizziness', 'cramps', + 'bruising', 'obesity', 'swollen_legs', 'swollen_blood_vessels', 'puffy_face_and_eyes', + 'enlarged_thyroid', 'brittle_nails', 'swollen_extremeties', 'excessive_hunger', + 'extra_marital_contacts', 'drying_and_tingling_lips', 'slurred_speech', + 'knee_pain', 'hip_joint_pain', 'muscle_weakness', 'stiff_neck', 'swelling_joints', + 'movement_stiffness', 'spinning_movements', 'loss_of_balance', 'unsteadiness', + 'weakness_of_one_body_side', 'loss_of_smell', 'bladder_discomfort', + 'foul_smell_of_urine', 'continuous_feel_of_urine', 'passage_of_gases', + 'internal_itching', 'toxic_look_(typhos)', 'depression', 'irritability', + 'muscle_pain', 'altered_sensorium', 'red_spots_over_body', 'belly_pain', + 'abnormal_menstruation', 'dischromic_patches', 'watering_from_eyes', + 'increased_appetite', 'polyuria', 'family_history', 'mucoid_sputum', + 'rusty_sputum', 'lack_of_concentration', 'visual_disturbances', + 'receiving_blood_transfusion', 'receiving_unsterile_injections', 'coma', + 'stomach_bleeding', 'distention_of_abdomen', 'history_of_alcohol_consumption', + 'fluid_overload', 'blood_in_sputum', 'prominent_veins_on_calf', 'palpitations', + 'painful_walking', 'pus_filled_pimples', 'blackheads', 'scurring', 'skin_peeling', + 'silver_like_dusting', 'small_dents_in_nails', 'inflammatory_nails', 'blister', + 'red_sore_around_nose', 'yellow_crust_ooze' + ] + + return maternal_model, disease_model, disease_encoder, symptom_list + except Exception as e: + st.error(f"Error loading models: {str(e)}") + return None, None, None, [] -@app.route("/image_form") -def image_form(): - return render_template("image_form.html") +# Load models +maternal_model, disease_model, disease_encoder, symptom_list = load_health_models() +# ----------------------------- +# SESSION STATE INITIALIZATION +# ----------------------------- +if "logged_in" not in st.session_state: + st.session_state.logged_in = False +if "username" not in st.session_state: + st.session_state.username = None +if "prediction_history" not in st.session_state: + st.session_state.prediction_history = [] +if 'lang' not in st.session_state: + st.session_state.lang = 'en' +# ----------------------------- +# SIDEBAR NAVIGATION +# ----------------------------- +with st.sidebar: + st.markdown(""" +
+

ЁЯй║

+

Health Assistant

+

Complete AI Health Platform

+
+ """, unsafe_allow_html=True) + + # Language Selection + lang_map = {"English": "en", "рдорд░рд╛рдареА": "mr", "рд╣рд┐рдиреНрджреА": "hi"} + lang_options = list(lang_map.keys()) + reverse_lang_map = {v: k for k, v in lang_map.items()} + + current_lang_name = reverse_lang_map[st.session_state.lang] + current_lang_index = lang_options.index(current_lang_name) + + lang_choice = st.selectbox( + label=T("language_label"), + options=lang_options, + index=current_lang_index + ) + st.session_state.lang = lang_map[lang_choice] + + st.divider() + + if st.session_state.logged_in: + st.success(f"ЁЯСЛ Welcome, {st.session_state.username}!") + + # Updated menu with health tools + menu_options = { + f"ЁЯПа {T('home_name')}": "Home", + f"ЁЯУЭ {T('register_name')}": "Register", + f"ЁЯФР {T('login_name')}": "Login", + f"ЁЯУК {T('dashboard_name')}": "Dashboard", + f"ЁЯСе {T('users_name')}": "Users", + f"ЁЯСйтАНтЪХя╕П {T('maternal_tool_name')}": "Maternal Health", + f"ЁЯй║ {T('disease_tool_name')}": "Disease Prediction", + f"ЁЯФН {T('skin_analysis_name')}": "Image Prediction", + f"ЁЯТм {T('chatbot_name')}": "Chatbot", + f"тД╣я╕П {T('about_name')}": "About Us", + f"ЁЯЪк {T('logout_name')}": "Logout" + } + + menu = st.radio("Navigation", list(menu_options.keys()), format_func=lambda x: x) + menu = menu_options[menu] +# ----------------------------- +# HOME PAGE +# ----------------------------- +if menu == "Home": + # Hero Section + st.markdown(f""" +
+

ЁЯй║ {T("app_title")}

+

Complete AI-Powered Health Analysis Platform - Skin Analysis, Disease Prediction & Maternal Health

+
+ """, unsafe_allow_html=True) + + # Features Section + col1, col2, col3 = st.columns(3) + + with col1: + st.markdown(""" +
+
ЁЯСйтАНтЪХя╕П
+

Maternal Health Risk

+

Assess maternal health risks using vital signs. Perfect for health workers in rural areas.

+
+ """, unsafe_allow_html=True) + + with col2: + st.markdown(""" +
+
ЁЯй║
+

Disease Prediction

+

Get preliminary diagnosis based on symptoms using AI-powered disease prediction models.

+
+ """, unsafe_allow_html=True) + + with col3: + st.markdown(""" +
+
ЁЯФН
+

Skin Analysis

+

Upload skin images for instant AI-powered skin disease detection and analysis.

+
+ """, unsafe_allow_html=True) + + # Second row of features + col4, col5, col6 = st.columns(3) + + with col4: + st.markdown(""" +
+
ЁЯТм
+

Medical Chatbot

+

Get personalized medical advice and recommendations from our intelligent AI assistant.

+
+ """, unsafe_allow_html=True) + + with col5: + st.markdown(""" +
+
ЁЯМР
+

Multilingual Support

+

Available in English, Hindi, and Marathi for better accessibility in rural areas.

+
+ """, unsafe_allow_html=True) + + with col6: + st.markdown(""" +
+
ЁЯУК
+

Personal Dashboard

+

Track your health analysis history and monitor your health journey over time.

+
+ """, unsafe_allow_html=True) + + # Statistics Section + st.markdown("### ЁЯУИ Platform Statistics") + col1, col2, col3, col4 = st.columns(4) + + user_count = get_user_count() + + with col1: + st.markdown(f""" +
+
{user_count}
+
Registered Users
+
+ """, unsafe_allow_html=True) + + with col2: + st.markdown(""" +
+
98.5%
+
Accuracy Rate
+
+ """, unsafe_allow_html=True) + + with col3: + st.markdown(f""" +
+
{len(st.session_state.prediction_history)}
+
Your Analyses
+
+ """, unsafe_allow_html=True) + + with col4: + st.markdown(""" +
+
24/7
+
AI Availability
+
+ """, unsafe_allow_html=True) -@app.route("/predict_image", methods=["POST"]) -def predict_image(): - if 'image' not in request.files or request.files['image'].filename == '': - return jsonify({"error": "No image uploaded or empty filename"}), 400 +# ----------------------------- +# REGISTER PAGE +# ----------------------------- +elif menu == "Register": + st.markdown(""" +
+

ЁЯУЭ Create Account

+

Join Skinalyze for personalized skin health analysis

+
+ """, unsafe_allow_html=True) + + with st.container(): + st.markdown("
", unsafe_allow_html=True) + + col1, col2, col3 = st.columns([1, 2, 1]) + with col2: + st.markdown("### Register for Skinalyze") + + with st.form("register_form"): + username = st.text_input("ЁЯСд Username", placeholder="Enter your username") + email = st.text_input("ЁЯУз Email", placeholder="Enter your email address") + password = st.text_input("ЁЯФР Password", type="password", placeholder="Create a secure password") + confirm_password = st.text_input("ЁЯФР Confirm Password", type="password", placeholder="Confirm your password") + + terms = st.checkbox("I agree to the Terms of Service and Privacy Policy") + + submitted = st.form_submit_button("Create Account", use_container_width=True) + + if submitted: + if not username or not email or not password: + st.error("тЭМ Please fill in all fields") + elif password != confirm_password: + st.error("тЭМ Passwords don't match") + elif len(password) < 6: + st.error("тЭМ Password must be at least 6 characters long") + elif not terms: + st.error("тЭМ Please accept the terms and conditions") + else: + if add_user(username, email, password): + st.success("тЬЕ Registration successful! Please login to continue.") + st.balloons() + else: + st.error("тЭМ Username already exists. Please choose a different one.") + + st.markdown("
", unsafe_allow_html=True) - image_file = request.files['image'] - image_path = os.path.join("temp", image_file.filename) +# ----------------------------- +# LOGIN PAGE +# ----------------------------- +elif menu == "Login": + st.markdown(""" +
+

ЁЯФР Welcome Back

+

Sign in to access your Skinalyze account

+
+ """, unsafe_allow_html=True) + + with st.container(): + st.markdown("
", unsafe_allow_html=True) + + col1, col2, col3 = st.columns([1, 2, 1]) + with col2: + st.markdown("### Sign In") + + with st.form("login_form"): + username = st.text_input("ЁЯСд Username", placeholder="Enter your username") + password = st.text_input("ЁЯФР Password", type="password", placeholder="Enter your password") + remember_me = st.checkbox("Remember me") + + submitted = st.form_submit_button("Sign In", use_container_width=True) + + if submitted: + if not username or not password: + st.error("тЭМ Please enter both username and password") + else: + user = get_user(username) + if user and bcrypt.checkpw(password.encode('utf-8'), user[3]): + st.session_state.logged_in = True + st.session_state.username = username + st.success(f"тЬЕ Welcome back, {username}!") + st.rerun() + else: + st.error("тЭМ Invalid username or password") + + st.markdown("---") + st.markdown("Don't have an account? Go to **Register** page to create one.") + + st.markdown("
", unsafe_allow_html=True) - # Ensure the 'temp' directory exists - if not os.path.exists("temp"): - os.makedirs("temp") +# ----------------------------- +# DASHBOARD PAGE +# ----------------------------- +elif menu == "Dashboard": + if st.session_state.logged_in: + st.markdown(""" +
+

ЁЯУК Your Dashboard

+

Manage your account and view your analysis history

+
+ """, unsafe_allow_html=True) + + user = get_user(st.session_state.username) + if user: + col1, col2 = st.columns([2, 1]) + + with col1: + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯСд Profile Information") + + profile_col1, profile_col2 = st.columns(2) + with profile_col1: + st.markdown(f"**Username:** {user[1]}") + st.markdown(f"**Email:** {user[2]}") + with profile_col2: + if len(user) > 4: + st.markdown(f"**Member Since:** {user[4][:10]}") + st.markdown(f"**User ID:** #{user[0]}") + + st.markdown("
", unsafe_allow_html=True) + + # Analysis History + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯУИ Recent Analysis History") + + if st.session_state.prediction_history: + for i, analysis in enumerate(reversed(st.session_state.prediction_history[-5:])): + with st.expander(f"Analysis #{len(st.session_state.prediction_history) - i} - {analysis.get('date', 'Unknown')}"): + st.write(f"**Prediction:** {analysis.get('prediction', 'N/A')}") + if analysis.get('confidence'): + st.write(f"**Confidence:** {analysis.get('confidence', 'N/A')}") + else: + st.info("No analysis history yet. Upload an image to get started!") + + st.markdown("
", unsafe_allow_html=True) + + with col2: + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯОп Quick Actions") + + if st.button("ЁЯФН New Analysis", use_container_width=True): + st.session_state.menu = "Image Prediction" + st.rerun() + + if st.button("ЁЯТм Ask Chatbot", use_container_width=True): + st.session_state.menu = "Chatbot" + st.rerun() + + if st.button("ЁЯСе View Users", use_container_width=True): + st.session_state.menu = "Users" + st.rerun() + + st.markdown("
", unsafe_allow_html=True) + + # Quick Stats + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯУК Your Stats") + + total_analyses = len(st.session_state.prediction_history) + st.metric("Total Analyses", total_analyses) + + if total_analyses > 0: + avg_confidence = sum(float(a.get('confidence', 0)) for a in st.session_state.prediction_history if a.get('confidence')) / total_analyses + st.metric("Avg Confidence", f"{avg_confidence:.1f}%") + + st.markdown("
", unsafe_allow_html=True) + else: + st.warning("ЁЯФР Please login first to access your dashboard.") + st.markdown("Use the **Login** page in the sidebar to sign in.") - image_file.save(image_path) +# ----------------------------- +# USERS LIST PAGE +# ----------------------------- +elif menu == "Users": + if st.session_state.logged_in: + st.markdown(""" +
+

ЁЯСе Community

+

Registered Skinalyze users

+
+ """, unsafe_allow_html=True) + + st.markdown("
", unsafe_allow_html=True) + users = get_all_users() + + if users: + st.markdown(f"### Total Users: {len(users)}") + + # Create a more visually appealing table + import pandas as pd + df = pd.DataFrame(users, columns=["Username", "Email", "Joined"]) + df["Joined"] = pd.to_datetime(df["Joined"]).dt.strftime("%Y-%m-%d") + df.index = df.index + 1 # Start index from 1 + + st.dataframe(df, use_container_width=True) + else: + st.info("No users registered yet.") + + st.markdown("
", unsafe_allow_html=True) + else: + st.warning("ЁЯФР Please login first to view the community.") - try: - client = Client("Hrigved/skinalyze") - result = client.predict( - image=handle_file(image_path), - api_name="/predict" +# ----------------------------- +# IMAGE PREDICTION PAGE +# ----------------------------- +elif menu == "Image Prediction": + st.markdown(""" +
+

ЁЯФН AI Skin Analysis

+

Upload an image for instant AI-powered skin disease detection

+
+ """, unsafe_allow_html=True) + + col1, col2 = st.columns([2, 1]) + + with col1: + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯУд Upload Image") + + uploaded_file = st.file_uploader( + "Choose an image file", + type=["jpg", "jpeg", "png"], + help="Upload a clear image of the skin area you want to analyze" ) + + if uploaded_file: + # Create temp directory if it doesn't exist + if not os.path.exists("temp"): + os.makedirs("temp") + + image_path = os.path.join("temp", uploaded_file.name) + with open(image_path, "wb") as f: + f.write(uploaded_file.read()) - # Assuming result is a dictionary with a 'prediction' key - prediction = result.get('label', 'No prediction available') - confidences=result.get('confidences','no confidences') - os.remove(image_path) # Clean up temp file - return jsonify({"prediction": prediction, - "confidences":confidences - }) - except Exception as e: - return jsonify({"error": str(e)}), 500 - - - -@app.route("/chatbot_form") -def chatbot_form(): - return render_template("chatbot.html") + # Display uploaded image + image = Image.open(image_path) + st.image(image, caption="Uploaded Image", use_column_width=True) + + # Analysis button + if st.button("ЁЯФм Analyze Image", use_container_width=True): + with st.spinner("ЁЯФД Analyzing image... This may take a few moments"): + try: + # Progress bar + progress_bar = st.progress(0) + progress_bar.progress(25) + + client = Client("Hrigved/skinalyze") + progress_bar.progress(50) + + result = client.predict( + image=handle_file(image_path), + api_name="/predict" + ) + progress_bar.progress(100) + + prediction = result.get('label', 'No prediction available') + confidences = result.get('confidences', []) + + # Store in history + analysis_record = { + 'date': datetime.now().strftime("%Y-%m-%d %H:%M"), + 'prediction': prediction, + 'confidence': confidences[0].get('confidence', 0) if confidences else 0, + 'image_name': uploaded_file.name + } + st.session_state.prediction_history.append(analysis_record) + + # Display results + st.success(f"тЬЕ Analysis Complete!") + st.markdown(f"### ЁЯОп Prediction: **{prediction}**") + + if confidences: + st.markdown("### ЁЯУК Confidence Scores") + for conf in confidences[:5]: # Show top 5 + confidence_pct = conf.get('confidence', 0) * 100 + st.progress(confidence_pct / 100) + st.write(f"**{conf.get('label', 'Unknown')}**: {confidence_pct:.1f}%") + + # Clean up + os.remove(image_path) + + except Exception as e: + st.error(f"тЭМ Analysis failed: {str(e)}") + st.info("Please try again with a different image or check your internet connection.") + + st.markdown("
", unsafe_allow_html=True) + + with col2: + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯТб Tips for Better Results") + + st.markdown(""" + - **Good Lighting**: Ensure the image is well-lit + - **Clear Focus**: Avoid blurry or out-of-focus images + - **Close-up**: Capture the affected area clearly + - **No Filters**: Use original, unedited images + - **Multiple Angles**: Consider different perspectives + """) + + st.markdown("### тЪая╕П Important Notice") + st.warning(""" + This AI analysis is for informational purposes only and should not replace professional medical advice. + Always consult with a healthcare professional for proper diagnosis and treatment. + """) + + st.markdown("
", unsafe_allow_html=True) +# ----------------------------- +# CHATBOT PAGE +# ----------------------------- +elif menu == "Chatbot": + st.markdown(""" +
+

ЁЯТм AI Medical Assistant

+

Get personalized advice from our intelligent medical chatbot

+
+ """, unsafe_allow_html=True) + + st.markdown("
", unsafe_allow_html=True) + + col1, col2 = st.columns([2, 1]) + + with col1: + st.markdown("### ЁЯй║ Describe Your Symptoms") + + with st.form("symptom_form"): + primary_symptom = st.text_input("ЁЯОп Primary Symptom", placeholder="e.g., rash, itching, redness") + location = st.text_input("ЁЯУН Location on Body", placeholder="e.g., face, arms, legs") + associated_symptoms = st.text_area("ЁЯФЧ Associated Symptoms", placeholder="Any other symptoms you've noticed") + duration = st.text_input("тП░ Duration", placeholder="e.g., 3 days, 1 week") + severity = st.selectbox("ЁЯУК Severity Level", ["Mild", "Moderate", "Severe"]) + additional_info = st.text_area("тД╣я╕П Additional Information", placeholder="Any other relevant details") + + submitted = st.form_submit_button("ЁЯТм Get AI Advice", use_container_width=True) + + if submitted: + if not primary_symptom: + st.error("тЭМ Please describe your primary symptom") + else: + with st.spinner("ЁЯдЦ AI is analyzing your symptoms..."): + try: + progress_bar = st.progress(0) + progress_bar.progress(33) + + client = Client("Pro-Coder/Skinalyze") + progress_bar.progress(66) + + result = client.predict( + primary_symptom=primary_symptom, + location=location, + associated_symptoms=associated_symptoms, + duration=duration, + severity=severity, + additional_info=additional_info, + api_name="/predict" + ) + progress_bar.progress(100) + + st.success("тЬЕ Analysis Complete!") + st.markdown("### ЁЯдЦ AI Recommendation") + + if isinstance(result, dict): + for key, value in result.items(): + st.markdown(f"**{key.title()}:** {value}") + else: + st.write(result) + + except Exception as e: + st.error(f"тЭМ Chatbot service unavailable: {str(e)}") + st.info("Please try again later or consult with a healthcare professional.") + + with col2: + st.markdown("### ЁЯЪи Medical Disclaimer") + st.error(""" + **Important:** This AI assistant provides general information only and is not a substitute for professional medical advice, diagnosis, or treatment. + + **Always seek the advice of your physician** or other qualified health provider with any questions about a medical condition. + """) + + st.markdown("### ЁЯУЮ Emergency Contacts") + st.info(""" + **If you have a medical emergency:** + - Call your local emergency number + - Go to the nearest emergency room + - Contact your healthcare provider immediately + """) + + st.markdown("
", unsafe_allow_html=True) -@app.route('/predict', methods=['GET', 'POST']) -def predict(): +# ----------------------------- +# ABOUT US PAGE +# ----------------------------- +elif menu == "About Us": + st.markdown(""" +
+

тД╣я╕П About Skinalyze

+

Revolutionizing skin health through AI-powered analysis

+
+ """, unsafe_allow_html=True) + + col1, col2 = st.columns(2) + + with col1: + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯОп Our Mission") + st.write(""" + Skinalyze is dedicated to making skin health analysis accessible to everyone through + cutting-edge artificial intelligence technology. We believe that early detection and + proper guidance can significantly improve skin health outcomes. + """) + + st.markdown("### ЁЯФм Technology") + st.write(""" + Our platform uses advanced deep learning models trained on thousands of skin condition + images to provide accurate analysis and recommendations. The AI continuously learns + and improves to deliver better results. + """) + st.markdown("
", unsafe_allow_html=True) + + with col2: + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯМЯ Features") + st.write(""" + - **AI Image Analysis**: Instant skin condition detection + - **Smart Chatbot**: Personalized medical guidance + - **Secure Platform**: Your data privacy is our priority + - **User Dashboard**: Track your analysis history + - **24/7 Availability**: Access anytime, anywhere + """) + + st.markdown("### ЁЯУз Contact Us") + st.write(""" + Have questions or feedback? We'd love to hear from you! + + - Email: support@skinalyze.com + - Phone: +1 (555) 123-4567 + - Website: www.skinalyze.com + """) + st.markdown("
", unsafe_allow_html=True) + + # Team section + st.markdown("
", unsafe_allow_html=True) + st.markdown("### ЁЯСе Our Team") + + team_col1, team_col2, team_col3 = st.columns(3) + + with team_col1: + st.markdown(""" +
+
ЁЯСитАНтЪХя╕П
+

Dr. Sarah Johnson

+

Chief Medical Officer

+ Dermatologist with 15+ years experience +
+ """, unsafe_allow_html=True) + + with team_col2: + st.markdown(""" +
+
ЁЯСитАНЁЯТ╗
+

Alex Chen

+

Lead AI Engineer

+ Machine Learning specialist in medical AI +
+ """, unsafe_allow_html=True) + + with team_col3: + st.markdown(""" +
+
ЁЯСйтАНЁЯТ╝
+

Emily Rodriguez

+

Product Manager

+ Healthcare technology expert +
+ """, unsafe_allow_html=True) + + st.markdown("
", unsafe_allow_html=True) - result = None - form_data = request.form - primary_symptom = form_data.get('primary_symptom', '') - location = form_data.get('location', '') - associated_symptoms = form_data.get('associated_symptoms', '') - duration = form_data.get('duration', '') - severity = form_data.get('severity', '') - additional_info = form_data.get('additional_info', '') +# ----------------------------- +# MATERNAL HEALTH RISK PREDICTOR +# ----------------------------- +elif menu == "Maternal Health": + st.markdown(f""" +
+

{T("maternal_title")}

+

{T("maternal_desc")}

+
+ """, unsafe_allow_html=True) + + if maternal_model is None: + st.error("тЪая╕П Maternal health model not available. Please ensure model files are properly loaded.") + st.info("This feature requires the maternal risk prediction model to be available.") + else: + st.markdown("
", unsafe_allow_html=True) + st.markdown(f"### {T('vitals_header')}") + + col1, col2 = st.columns(2) + with col1: + age = st.number_input(T("age"), 10, 70, 25, 1) + systolic_bp = st.number_input(T("systolic_bp"), 70, 180, 120, 1) + diastolic_bp = st.number_input(T("diastolic_bp"), 40, 120, 80, 1) + with col2: + bs = st.number_input(T("bs"), 6.0, 19.0, 7.5, 0.1, "%.1f") + body_temp = st.number_input(T("body_temp"), 96.0, 104.0, 98.6, 0.1, "%.1f") + heart_rate = st.number_input(T("heart_rate"), 60, 100, 75, 1) + if st.button(T("assess_button"), use_container_width=True, type="primary"): + input_data = pd.DataFrame({ + 'Age': [age], + 'SystolicBP': [systolic_bp], + 'DiastolicBP': [diastolic_bp], + 'BS': [bs], + 'BodyTemp': [body_temp], + 'HeartRate': [heart_rate] + }) + + with st.spinner(T("analyzing")): + time.sleep(1) + try: + prediction = maternal_model.predict(input_data)[0] + + st.divider() + st.markdown(f"### {T('result_header')}") + + # Risk level translation + risk_translation = {"low risk": "Low Risk", "mid risk": "Mid Risk", "high risk": "High Risk"} + if st.session_state.lang == "mr": + risk_translation = {"low risk": "рдХрдореА рдЬреЛрдЦреАрдо", "mid risk": "рдордзреНрдпрдо рдЬреЛрдЦреАрдо", "high risk": "рдЙрдЪреНрдЪ рдЬреЛрдЦреАрдо"} + elif st.session_state.lang == "hi": + risk_translation = {"low risk": "рдХрдо рдЬреЛрдЦрд┐рдо", "mid risk": "рдордзреНрдпрдо рдЬреЛрдЦрд┐рдо", "high risk": "рдЙрдЪреНрдЪ рдЬреЛрдЦрд┐рдо"} + if prediction == 'low risk': + st.success(f"**{T('outcome_prefix')}: {risk_translation[prediction]}**") + st.info(T("low_risk_rec")) + elif prediction == 'mid risk': + st.warning(f"**{T('outcome_prefix')}: {risk_translation[prediction]}**") + st.warning(T("mid_risk_rec")) + else: + st.error(f"**{T('outcome_prefix')}: {risk_translation[prediction]}**") + st.error(T("high_risk_rec")) + + except Exception as e: + st.error(f"Error making prediction: {str(e)}") + + st.markdown("
", unsafe_allow_html=True) - from gradio_client import Client +# ----------------------------- +# GENERAL DISEASE PREDICTOR +# ----------------------------- +elif menu == "Disease Prediction": + st.markdown(f""" +
+

{T("disease_title")}

+

{T("disease_desc")}

+
+ """, unsafe_allow_html=True) + + if disease_model is None or disease_encoder is None: + st.error("тЪая╕П Disease prediction model not available. Please ensure model files are properly loaded.") + st.info("This feature requires the disease prediction model and encoder to be available.") + else: + st.markdown("
", unsafe_allow_html=True) + st.markdown(f"### {T('symptoms_header')}") + + selected_symptoms = st.multiselect( + T("symptoms_placeholder"), + options=symptom_list, + help=T("symptoms_help") + ) - client = Client("Pro-Coder/Skinalyze") - result = client.predict( - primary_symptom=primary_symptom, - location=location, - associated_symptoms=associated_symptoms, - duration=duration, - severity=severity, - additional_info=additional_info, - api_name="/predict" - ) - return jsonify(result) + if st.button(T("predict_button"), use_container_width=True, type="primary"): + if not selected_symptoms: + st.warning(T("no_symptom_warn")) + else: + input_vector = [0] * len(symptom_list) + for symptom in selected_symptoms: + if symptom in symptom_list: + input_vector[symptom_list.index(symptom)] = 1 + + with st.spinner(T("analyzing")): + time.sleep(1) + try: + numeric_prediction = disease_model.predict([input_vector])[0] + disease_name = disease_encoder.inverse_transform([numeric_prediction])[0] -@app.route("/about_us") -def aboutus(): - return render_template("aboutUs.html") + st.divider() + st.markdown(f"### {T('diagnosis_header')}") + st.success(f"**{T('predicted_condition')}: {disease_name}**") + st.warning(T("disclaimer")) + + # Store prediction in history + prediction_record = { + 'date': datetime.now().strftime("%Y-%m-%d %H:%M"), + 'type': 'Disease Prediction', + 'symptoms': selected_symptoms, + 'prediction': disease_name + } + st.session_state.prediction_history.append(prediction_record) + + except Exception as e: + st.error(f"Error making prediction: {str(e)}") + + st.markdown("
", unsafe_allow_html=True) -if __name__ == "__main__": # Run the application +# ----------------------------- +# LOGOUT +# ----------------------------- +elif menu == "Logout": + if st.session_state.logged_in: + st.session_state.logged_in = False + st.session_state.username = None + st.success("тЬЕ You have been successfully logged out.") + st.info("Thank you for using Skinalyze! Come back anytime.") + st.balloons() + else: + st.info("You are not currently logged in.") - with app.app_context(): - db.create_all() - app.run(debug=True) +# ----------------------------- +# FOOTER +# ----------------------------- +st.markdown("---") +st.markdown(""" +
+

┬й 2024 Skinalyze. All rights reserved. | Made with тЭдя╕П using Streamlit

+

ЁЯФТ Your privacy and data security are our top priorities

+
+""", unsafe_allow_html=True) \ No newline at end of file diff --git a/database/README.md b/database/README.md new file mode 100644 index 0000000..c4d0be3 --- /dev/null +++ b/database/README.md @@ -0,0 +1,31 @@ +# Database Files + +This directory should contain the training data for the health prediction models. + +## Required Files: + +1. **Training.csv** - Dataset containing symptom-disease mappings for disease prediction + +## Training.csv Format: + +The CSV should have: +- Columns for each symptom (binary 0/1 values) +- Final column named 'prognosis' with disease names +- Each row represents a patient case + +Example structure: +```csv +itching,skin_rash,continuous_sneezing,shivering,chills,joint_pain,stomach_pain,...,prognosis +1,1,0,0,0,0,0,...,Fungal infection +0,0,1,1,1,0,0,...,Common Cold +... +``` + +## Note: + +Without the Training.csv file, the application will use a default symptom list but disease prediction may not work optimally. + +To add your data: +1. Prepare your symptom-disease dataset in the required format +2. Save as Training.csv in this directory +3. Restart the application \ No newline at end of file diff --git a/model/README.md b/model/README.md new file mode 100644 index 0000000..dcf7add --- /dev/null +++ b/model/README.md @@ -0,0 +1,26 @@ +# Model Files + +This directory should contain the following model files for the health prediction features: + +## Required Files: + +1. **maternal_risk_model.joblib** - Trained model for maternal health risk prediction +2. **disease_model.joblib** - Trained model for general disease prediction +3. **disease_label_encoder.joblib** - Label encoder for disease prediction model + +## Model Training: + +These models should be trained using appropriate datasets: + +- **Maternal Health Risk**: Train on maternal health datasets with features like Age, SystolicBP, DiastolicBP, BS, BodyTemp, HeartRate +- **Disease Prediction**: Train on symptom-disease datasets with binary symptom features + +## Note: + +Without these model files, the corresponding features will show error messages and won't function. The application will still work for other features like skin analysis and user management. + +To add your models: +1. Train your models using scikit-learn or similar +2. Save them using joblib.dump() +3. Place the .joblib files in this directory +4. Restart the application \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index b38cc3f..87b3d6a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,11 +1,8 @@ -Flask==3.1.0 -Flask-SQLAlchemy==3.1.1 -Flask-Bcrypt==1.0.1 -Flask-Login==0.6.3 -Flask-WTF==1.2.2 -gunicorn -nltk==3.8.1 -torch==2.2.0 -sentence-transformers==2.5.1 -numpy==1.26.3 -gradio_client +streamlit>=1.28.0 +bcrypt>=4.0.0 +gradio-client>=0.7.0 +Pillow>=9.0.0 +plotly>=5.15.0 +pandas>=1.5.0 +joblib>=1.3.0 +scikit-learn>=1.3.0 \ No newline at end of file