Spaces:
Sleeping
Sleeping
Download app.py from aysan98/empathy-map-interview: direct link, hf CLI and curl.
- Browser
- Download file 27 kB
-
https://huggingface.co/spaces/aysan98/empathy-map-interview/resolve/main/app.py
- Command line
-
hf download hf://spaces/aysan98/empathy-map-interview/app.py
-
curl -L -o app.py https://huggingface.co/spaces/aysan98/empathy-map-interview/resolve/main/app.py
27 kB
| import gradio as gr | |
| import uuid | |
| import os | |
| from datetime import datetime | |
| from agents import QuestionGeneratorAgent, SynthesisAgent | |
| from storage import ( | |
| add_session, add_response, get_session, | |
| get_all_responses, update_global_analysis, | |
| get_global_data, get_unique_studies, get_responses_by_study | |
| ) | |
| from validator import validate_response_quality, generate_research_followup | |
| # Get Groq API key from environment | |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY") | |
| def create_app(): | |
| with gr.Blocks(title="Empathy Map Interview System", css=""" | |
| .stat-card { | |
| background: #f8f9fa; | |
| padding: 15px; | |
| border-radius: 8px; | |
| border: 1px solid #dee2e6; | |
| } | |
| .section-header { | |
| font-size: 18px; | |
| font-weight: 600; | |
| margin-top: 20px; | |
| margin-bottom: 10px; | |
| } | |
| .insight-item { | |
| background: white; | |
| padding: 12px; | |
| margin: 8px 0; | |
| border-left: 3px solid #3498db; | |
| border-radius: 4px; | |
| } | |
| .percentage { | |
| color: #3498db; | |
| font-weight: 600; | |
| } | |
| .quote { | |
| font-style: italic; | |
| color: #6c757d; | |
| margin-left: 15px; | |
| padding: 5px 0; | |
| } | |
| """) as app: | |
| gr.Markdown("# Empathy Map AI Interview System") | |
| gr.Markdown("Evidence-based customer research powered by AI") | |
| if not GROQ_API_KEY: | |
| gr.Markdown("⚠️ **Warning**: GROQ_API_KEY not found in environment variables. Please add it to Space Secrets.") | |
| with gr.Tab("Create Interview"): | |
| gr.Markdown("### Design Interview Questions") | |
| query_input = gr.Textbox( | |
| label="Customer Segment / Research Focus", | |
| lines=2, | |
| placeholder="e.g., Premium sports shoe buyers, Small business owners looking for accounting software" | |
| ) | |
| context_input = gr.Textbox( | |
| label="Study Name / Context (recommended for organizing multiple studies)", | |
| lines=2, | |
| placeholder="e.g., Q4 2024 Footwear Research, SaaS Buyer Study, Coffee Shop Customers - Winter 2024" | |
| ) | |
| generate_btn = gr.Button("Generate Interview Questions", variant="primary", size="lg") | |
| questions_display = gr.Dataframe( | |
| headers=["ID", "Section", "Question"], | |
| datatype=["number", "str", "str"], | |
| interactive=True, | |
| label="Generated Questions (editable)" | |
| ) | |
| save_btn = gr.Button("Save & Create Session", variant="primary") | |
| status = gr.Textbox(label="Status", interactive=False) | |
| link_box = gr.Textbox(label="Session ID (share with respondents)", visible=False, interactive=True) | |
| questions_state = gr.State([]) | |
| def generate_q(query, context): | |
| if not GROQ_API_KEY: | |
| return None, "Error: GROQ_API_KEY not configured. Please add it to Space Secrets.", [], "", False | |
| if not query or not query.strip(): | |
| return None, "Please provide a customer segment or research focus", [], "", False | |
| try: | |
| agent = QuestionGeneratorAgent(GROQ_API_KEY) | |
| result = agent.generate(query, context) | |
| questions = result.get('questions', []) | |
| df_data = [[q['id'], q['section'], q['question']] for q in questions] | |
| return df_data, f"Generated {len(questions)} research questions", questions, "", False | |
| except Exception as e: | |
| return None, f"Error: {str(e)}", [], "", False | |
| def save_q(df_data, query, context): | |
| try: | |
| if not GROQ_API_KEY: | |
| return [], "Error: GROQ_API_KEY not configured", "", False | |
| if df_data is None or len(df_data) == 0: | |
| return [], "No questions to save", "", False | |
| questions = [] | |
| if hasattr(df_data, 'values'): | |
| rows = df_data.values.tolist() | |
| else: | |
| rows = df_data | |
| for i, row in enumerate(rows): | |
| if not row or len(row) < 3 or not str(row[2]).strip(): | |
| continue | |
| try: | |
| id_num = int(float(row[0])) | |
| except: | |
| id_num = i + 1 | |
| questions.append({ | |
| 'id': id_num, | |
| 'section': str(row[1]).strip() if row[1] else 'general', | |
| 'question': str(row[2]).strip() | |
| }) | |
| if not questions: | |
| return [], "No valid questions found", "", False | |
| session_id = str(uuid.uuid4())[:8] | |
| # Use context as study identifier, or use query if context is empty | |
| study_name = context.strip() if context and context.strip() else query.strip() | |
| add_session(session_id, questions, GROQ_API_KEY, study_name) | |
| return questions, f"Session created successfully! ID: {session_id}", session_id, True | |
| except Exception as e: | |
| return [], f"Error: {str(e)}", "", False | |
| generate_btn.click( | |
| generate_q, | |
| [query_input, context_input], | |
| [questions_display, status, questions_state, link_box, link_box] | |
| ) | |
| save_btn.click( | |
| save_q, | |
| [questions_display, query_input, context_input], | |
| [questions_state, status, link_box, link_box] | |
| ) | |
| with gr.Tab("Interview Form"): | |
| gr.Markdown("### Respondent Interview") | |
| gr.Markdown("Enter the Session ID provided by the researcher to begin") | |
| session_input = gr.Textbox(label="Session ID", placeholder="Enter 8-character session ID") | |
| load_btn = gr.Button("Load Interview", variant="primary") | |
| chatbot = gr.Chatbot(label="Interview", height=400, visible=False) | |
| answer = gr.Textbox(label="Your Answer", lines=4, visible=False, placeholder="Please provide detailed, specific answers based on your actual experience...") | |
| next_btn = gr.Button("Next Question", visible=False) | |
| submit_btn = gr.Button("Submit Interview", variant="primary", visible=False) | |
| interview_status = gr.Textbox(label="Status") | |
| idx = gr.State(0) | |
| history = gr.State([]) | |
| responses = gr.State([]) | |
| loaded_id = gr.State("") | |
| attempt_count = gr.State(0) | |
| current_original_q = gr.State({}) | |
| previous_answers = gr.State([]) | |
| def load_interview(sid): | |
| session = get_session(sid) | |
| if not session: | |
| return ( | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| gr.update(visible=False), | |
| "Invalid Session ID", | |
| [], | |
| 0, | |
| [], | |
| "", | |
| 0, | |
| {}, | |
| [] | |
| ) | |
| q1 = session['questions'][0] | |
| total = len(session['questions']) | |
| h = [ | |
| { | |
| "role": "assistant", | |
| "content": f"Welcome! This interview has {total} questions.\n\nQuestion 1 of {total}\n\n{q1['question']}" | |
| } | |
| ] | |
| return ( | |
| gr.update(visible=True, value=h), | |
| gr.update(visible=True), | |
| gr.update(visible=True), | |
| gr.update(visible=True), | |
| "Interview loaded. Please provide detailed, specific answers based on your actual experiences.", | |
| h, | |
| 0, | |
| [], | |
| sid, | |
| 0, | |
| q1, | |
| [] | |
| ) | |
| def next_q(ans, sid, idx, hist, resp, attempt_count, current_q, prev_answers): | |
| if not ans or not ans.strip(): | |
| return hist, "Please provide an answer", idx, resp, attempt_count, current_q, prev_answers, "" | |
| if not GROQ_API_KEY: | |
| return hist, "Error: API key not configured", idx, resp, attempt_count, current_q, prev_answers, "" | |
| session = get_session(sid) | |
| if not session: | |
| return hist, "Invalid session", idx, resp, attempt_count, current_q, prev_answers, "" | |
| qs = session['questions'] | |
| total = len(qs) | |
| # Validate answer quality | |
| validation = validate_response_quality(ans, current_q.get('question', qs[idx]['question']), current_q.get('section', qs[idx]['section']), GROQ_API_KEY) | |
| # Add current answer to history | |
| prev_answers.append(ans) | |
| # Check if we need follow-up (score <= 2 and attempts < 2) | |
| if validation['score'] <= 2 and attempt_count < 2: | |
| attempt_count += 1 | |
| if attempt_count == 1 and not current_q: | |
| current_q = qs[idx] | |
| # Generate intelligent follow-up | |
| follow_up = generate_research_followup( | |
| current_q.get('question', qs[idx]['question']), | |
| ans, | |
| current_q.get('section', qs[idx]['section']), | |
| attempt_count, | |
| GROQ_API_KEY | |
| ) | |
| hist.append({"role": "user", "content": ans}) | |
| hist.append({"role": "assistant", "content": follow_up}) | |
| return ( | |
| hist, | |
| f"Follow-up question (Attempt {attempt_count + 1}/3): {validation.get('reason', 'Need more detail')}", | |
| idx, | |
| resp, | |
| attempt_count, | |
| current_q, | |
| prev_answers, | |
| "" | |
| ) | |
| # Answer is acceptable or max attempts reached | |
| hist.append({"role": "user", "content": ans}) | |
| # Save response with all attempts | |
| question_to_save = current_q.get('question') if current_q else qs[idx]['question'] | |
| section_to_save = current_q.get('section') if current_q else qs[idx]['section'] | |
| # Combine all answers from attempts | |
| combined_answer = " | ".join(prev_answers) if len(prev_answers) > 1 else ans | |
| resp.append({ | |
| 'q': question_to_save, | |
| 'a': combined_answer, | |
| 'section': section_to_save, | |
| 'attempts': attempt_count + 1, | |
| 'quality_score': validation['score'] | |
| }) | |
| # Reset for next question | |
| attempt_count = 0 | |
| prev_answers = [] | |
| idx += 1 | |
| if idx < total: | |
| next_question = qs[idx] | |
| hist.append({ | |
| "role": "assistant", | |
| "content": f"Question {idx+1} of {total}\n\n{next_question['question']}" | |
| }) | |
| return ( | |
| hist, | |
| f"Response recorded. Question {idx+1}/{total}", | |
| idx, | |
| resp, | |
| 0, | |
| next_question, | |
| [], | |
| "" | |
| ) | |
| else: | |
| return ( | |
| hist, | |
| "All questions answered! Click 'Submit Interview' to complete.", | |
| idx, | |
| resp, | |
| 0, | |
| {}, | |
| [], | |
| "" | |
| ) | |
| def submit_int(sid, resp): | |
| if not resp: | |
| return "No responses to submit" | |
| success = add_response(sid, resp) | |
| if not success: | |
| return "Error saving interview" | |
| try: | |
| if not GROQ_API_KEY: | |
| return "Interview saved, but analysis unavailable (API key missing)" | |
| session = get_session(sid) | |
| study_name = session.get('study_name', 'All Studies') | |
| # Get all responses for this study | |
| all_responses, total_sessions = get_responses_by_study(study_name) | |
| # Generate analysis for this study | |
| syn = SynthesisAgent(GROQ_API_KEY) | |
| analysis = syn.aggregate_interviews(all_responses) | |
| # Update analysis for this study | |
| update_global_analysis(analysis, study_name) | |
| return f"Interview submitted successfully! Thank you for your detailed responses.\n\nStudy: {study_name}\nTotal interviews in this study: {len(all_responses)}\n\nEmpathy map has been updated." | |
| except Exception as e: | |
| print(f"Error in analysis: {e}") | |
| return f"Interview submitted successfully! Thank you.\n\n(Automated analysis will be updated shortly)" | |
| load_btn.click( | |
| load_interview, | |
| inputs=[session_input], | |
| outputs=[chatbot, answer, next_btn, submit_btn, interview_status, history, idx, responses, loaded_id, attempt_count, current_original_q, previous_answers] | |
| ) | |
| answer.submit( | |
| next_q, | |
| inputs=[answer, loaded_id, idx, history, responses, attempt_count, current_original_q, previous_answers], | |
| outputs=[history, interview_status, idx, responses, attempt_count, current_original_q, previous_answers, answer] | |
| ).then( | |
| lambda h: gr.update(value=h), | |
| inputs=[history], | |
| outputs=[chatbot] | |
| ) | |
| next_btn.click( | |
| next_q, | |
| inputs=[answer, loaded_id, idx, history, responses, attempt_count, current_original_q, previous_answers], | |
| outputs=[history, interview_status, idx, responses, attempt_count, current_original_q, previous_answers, answer] | |
| ).then( | |
| lambda h: gr.update(value=h), | |
| inputs=[history], | |
| outputs=[chatbot] | |
| ) | |
| submit_btn.click( | |
| submit_int, | |
| inputs=[loaded_id, responses], | |
| outputs=[interview_status] | |
| ) | |
| with gr.Tab("Analysis Dashboard"): | |
| gr.Markdown("### Empathy Map Analysis") | |
| gr.Markdown("Systematic qualitative analysis using thematic coding") | |
| # Study selector | |
| study_dropdown = gr.Dropdown( | |
| label="Select Study", | |
| choices=[], | |
| value=None, | |
| interactive=True | |
| ) | |
| refresh_studies_btn = gr.Button("Refresh Study List", size="sm") | |
| load_analysis_btn = gr.Button("Load Analysis", variant="primary", size="lg") | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| stats_display = gr.HTML(label="Study Statistics") | |
| with gr.Column(scale=1): | |
| update_info = gr.HTML(label="Last Updated") | |
| analysis_display = gr.HTML(label="Empathy Map Insights") | |
| def refresh_studies(): | |
| studies = get_unique_studies() | |
| if not studies: | |
| return gr.update(choices=["No studies available"], value=None) | |
| return gr.update(choices=studies, value=studies[0] if studies else None) | |
| def format_insight(insight): | |
| """Format a single insight with percentage and evidence""" | |
| html = f""" | |
| <div style='background: white; padding: 12px; margin: 8px 0; border-left: 3px solid #3498db; border-radius: 4px;'> | |
| <div><strong style='color: #1a1a1a;'>{insight['text']}</strong></div> | |
| <div style='color: #3498db; font-weight: 600;'>{insight['percentage']}% ({insight['count']} respondents)</div> | |
| """ | |
| if insight.get('quotes'): | |
| html += '<div style="margin-top: 8px;">' | |
| for quote in insight['quotes'][:2]: | |
| html += f'<div style="font-style: italic; color: #6c757d; margin-left: 15px; padding: 5px 0;">"{quote}"</div>' | |
| html += '</div>' | |
| html += '</div>' | |
| return html | |
| def load_analysis(study_name): | |
| try: | |
| if not study_name: | |
| return ( | |
| "<div style='background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;'><h3 style='color: #1a1a1a; margin-top: 0;'>No Study Selected</h3><p style='color: #1a1a1a;'>Please select a study from the dropdown.</p></div>", | |
| "", | |
| "" | |
| ) | |
| global_data = get_global_data() | |
| # Get analysis for selected study | |
| analyses = global_data.get('analyses', {}) | |
| analysis = analyses.get(study_name) | |
| if not analysis: | |
| return ( | |
| "<div style='background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;'><h3 style='color: #1a1a1a; margin-top: 0;'>No Analysis Available</h3><p style='color: #1a1a1a;'>Submit interviews for this study to generate empathy map insights.</p></div>", | |
| "", | |
| "" | |
| ) | |
| if 'error' in analysis: | |
| return ( | |
| f"<div style='background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;'><h3 style='color: #1a1a1a; margin-top: 0;'>Analysis Error</h3><p style='color: #1a1a1a;'>{analysis.get('error')}</p></div>", | |
| "", | |
| "" | |
| ) | |
| # Get study-specific stats | |
| all_responses, total_sessions = get_responses_by_study(study_name) | |
| total_interviews = len(all_responses) | |
| # Stats HTML | |
| stats_html = f""" | |
| <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;'> | |
| <h3 style='color: #1a1a1a; margin-top: 0;'>Study Statistics</h3> | |
| <p style='color: #1a1a1a; margin: 5px 0;'><strong style='color: #1a1a1a;'>Study:</strong> {study_name}</p> | |
| <p style='color: #1a1a1a; margin: 5px 0;'><strong style='color: #1a1a1a;'>Total Interviews:</strong> {total_interviews}</p> | |
| <p style='color: #1a1a1a; margin: 5px 0;'><strong style='color: #1a1a1a;'>Sessions:</strong> {total_sessions}</p> | |
| <p style='color: #1a1a1a; margin: 5px 0;'><strong style='color: #1a1a1a;'>Methodology:</strong> Thematic Analysis</p> | |
| </div> | |
| """ | |
| # Update info | |
| updated_at = analysis.get('updated_at', 'Unknown') | |
| update_html = f""" | |
| <div style='background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;'> | |
| <h3 style='color: #1a1a1a; margin-top: 0;'>Last Updated</h3> | |
| <p style='color: #1a1a1a;'>{updated_at}</p> | |
| </div> | |
| """ | |
| # Analysis HTML | |
| analysis_html = "<div style='margin-top: 20px;'>" | |
| # WHO | |
| if 'who' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>WHO: Customer Segment Profile</div>" | |
| analysis_html += f"<p style='color: #ffffff;'><em>{analysis['who'].get('description', '')}</em></p>" | |
| for insight in analysis['who'].get('insights', []): | |
| analysis_html += format_insight(insight) | |
| # GOAL | |
| if 'goal' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>GOAL: Jobs-to-be-Done</div>" | |
| analysis_html += f"<p style='color: #ffffff;'><strong style='color: #ffffff;'>Main Goal:</strong> {analysis['goal'].get('main_goal', '')}</p>" | |
| for insight in analysis['goal'].get('insights', []): | |
| analysis_html += format_insight(insight) | |
| # SEE | |
| if 'see' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>SEE: External Observations</div>" | |
| analysis_html += f"<p style='color: #ffffff;'><em>{analysis['see'].get('summary', '')}</em></p>" | |
| for insight in analysis['see'].get('insights', []): | |
| analysis_html += format_insight(insight) | |
| # SAY | |
| if 'say' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>SAY: Verbal Expressions</div>" | |
| analysis_html += f"<p style='color: #ffffff;'><em>{analysis['say'].get('summary', '')}</em></p>" | |
| for insight in analysis['say'].get('insights', []): | |
| analysis_html += format_insight(insight) | |
| # DO | |
| if 'do' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>DO: Behaviors & Actions</div>" | |
| analysis_html += f"<p style='color: #ffffff;'><em>{analysis['do'].get('summary', '')}</em></p>" | |
| for insight in analysis['do'].get('insights', []): | |
| analysis_html += format_insight(insight) | |
| # HEAR | |
| if 'hear' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>HEAR: External Influences</div>" | |
| analysis_html += f"<p style='color: #ffffff;'><em>{analysis['hear'].get('summary', '')}</em></p>" | |
| for insight in analysis['hear'].get('insights', []): | |
| analysis_html += format_insight(insight) | |
| # THINK & FEEL | |
| if 'think_feel' in analysis: | |
| analysis_html += "<div style='font-size: 18px; font-weight: 600; margin-top: 20px; margin-bottom: 10px; color: #ffffff;'>THINK & FEEL: Internal States</div>" | |
| analysis_html += "<h4 style='margin-top: 15px; color: #e74c3c;'>Pains (Obstacles & Frustrations)</h4>" | |
| for pain in analysis['think_feel'].get('pains', []): | |
| analysis_html += format_insight(pain) | |
| analysis_html += "<h4 style='margin-top: 15px; color: #27ae60;'>Gains (Desires & Aspirations)</h4>" | |
| for gain in analysis['think_feel'].get('gains', []): | |
| analysis_html += format_insight(gain) | |
| analysis_html += "</div>" | |
| return stats_html, update_html, analysis_html | |
| except Exception as e: | |
| return f"<div style='background: #f8f9fa; padding: 15px; border-radius: 8px; border: 1px solid #dee2e6;'><h3 style='color: #1a1a1a; margin-top: 0;'>Error</h3><p style='color: #1a1a1a;'>{str(e)}</p></div>", "", "" | |
| # Load studies on tab open | |
| app.load(refresh_studies, outputs=[study_dropdown]) | |
| refresh_studies_btn.click( | |
| refresh_studies, | |
| outputs=[study_dropdown] | |
| ) | |
| load_analysis_btn.click( | |
| load_analysis, | |
| inputs=[study_dropdown], | |
| outputs=[stats_display, update_info, analysis_display] | |
| ) | |
| return app | |
| if __name__ == "__main__": | |
| app = create_app() | |
| app.launch() |