Spaces:
Runtime error
Runtime error
File size: 9,061 Bytes
d4b3047 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
# 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()
|