Phoenix21's picture
first commit
d4b3047
# app.py
import gradio as gr
import json
import re
from pipeline import process_answers_pipeline
from questions import questions
def extract_report_content(report_text):
"""Extract the actual report content from the report field."""
try:
if isinstance(report_text, str) and report_text.startswith('{'):
report_dict = eval(report_text)
return report_dict.get('report', '').strip()
except:
pass
return report_text.strip()
def parse_recommendation_array_and_text(raw_recommendation):
"""
1) Extract the bracketed JSON array of packages
2) Return the remainder of the text for further parsing.
"""
array_match = re.search(r'\[(.*?)\]', raw_recommendation, flags=re.DOTALL)
if array_match:
try:
packages_list = json.loads(f"[{array_match.group(1)}]")
packages_list = [p.strip() for p in packages_list if isinstance(p, str)]
except:
packages_list = []
else:
packages_list = []
end_of_array = array_match.end() if array_match else 0
remainder_text = raw_recommendation[end_of_array:].strip()
return packages_list, remainder_text
def parse_package_descriptions(text):
"""Parse package descriptions from text using regex."""
mental_match = re.search(
r"\*\*High Stress/Anxiety:\*\*(.*?)(?=\*\*|$)",
text,
flags=re.DOTALL
)
mental_text = mental_match.group(1).strip() if mental_match else ""
fitness_match = re.search(
r"\*\*Moderate Fitness & Mobility:\*\*(.*?)(?=\*\*|$)",
text,
flags=re.DOTALL
)
fitness_text = fitness_match.group(1).strip() if fitness_match else ""
gut_match = re.search(
r"\*\*Gut Health:\*\*(.*?)(?=\*\*|$)",
text,
flags=re.DOTALL
)
gut_text = gut_match.group(1).strip() if gut_match else ""
insomnia_match = re.search(
r"\*\*No More Insomnia:\*\*(.*?)(?=\*\*|$)",
text,
flags=re.DOTALL
)
insomnia_text = insomnia_match.group(1).strip() if insomnia_match else ""
just_match = re.search(
r"\*\*Justification for Exclusion:\*\*(.*?)(?=$)",
text,
flags=re.DOTALL
)
justification_text = just_match.group(1).strip() if just_match else ""
return {
"mental_wellness": mental_text,
"fitness_mobility": fitness_text,
"gut_health": gut_text,
"no_more_insomnia": insomnia_text,
"justification": justification_text
}
def process_answers(
sleep,
exercise,
mood,
stress_level,
wellness_goals,
dietary_restrictions,
relaxation_time,
health_issues,
water_intake,
gratitude_feelings,
connection_rating,
energy_rating
):
responses = {
questions[0]: sleep,
questions[1]: exercise,
questions[2]: mood,
questions[3]: stress_level,
questions[4]: wellness_goals,
questions[5]: dietary_restrictions,
questions[7]: relaxation_time,
questions[8]: health_issues,
questions[12]: water_intake,
questions[23]: gratitude_feelings,
questions[24]: connection_rating,
questions[27]: energy_rating
}
try:
# Run the pipeline
results = process_answers_pipeline(responses)
# Capture the entire pipeline response as a string
complete_response = str(results)# removed complete response
# Extract individual fields
wellness_report = extract_report_content(results.get('report', ''))
# Extract final_summary and shortened_summary
final_summary = results.get('final_summary', '')
shortened_summary = results.get('shortened_summary', '')
problems_data = results.get('problems', {})
identified_problems = {
"stress_management": float(str(problems_data.get('stress_management', 0)).replace('%', '')),
"low_therapy": float(str(problems_data.get('low_therapy', 0)).replace('%', '')),
"balanced_weight": float(str(problems_data.get('balanced_weight', 0)).replace('%', '')),
"restless_night": float(str(problems_data.get('restless_night', 0)).replace('%', '')),
"lack_of_motivation": float(str(problems_data.get('lack_of_motivation', 0)).replace('%', '')),
"gut_health": float(str(problems_data.get('gut_health', 0)).replace('%', '')),
"anxiety": float(str(problems_data.get('anxiety', 0)).replace('%', '')),
"burnout": float(str(problems_data.get('burnout', 0)).replace('%', ''))
}
raw_recommendation = results.get('recommendation', '').strip()
recommended_packages, remainder_text = parse_recommendation_array_and_text(raw_recommendation)
descriptions = parse_package_descriptions(remainder_text)
recommendations_with_description = []
for pkg in recommended_packages:
if pkg == "Mental Wellness":
final_desc = (
"**High Stress/Anxiety:** "
+ descriptions["mental_wellness"]
)
elif pkg == "Fitness & Mobility":
final_desc = (
"**Moderate Fitness & Mobility:** "
+ descriptions["fitness_mobility"]
)
elif pkg == "Gut Health":
final_desc = (
"**Gut Health:** "
+ descriptions["gut_health"]
)
elif pkg == "No More Insomnia":
final_desc = (
"**No More Insomnia:** "
+ descriptions["no_more_insomnia"]
)
else:
final_desc = ""
recommendations_with_description.append({
"package": pkg,
"description": final_desc
})
return {
# "complete_response": complete_response,# removed complete response
"wellness_report": wellness_report,
"identified_problems": identified_problems,
"recommended_packages": recommended_packages,
"recommendations_with_description": recommendations_with_description,
"exclusion_justification": descriptions["justification"],
"user summary": final_summary, # ADDED
"video script": shortened_summary # ADDED
}
except Exception as e:
return {
"error": f"Error processing answers: {str(e)}",
"complete_response": str(results) if 'results' in locals() else "No results generated"
}
# Create the Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Wellness Assessment")
with gr.Row():
with gr.Column():
sleep = gr.Textbox(
label="How many hours of sleep do you get each night?"
)
exercise = gr.Textbox(
label="How often do you exercise in a week?"
)
mood = gr.Textbox(
label="On a scale of 1 to 10, how would you rate your mood today?"
)
stress_level = gr.Textbox(
label="On a scale from 1 to 10, what is your current stress level?"
)
wellness_goals = gr.Textbox(
label="What are your primary wellness goals?"
)
dietary_restrictions = gr.Textbox(
label="Do you follow any specific diet or have any dietary restrictions?"
)
relaxation_time = gr.Textbox(
label="How much time do you spend on relaxation or mindfulness activities daily?"
)
health_issues = gr.Textbox(
label="How would you rate your health and wellness on a scale of 1 to 10?"
)
water_intake = gr.Textbox(
label="How much water do you drink on average per day?"
)
gratitude_feelings = gr.Textbox(
label="How often do you experience feelings of gratitude or happiness?"
)
connection_rating = gr.Textbox(
label="On a scale from 1 to 10, how will you define your human relations ?"
)
energy_rating = gr.Textbox(
label="On a scale from 1 to 10, how would you rate your energy levels throughout the day?"
)
submit_btn = gr.Button("Submit")
output = gr.JSON()
submit_btn.click(
fn=process_answers,
inputs=[
sleep, exercise, mood, stress_level, wellness_goals,
dietary_restrictions, relaxation_time, health_issues,
water_intake, gratitude_feelings, connection_rating,
energy_rating
],
outputs=output
)
if __name__ == "__main__":
demo.launch()