aysan98 commited on
Commit
cf09db4
·
verified ·
1 Parent(s): b09b517

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -37
app.py CHANGED
@@ -6,7 +6,7 @@ from agents import QuestionGeneratorAgent, SynthesisAgent
6
  from storage import (
7
  add_session, add_response, get_session,
8
  get_all_responses, update_global_analysis,
9
- get_global_data
10
  )
11
  from validator import validate_response_quality, generate_research_followup
12
 
@@ -20,6 +20,15 @@ def create_app():
20
  padding: 15px;
21
  border-radius: 8px;
22
  border: 1px solid #dee2e6;
 
 
 
 
 
 
 
 
 
23
  }
24
  .section-header {
25
  font-size: 18px;
@@ -34,6 +43,10 @@ def create_app():
34
  margin: 8px 0;
35
  border-left: 3px solid #3498db;
36
  border-radius: 4px;
 
 
 
 
37
  }
38
  .percentage {
39
  color: #3498db;
@@ -41,7 +54,7 @@ def create_app():
41
  }
42
  .quote {
43
  font-style: italic;
44
- color: #7f8c8d;
45
  margin-left: 15px;
46
  padding: 5px 0;
47
  }
@@ -59,13 +72,13 @@ def create_app():
59
  query_input = gr.Textbox(
60
  label="Customer Segment / Research Focus",
61
  lines=2,
62
- placeholder="e.g., Premium sports shoe buyers, Small business owners looking for accounting software, Parents shopping for educational toys"
63
  )
64
 
65
  context_input = gr.Textbox(
66
- label="Additional Context (optional)",
67
- lines=3,
68
- placeholder="e.g., Demographics, behaviors, specific situation, industry details, or any background information that will help generate better questions"
69
  )
70
 
71
  generate_btn = gr.Button("Generate Interview Questions", variant="primary", size="lg")
@@ -85,21 +98,21 @@ def create_app():
85
 
86
  def generate_q(query, context):
87
  if not GROQ_API_KEY:
88
- return None, "Error: GROQ_API_KEY not configured. Please add it to Space Secrets.", []
89
 
90
  if not query or not query.strip():
91
- return None, "Please provide a customer segment or research focus", []
92
 
93
  try:
94
  agent = QuestionGeneratorAgent(GROQ_API_KEY)
95
  result = agent.generate(query, context)
96
  questions = result.get('questions', [])
97
  df_data = [[q['id'], q['section'], q['question']] for q in questions]
98
- return df_data, f"Generated {len(questions)} research questions", questions
99
  except Exception as e:
100
- return None, f"Error: {str(e)}", []
101
 
102
- def save_q(df_data):
103
  try:
104
  if not GROQ_API_KEY:
105
  return [], "Error: GROQ_API_KEY not configured", "", False
@@ -130,7 +143,11 @@ def create_app():
130
  return [], "No valid questions found", "", False
131
 
132
  session_id = str(uuid.uuid4())[:8]
133
- add_session(session_id, questions, GROQ_API_KEY)
 
 
 
 
134
 
135
  return questions, f"Session created successfully! ID: {session_id}", session_id, True
136
  except Exception as e:
@@ -139,12 +156,12 @@ def create_app():
139
  generate_btn.click(
140
  generate_q,
141
  [query_input, context_input],
142
- [questions_display, status, questions_state]
143
  )
144
 
145
  save_btn.click(
146
  save_q,
147
- [questions_display],
148
  [questions_state, status, link_box, link_box]
149
  )
150
 
@@ -325,17 +342,20 @@ def create_app():
325
  if not GROQ_API_KEY:
326
  return "Interview saved, but analysis unavailable (API key missing)"
327
 
328
- # Get all responses
329
- all_responses, total_sessions = get_all_responses()
 
 
 
330
 
331
- # Generate global analysis
332
  syn = SynthesisAgent(GROQ_API_KEY)
333
  analysis = syn.aggregate_interviews(all_responses)
