Spaces:
Sleeping
Sleeping
File size: 27,049 Bytes
993c60a cf9d45d 5dde284 cf9d45d b8dbb54 49cb212 e88796e cf09db4 49cb212 5dde284 993c60a 49cb212 cf09db4 49cb212 5dde284 993c60a 5dde284 993c60a 5dde284 993c60a 5dde284 cf09db4 5dde284 993c60a e88796e cf09db4 e88796e 5dde284 f63e204 5dde284 f63e204 49cb212 a16ed82 da33126 993c60a a16ed82 5dde284 cf09db4 5dde284 cf09db4 5dde284 c4c2e42 5dde284 f63e204 cf09db4 c4c2e42 cf09db4 f63e204 cf09db4 cf9d45d 5dde284 cf9d45d 49cb212 cf9d45d 7166760 a16ed82 06b2b85 807cb03 a16ed82 7166760 06b2b85 a16ed82 06b2b85 cf9d45d 49cb212 cf9d45d cf09db4 cf9d45d 5dde284 cf9d45d 49cb212 f63e204 5dde284 cf09db4 5dde284 cf09db4 5dde284 993c60a 49cb212 5dde284 cf9d45d 5dde284 a16ed82 993c60a da33126 5dde284 da33126 a16ed82 cf9d45d a16ed82 68925ae 5dde284 cf9d45d a16ed82 b8dbb54 b92709d 49cb212 b92709d 68925ae 5dde284 b92709d a16ed82 da33126 d92d2b7 5dde284 d92d2b7 b92709d 5dde284 b92709d 68925ae 5dde284 b92709d a16ed82 5dde284 b92709d 5dde284 b92709d a16ed82 b8dbb54 5dde284 993c60a a16ed82 da33126 993c60a 5dde284 68925ae 5dde284 68925ae 5dde284 68925ae 5dde284 68925ae 5dde284 68925ae 5dde284 68925ae 5dde284 68925ae 5dde284 b92709d 5dde284 68925ae 5dde284 b92709d 68925ae 5dde284 68925ae 5dde284 b92709d 5dde284 68925ae 5dde284 a16ed82 993c60a da33126 68925ae d92d2b7 49cb212 d92d2b7 68925ae 5dde284 68925ae 5dde284 68925ae cf9d45d 68925ae 5dde284 68925ae 5dde284 68925ae 993c60a a16ed82 49cb212 b92709d 49cb212 b92709d b8dbb54 5dde284 49cb212 cf09db4 49cb212 cf09db4 5dde284 e88796e 49cb212 cf09db4 49cb212 cf09db4 b92709d 49cb212 5dde284 b92709d 5dde284 b92709d 5dde284 b92709d 5dde284 b92709d 993c60a 49cb212 e88796e 5dde284 b92709d cf09db4 a16ed82 b92709d 49cb212 5dde284 b92709d 49cb212 5dde284 b92709d 5dde284 a16ed82 cf09db4 49cb212 5dde284 49cb212 7f4fb44 919b156 7f4fb44 49cb212 b92709d 49cb212 e88796e 7f4fb44 49cb212 b92709d 49cb212 a16ed82 cf09db4 c4c2e42 cf09db4 7f4fb44 cf09db4 e88796e 49cb212 cf09db4 49cb212 7f4fb44 49cb212 5dde284 7f4fb44 5dde284 cf09db4 49cb212 7f4fb44 919b156 49cb212 cf09db4 49cb212 7f4fb44 919b156 49cb212 7f4fb44 8c4486c 49cb212 7f4fb44 49cb212 7f4fb44 8c4486c 49cb212 7f4fb44 8c4486c 49cb212 7f4fb44 8c4486c 49cb212 7f4fb44 49cb212 7f4fb44 49cb212 5dde284 49cb212 5dde284 49cb212 c4c2e42 7f4fb44 cf09db4 993c60a 49cb212 cf09db4 49cb212 993c60a 9897d04 | 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 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 | 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() |