import os import tensorflow as tf import pandas as pd import gradio as gr # Load the model # Load the model dynamically from the current directory model_path = "model.keras" try: model = tf.keras.models.load_model(model_path) print(f"Model loaded successfully from: {model_path}") except Exception as e: raise RuntimeError(f"Failed to load the model from {model_path}: {e}") # Define the risk classes classes = [ 'No Immediate Risk: No urgent concerns detected. Maintain self-care and regular check-ups.', 'Medium Risk of Harm - Needs Monitoring: Consider consulting a psychiatrist or mental health professional for guidance and treatment.', 'Immediate Concern - Needs Urgent Support: Seek immediate help from a psychiatrist or mental health crisis intervention services.' ] # Yes/No mapping for questions yes_no_mapping = { 'q1': {'yes': 0.1, 'no': 0}, 'q2': {'yes': 0.1, 'no': 0}, 'q3': {'yes': 0.1, 'no': 0}, 'q4': {'yes': 0.1, 'no': 0}, 'q5': {'yes': 0.1, 'no': 0}, 'q6': {'yes': 0.1, 'no': 0}, 'q7': {'yes': 0.1, 'no': 0}, 'q8': {'yes': 0.1, 'no': 0}, 'q9': {'yes': 0.1, 'no': 0}, 'q10': {'yes': 0.1, 'no': 0}, 'q11': {'yes': 0.5, 'no': 0}, 'q12': {'yes': 0.7, 'no': 0}, 'q13': {'yes': 0.5, 'no': 0}, 'q14': {'yes': 0.5, 'no': 0}, 'q15': {'yes': 0.5, 'no': 0}, 'q16': {'yes': 0.5, 'no': 0}, 'q17': {'yes': 0.7, 'no': 0}, 'q18': {'yes': 0.7, 'no': 0}, 'q19': {'yes': 0.7, 'no': 0}, 'q20': {'yes': 0.7, 'no': 0}, 'q21': {'yes': 0.7, 'no': 0}, 'q22': {'yes': 0.7, 'no': 0}, 'q23': {'yes': 0.7, 'no': 0}, 'q24': {'yes': 0.7, 'no': 0}, 'q25': {'yes': 0.7, 'no': 0}, 'q26': {'yes': 0.7, 'no': 0}, 'q27': {'yes': 0.9, 'no': 0}, 'q28': {'yes': 0.9, 'no': 0}, 'q29': {'yes': 0.9, 'no': 0}, 'q30': {'yes': 0.9, 'no': 0}, 'q31': {'yes': 1, 'no': 0}, 'q32': {'yes': 1, 'no': 0}, 'q33': {'yes': 1, 'no': 0} } # Store responses in a DataFrame responses_df = pd.DataFrame(columns=["Name", "ID", "Predicted Risk Level"]) # Function to process form input def predict_from_form(name, id_number, *responses): global responses_df try: # Map Yes/No to numeric processed_data = [yes_no_mapping[f'q{i+1}'][response.lower()] for i, response in enumerate(responses)] input_data = pd.DataFrame([processed_data], columns=[f'q{i+1}' for i in range(len(responses))]) # Predict using model predictions = model.predict(input_data) predicted_class = predictions.argmax(axis=1)[0] # Store the result new_entry = {"Name": name or "N/A", "ID": id_number or "N/A", "Predicted Risk Level": classes[predicted_class]} responses_df = pd.concat([responses_df, pd.DataFrame([new_entry])], ignore_index=True) return f"Prediction for {name or 'Anonymous'}: {classes[predicted_class]}" except Exception as e: return f"Error: {e}" # Function to view all recorded responses def view_responses(): if responses_df.empty: return "No responses recorded yet." return responses_df # Function to download responses as CSV def download_responses(): file_path = "results.csv" try: # Save the responses to a CSV file responses_df.to_csv(file_path, index=False) print(f"Responses saved to {file_path}") return file_path except Exception as e: return f"Error saving file: {e}" # Define Gradio Inputs form_inputs = [ gr.Textbox(label="Name (Optional)"), gr.Textbox(label="ID (Optional)") ] form_inputs.extend([ gr.Radio(["Yes", "No"], label="Is your age less than 18 years?", info="**Select 'Yes' if you are under 18. Otherwise, select 'No'.**"), # q1 gr.Radio(["Yes", "No"], label="Are you Male?", info="**Select 'Yes' if you identify as male. Otherwise, select 'No'.**"), # q2 gr.Radio(["Yes", "No"], label="Have financial concerns been a source of stress for you or your family?", info="**This includes challenges like debt, job loss, tuition fees, or difficulty covering daily expenses.**"), # q3 gr.Radio(["Yes", "No"], label="Are you currently living alone, and unsatisfied with your living situation?", info="**Select 'Yes' if you live alone and feel unhappy or unsupported in your environment.**"), # q4 gr.Radio(["Yes", "No"], label="Are you living in a hostel or dormitory and unsatisfied with your living situation?", info="**Select 'Yes' if you live in shared accommodations like a hostel or dorm and feel unhappy.**"), # q5 gr.Radio(["Yes", "No"], label="Do you feel like you are pursuing your current path mainly because of your family’s expectations?", info="**This includes academic, career, or personal decisions made primarily to satisfy family expectations.**"), # q6 gr.Radio(["Yes", "No"], label="Have you been feeling disappointed with your performance recently?", info="**This applies to academic, professional, or personal performance where you feel dissatisfied with yourself.**"), # q7 gr.Radio(["Yes", "No"], label="Do you feel like your family is unhappy with your performance or choices?", info="**Consider whether you feel judged or unsupported by your family for academic, professional, or personal reasons.**"), # q8 gr.Radio(["Yes", "No"], label="Are there several problems in your family, or is your family environment very stressful?", info="**This includes frequent arguments, lack of support, or other issues causing emotional stress at home.**"), # q9 gr.Radio(["Yes", "No"], label="Does your family not support your decisions or choices?", info="**Select 'Yes' if your family has expressed disapproval of significant life choices like career or relationships.**"), # q10 gr.Radio(["Yes", "No"], label="Have you recently experienced a breakup?", info="**This includes the end of romantic relationships or close friendships.**"), # q11 gr.Radio(["Yes", "No"], label="Have you ever suffered from any mental illness in the past or are you currently suffering?", info="**This includes diagnosed or undiagnosed conditions like depression, anxiety, or PTSD.**"), # q12 gr.Radio(["Yes", "No"], label="Is there any history of psychiatric illness in your family?", info="**Consider conditions like depression, bipolar disorder, or anxiety disorders among close family members.**"), # q13 gr.Radio(["Yes", "No"], label="Has any close family member recently or in the past committed suicide?", info="**Select 'Yes' if you've lost a family member to suicide.**"), # q14 gr.Radio(["Yes", "No"], label="Has any close friend recently committed suicide?", info="**Select 'Yes' if you've lost a friend or close acquaintance to suicide.**"), # q15 gr.Radio(["Yes", "No"], label="Are you suffering from any medical illness like diabetes, asthma, hypertension, or other chronic illness?", info="**This includes long-term physical health conditions that might impact your mental well-being.**"), # q16 gr.Radio(["Yes", "No"], label="Have you found yourself using alcohol, drugs, or online gaming to cope with stress recently?", info="**This includes any substance or behavior used to escape stress or emotions.**"), # q17 gr.Radio(["Yes", "No"], label="Have you ever experienced any form of abuse?", info="**This includes physical, emotional, sexual, or verbal abuse at any stage of life.**"), # q18 gr.Radio(["Yes", "No"], label="Have you been feeling emotionally numb or disconnected over the past few days?", info="**Consider whether you've felt detached from emotions, others, or reality recently.**"), # q19 gr.Radio(["Yes", "No"], label="Are you feeling very sad or anxious over the last few days?", info="**This includes persistent feelings of sadness, worry, or unease.**"), # q20 gr.Radio(["Yes", "No"], label="Have you been feeling hurt or embarrassed by things others have said recently?", info="**Consider if recent comments or actions from others have affected your emotional well-being.**"), # q21 gr.Radio(["Yes", "No"], label="Have you been feeling trapped in your current situation?", info="**Select 'Yes' if you've felt unable to escape a stressful or challenging situation.**"), # q22 gr.Radio(["Yes", "No"], label="Have you been feeling particularly lonely over the past few days?", info="**Consider whether you've felt isolated or without companionship recently.**"), # q23 gr.Radio(["Yes", "No"], label="Have you been feeling uncertain or hopeless about your future?", info="**Select 'Yes' if you've felt unsure or negative about what lies ahead.**"), # q24 gr.Radio(["Yes", "No"], label="Have you lost interest in things you usually enjoy over the past few days?", info="**This includes hobbies, activities, or relationships that normally bring you happiness.**"), # q25 gr.Radio(["Yes", "No"], label="Have you been struggling with sleep recently, either finding it hard to fall asleep or stay asleep?", info="**This includes difficulty falling asleep, staying asleep, or waking up too early.**"), # q26 gr.Radio(["Yes", "No"], label="Have thoughts about hurting yourself crossed your mind?", info="**Select 'Yes' if you've had any thoughts about self-harm, even if fleeting.**"), # q27 gr.Radio(["Yes", "No"], label="Have you felt like life has been overwhelming recently?", info="**Consider whether you've felt unable to manage daily stressors effectively.**"), # q28 gr.Radio(["Yes", "No"], label="Have you been feeling a lack of motivation or desire to keep going in life?", info="**This includes a general sense of apathy or disinterest in life.**"), # q29 gr.Radio(["Yes", "No"], label="Have you been feeling like hurting yourself recently?", info="**Select 'Yes' if you've had persistent or recent thoughts about self-harm.**"), # q30 gr.Radio(["Yes", "No"], label="Have you been searching online for information related to suicide?", info="**Select 'Yes' if you've researched suicide methods or related topics online.**"), # q31 gr.Radio(["Yes", "No"], label="Have you been feeling so distressed that you’ve considered or planned how to end your life?", info="**Select 'Yes' if you've had specific thoughts or plans about ending your life.**"), # q32 gr.Radio(["Yes", "No"], label="Have you previously had moments where you tried to harm yourself or end your life?", info="**Select 'Yes' if you've attempted self-harm or suicide in the past.**"), # q33 ]) import gradio as gr # Tabbed Interface interface = gr.TabbedInterface( [ # Manual Form Submission Tab gr.Interface( fn=predict_from_form, inputs=form_inputs, outputs="text", title="PsyRiskAI – AI-Based Assessment of 33 Mental Health Risk Factors", description=( "### Instructions\n" "1. **For Individual Users**: Use a unique and special name instead of your real name to maintain privacy.\n" "2. **For Administrators/Mental Health Professionals**: Assign a unique special ID to each individual to ensure confidentiality, particularly for mass screenings.\n" "3. **Mass Screening**: Share the following link with all participants: " "[Self-Harm Risk Evaluator](https://huggingface.co/spaces/drvikasgaur/Self-Harm-Risk-Evaluator). " "Participants can complete the questionnaire anytime or simultaneously. Results are instantly analyzed and securely accessible by administrators.\n" "4. Respond to all 33 questions by selecting **'Yes'** or **'No'**. **All questions must be answered to generate a result.**\n" "5. **Click 'Submit'**: The result will be displayed immediately in the output section. Please scroll up again to output section to view the result.\n\n" "**Your responses will be analyzed using a deep learning model (Artificial Neural Network) to determine the predicted risk level.**" ), article=( "### Disclaimer\n" "**This application is for educational purposes only and is not a substitute for professional medical advice, diagnosis, or treatment.** " "Always seek advice from a psychiatrist or qualified health provider regarding any psychiatric or medical condition.\n\n" "**If you are in crisis or think you may have an emergency, contact a doctor or emergency services immediately.**" ), ), # View Responses Tab gr.Interface( fn=view_responses, inputs=None, outputs="dataframe", title="View All Responses", description=( "### Instructions\n" "1. **For Administrators / Mental Health Professionals:** Use this section to view all recorded responses and their predicted risk levels.\n" "2. Responses are stored only for this session and will not persist after the app is closed." ), ), # Download Responses Tab gr.Interface( fn=download_responses, inputs=None, outputs=gr.File(label="Download Results"), title="Download Results", description=( "### Instructions\n" "1. **For Administrators / Mental Health Professionals:** Use this section to download all recorded responses as a CSV file.\n" "2. **Click Generate**: This will allow you to save and analyze the data offline." ), ), ], tab_names=["Manual Form Submission", "View All Responses", "Download Results"], ) # Launch the Gradio app if __name__ == "__main__": interface.launch()