334
 
335
- # Update global analysis
336
- update_global_analysis(analysis)
337
 
338
- return f"Interview submitted successfully! Thank you for your detailed responses.\n\nTotal interviews in study: {len(all_responses)}\n\nEmpathy map has been updated with your insights."
339
  except Exception as e:
340
  print(f"Error in analysis: {e}")
341
  return f"Interview submitted successfully! Thank you.\n\n(Automated analysis will be updated shortly)"
@@ -376,7 +396,16 @@ def create_app():
376
  gr.Markdown("### Empathy Map Analysis")
377
  gr.Markdown("Systematic qualitative analysis using thematic coding")
378
 
379
- load_analysis_btn = gr.Button("Load Latest Analysis", variant="primary", size="lg")
 
 
 
 
 
 
 
 
 
380
 
381
  with gr.Row():
382
  with gr.Column(scale=1):
@@ -387,6 +416,12 @@ def create_app():
387
 
388
  analysis_display = gr.HTML(label="Empathy Map Insights")
389
 
 
 
 
 
 
 
390
  def format_insight(insight):
391
  """Format a single insight with percentage and evidence"""
392
  html = f"""
@@ -404,19 +439,28 @@ def create_app():
404
  html += '</div>'
405
  return html
406
 
407
- def load_analysis():
408
  try:
 
 
 
 
 
 
 
409
  global_data = get_global_data()
410
 
411
- if not global_data['global_analysis']:
 
 
 
 
412
  return (
413
- "<div class='stat-card'><h3>No Analysis Available</h3><p>Submit interviews to generate empathy map insights.</p></div>",
414
  "",
415
  ""
416
  )
417
 
418
- analysis = global_data['global_analysis']
419
-
420
  if 'error' in analysis:
421
  return (
422
  f"<div class='stat-card'><h3>Analysis Error</h3><p>{analysis.get('error')}</p></div>",
@@ -424,21 +468,23 @@ def create_app():
424
  ""
425
  )
426
 
427
- total_interviews = analysis.get('total_interviews', 0)
428
- total_sessions = global_data['total_sessions']
 
429
 
430
  # Stats HTML
431
  stats_html = f"""
432
  <div class='stat-card'>
433
  <h3>Study Statistics</h3>
 
434
  <p><strong>Total Interviews:</strong> {total_interviews}</p>
435
- <p><strong>Sessions Created:</strong> {total_sessions}</p>
436
  <p><strong>Methodology:</strong> Thematic Analysis</p>
437
  </div>
438
  """
439
 
440
  # Update info
441
- updated_at = global_data.get('analysis_updated_at', 'Unknown')
442
  update_html = f"""
443
  <div class='stat-card'>
444
  <h3>Last Updated</h3>
@@ -452,42 +498,42 @@ def create_app():
452
  # WHO
453
  if 'who' in analysis:
454
  analysis_html += "<div class='section-header'>WHO: Customer Segment Profile</div>"
455
- analysis_html += f"<p><em>{analysis['who'].get('description', '')}</em></p>"
456
  for insight in analysis['who'].get('insights', []):
457
  analysis_html += format_insight(insight)
458
 
459
  # GOAL
460
  if 'goal' in analysis:
461
  analysis_html += "<div class='section-header'>GOAL: Jobs-to-be-Done</div>"
462
- analysis_html += f"<p><strong>Main Goal:</strong> {analysis['goal'].get('main_goal', '')}</p>"
463
  for insight in analysis['goal'].get('insights', []):
464
  analysis_html += format_insight(insight)
465
 
466
  # SEE
467
  if 'see' in analysis:
468
  analysis_html += "<div class='section-header'>SEE: External Observations</div>"
469
- analysis_html += f"<p><em>{analysis['see'].get('summary', '')}</em></p>"
470
  for insight in analysis['see'].get('insights', []):
471
  analysis_html += format_insight(insight)
472
 
473
  # SAY
474
  if 'say' in analysis:
475
  analysis_html += "<div class='section-header'>SAY: Verbal Expressions</div>"
476
- analysis_html += f"<p><em>{analysis['say'].get('summary', '')}</em></p>"
477
  for insight in analysis['say'].get('insights', []):
478
  analysis_html += format_insight(insight)
479
 
480
  # DO
481
  if 'do' in analysis:
482
  analysis_html += "<div class='section-header'>DO: Behaviors & Actions</div>"
483
- analysis_html += f"<p><em>{analysis['do'].get('summary', '')}</em></p>"
484
  for insight in analysis['do'].get('insights', []):
485
  analysis_html += format_insight(insight)
486
 
487
  # HEAR
488
  if 'hear' in analysis:
489
  analysis_html += "<div class='section-header'>HEAR: External Influences</div>"
490
- analysis_html += f"<p><em>{analysis['hear'].get('summary', '')}</em></p>"
491
  for insight in analysis['hear'].get('insights', []):
492
  analysis_html += format_insight(insight)
493
 
@@ -508,10 +554,19 @@ def create_app():
508
  return stats_html, update_html, analysis_html
509
 
510
  except Exception as e:
511
- return f"<div class='stat-card'>Error loading analysis: {str(e)}</div>", "", ""
 
 
 
 
 
 
 
 
512
 
513
  load_analysis_btn.click(
514
  load_analysis,
 
515
  outputs=[stats_display, update_info, analysis_display]
516
  )
517
 
 
6
  from storage import (
7
  add_session, add_response, get_session,
8
  get_all_responses, update_global_analysis,
9
+ get_global_data, get_unique_studies, get_responses_by_study
10
  )
11
  from validator import validate_response_quality, generate_research_followup
12
 
 
20
  padding: 15px;
21
  border-radius: 8px;
22
  border: 1px solid #dee2e6;
23
+ color: #2c3e50;
24
+ }
25
+ .stat-card h3 {
26
+ color: #2c3e50;
27
+ margin-top: 0;
28
+ }
29
+ .stat-card p {
30
+ color: #495057;
31
+ margin: 5px 0;
32
  }
33
  .section-header {
34
  font-size: 18px;
 
43
  margin: 8px 0;
44
  border-left: 3px solid #3498db;
45
  border-radius: 4px;
46
+ color: #2c3e50;
47
+ }
48
+ .insight-item strong {
49
+ color: #2c3e50;
50
  }
51
  .percentage {
52
  color: #3498db;
 
54
  }
55
  .quote {
56
  font-style: italic;
57
+ color: #6c757d;
58
  margin-left: 15px;
59
  padding: 5px 0;
60
  }
 
72
  query_input = gr.Textbox(
73
  label="Customer Segment / Research Focus",
74
  lines=2,
75
+ placeholder="e.g., Premium sports shoe buyers, Small business owners looking for accounting software"
76
  )
77
 
78
  context_input = gr.Textbox(
79
+ label="Study Name / Context (recommended for organizing multiple studies)",
80
+ lines=2,
81
+ placeholder="e.g., Q4 2024 Footwear Research, SaaS Buyer Study, Coffee Shop Customers - Winter 2024"
82
  )
83
 
84
  generate_btn = gr.Button("Generate Interview Questions", variant="primary", size="lg")
 
98
 
99
  def generate_q(query, context):
100
  if not GROQ_API_KEY:
101
+ return None, "Error: GROQ_API_KEY not configured. Please add it to Space Secrets.", [], "", False
102
 
103
  if not query or not query.strip():
104
+ return None, "Please provide a customer segment or research focus", [], "", False
105
 
106
  try:
107
  agent = QuestionGeneratorAgent(GROQ_API_KEY)
108
  result = agent.generate(query, context)
109
  questions = result.get('questions', [])
110
  df_data = [[q['id'], q['section'], q['question']] for q in questions]
111
+ return df_data, f"Generated {len(questions)} research questions", questions, "", False
112
  except Exception as e:
113
+ return None, f"Error: {str(e)}", [], "", False
114
 
115
+ def save_q(df_data, query, context):
116
  try:
117
  if not GROQ_API_KEY:
118
  return [], "Error: GROQ_API_KEY not configured", "", False
 
143
  return [], "No valid questions found", "", False
144
 
145
  session_id = str(uuid.uuid4())[:8]
146
+
147
+ # Use context as study identifier, or use query if context is empty
148
+ study_name = context.strip() if context and context.strip() else query.strip()
149
+
150
+ add_session(session_id, questions, GROQ_API_KEY, study_name)
151
 
152
  return questions, f"Session created successfully! ID: {session_id}", session_id, True
153
  except Exception as e:
 
156
  generate_btn.click(
157
  generate_q,
158
  [query_input, context_input],
159
+ [questions_display, status, questions_state, link_box, link_box]
160
  )
161
 
162
  save_btn.click(
163
  save_q,
164
+ [questions_display, query_input, context_input],
165
  [questions_state, status, link_box, link_box]
166
  )
167
 
 
342
  if not GROQ_API_KEY:
343
  return "Interview saved, but analysis unavailable (API key missing)"
344
 
345
+ session = get_session(sid)
346
+ study_name = session.get('study_name', 'All Studies')
347
+
348
+ # Get all responses for this study
349
+ all_responses, total_sessions = get_responses_by_study(study_name)
350
 
351
+ # Generate analysis for this study
352
  syn = SynthesisAgent(GROQ_API_KEY)
353
  analysis = syn.aggregate_interviews(all_responses)
354
 
355
+ # Update analysis for this study
356
+ update_global_analysis(analysis, study_name)
357
 
358
+ 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."
359
  except Exception as e:
360
  print(f"Error in analysis: {e}")
361
  return f"Interview submitted successfully! Thank you.\n\n(Automated analysis will be updated shortly)"
 
396
  gr.Markdown("### Empathy Map Analysis")
397
  gr.Markdown("Systematic qualitative analysis using thematic coding")
398
 
399
+ # Study selector
400
+ study_dropdown = gr.Dropdown(
401
+ label="Select Study",
402
+ choices=[],
403
+ value=None,
404
+ interactive=True
405
+ )
406
+
407
+ refresh_studies_btn = gr.Button("Refresh Study List", size="sm")
408
+ load_analysis_btn = gr.Button("Load Analysis", variant="primary", size="lg")
409
 
410
  with gr.Row():
411
  with gr.Column(scale=1):
 
416
 
417
  analysis_display = gr.HTML(label="Empathy Map Insights")
418
 
419
+ def refresh_studies():
420
+ studies = get_unique_studies()
421
+ if not studies:
422
+ return gr.update(choices=["No studies available"], value=None)
423
+ return gr.update(choices=studies, value=studies[0] if studies else None)
424
+
425
  def format_insight(insight):
426
  """Format a single insight with percentage and evidence"""
427
  html = f"""
 
439
  html += '</div>'
440
  return html
441
 
442
+ def load_analysis(study_name):
443
  try:
444
+ if not study_name:
445
+ return (
446
+ "<div class='stat-card'><h3>No Study Selected</h3><p>Please select a study from the dropdown.</p></div>",
447
+ "",
448
+ ""
449
+ )
450
+
451
  global_data = get_global_data()
452
 
453
+ # Get analysis for selected study
454
+ analyses = global_data.get('analyses', {})
455
+ analysis = analyses.get(study_name)
456
+
457
+ if not analysis:
458
  return (
459
+ "<div class='stat-card'><h3>No Analysis Available</h3><p>Submit interviews for this study to generate empathy map insights.</p></div>",
460
  "",
461
  ""
462
  )
463
 
 
 
464
  if 'error' in analysis:
465
  return (
466
  f"<div class='stat-card'><h3>Analysis Error</h3><p>{analysis.get('error')}</p></div>",
 
468
  ""
469
  )
470
 
471
+ # Get study-specific stats
472
+ all_responses, total_sessions = get_responses_by_study(study_name)
473
+ total_interviews = len(all_responses)
474
 
475
  # Stats HTML
476
  stats_html = f"""
477
  <div class='stat-card'>
478
  <h3>Study Statistics</h3>
479
+ <p><strong>Study:</strong> {study_name}</p>
480
  <p><strong>Total Interviews:</strong> {total_interviews}</p>
481
+ <p><strong>Sessions:</strong> {total_sessions}</p>
482
  <p><strong>Methodology:</strong> Thematic Analysis</p>
483
  </div>
484
  """
485
 
486
  # Update info
487
+ updated_at = analysis.get('updated_at', 'Unknown')
488
  update_html = f"""
489
  <div class='stat-card'>
490
  <h3>Last Updated</h3>
 
498
  # WHO
499
  if 'who' in analysis:
500
  analysis_html += "<div class='section-header'>WHO: Customer Segment Profile</div>"
501
+ analysis_html += f"<p style='color: #495057;'><em>{analysis['who'].get('description', '')}</em></p>"
502
  for insight in analysis['who'].get('insights', []):
503
  analysis_html += format_insight(insight)
504
 
505
  # GOAL
506
  if 'goal' in analysis:
507
  analysis_html += "<div class='section-header'>GOAL: Jobs-to-be-Done</div>"
508
+ analysis_html += f"<p style='color: #495057;'><strong>Main Goal:</strong> {analysis['goal'].get('main_goal', '')}</p>"
509
  for insight in analysis['goal'].get('insights', []):
510
  analysis_html += format_insight(insight)
511
 
512
  # SEE
513
  if 'see' in analysis:
514
  analysis_html += "<div class='section-header'>SEE: External Observations</div>"
515
+ analysis_html += f"<p style='color: #495057;'><em>{analysis['see'].get('summary', '')}</em></p>"
516
  for insight in analysis['see'].get('insights', []):
517
  analysis_html += format_insight(insight)
518
 
519
  # SAY
520
  if 'say' in analysis:
521
  analysis_html += "<div class='section-header'>SAY: Verbal Expressions</div>"
522
+ analysis_html += f"<p style='color: #495057;'><em>{analysis['say'].get('summary', '')}</em></p>"
523
  for insight in analysis['say'].get('insights', []):
524
  analysis_html += format_insight(insight)
525
 
526
  # DO
527
  if 'do' in analysis:
528
  analysis_html += "<div class='section-header'>DO: Behaviors & Actions</div>"
529
+ analysis_html += f"<p style='color: #495057;'><em>{analysis['do'].get('summary', '')}</em></p>"
530
  for insight in analysis['do'].get('insights', []):
531
  analysis_html += format_insight(insight)
532
 
533
  # HEAR
534
  if 'hear' in analysis:
535
  analysis_html += "<div class='section-header'>HEAR: External Influences</div>"
536
+ analysis_html += f"<p style='color: #495057;'><em>{analysis['hear'].get('summary', '')}</em></p>"
537
  for insight in analysis['hear'].get('insights', []):
538
  analysis_html += format_insight(insight)
539
 
 
554
  return stats_html, update_html, analysis_html
555
 
556
  except Exception as e:
557
+ return f"<div class='stat-card'><h3>Error</h3><p>{str(e)}</p></div>", "", ""
558
+
559
+ # Load studies on tab open
560
+ app.load(refresh_studies, outputs=[study_dropdown])
561
+
562
+ refresh_studies_btn.click(
563
+ refresh_studies,
564
+ outputs=[study_dropdown]
565
+ )
566
 
567
  load_analysis_btn.click(
568
  load_analysis,
569
+ inputs=[study_dropdown],
570
  outputs=[stats_display, update_info, analysis_display]
571
  )
572