aradhyapavan commited on
Commit
55a9e99
·
verified ·
1 Parent(s): 815ff45

Update components/question_answering.py

Browse files
Files changed (1) hide show
  1. components/question_answering.py +529 -498
components/question_answering.py CHANGED
@@ -1,498 +1,529 @@
1
- import matplotlib.pyplot as plt
2
- import pandas as pd
3
- import numpy as np
4
- from transformers import pipeline
5
- import nltk
6
- from collections import Counter
7
- import re
8
- from sklearn.feature_extraction.text import TfidfVectorizer
9
- from sklearn.metrics.pairwise import cosine_similarity
10
-
11
- from utils.model_loader import load_qa_pipeline
12
- from utils.helpers import fig_to_html, df_to_html_table
13
-
14
- def question_answering_handler(context_text, question, answer_type="extractive", confidence_threshold=0.5):
15
- """Show question answering capabilities with comprehensive analysis."""
16
- output_html = []
17
-
18
- # Add result area container
19
- output_html.append('<div class="result-area">')
20
- output_html.append('<h2 class="task-header">Question Answering System</h2>')
21
-
22
- output_html.append("""
23
- <div class="alert alert-info">
24
- <i class="fas fa-info-circle"></i>
25
- Question Answering (QA) systems extract or generate answers to questions based on a given context or knowledge base.
26
- This system can handle both extractive (finding answers in text) and abstractive (generating new answers) approaches.
27
- </div>
28
- """)
29
-
30
- # Model info
31
- output_html.append("""
32
- <div class="alert alert-info">
33
- <h4><i class="fas fa-tools"></i> Models & Techniques Used:</h4>
34
- <ul>
35
- <li><b>RoBERTa-SQuAD2</b> - Fine-tuned transformer model for extractive QA (F1: ~83.7 on SQuAD 2.0)</li>
36
- <li><b>BERT-based QA</b> - Bidirectional encoder representations for understanding context</li>
37
- <li><b>TF-IDF Similarity</b> - Traditional approach for finding relevant text spans</li>
38
- <li><b>Confidence Scoring</b> - Model uncertainty estimation for answer reliability</li>
39
- </ul>
40
- </div>
41
- """)
42
-
43
- try:
44
- # Validate inputs
45
- if not context_text or not context_text.strip():
46
- output_html.append('<div class="alert alert-warning">⚠️ Please provide a context text for question answering.</div>')
47
- output_html.append('</div>')
48
- return "\n".join(output_html)
49
-
50
- if not question or not question.strip():
51
- output_html.append('<div class="alert alert-warning">⚠️ Please provide a question to answer.</div>')
52
- output_html.append('</div>')
53
- return "\n".join(output_html)
54
-
55
- # Display input information
56
- output_html.append('<h3 class="task-subheader">Input Analysis</h3>')
57
-
58
- context_stats = {
59
- "Context Length": len(context_text),
60
- "Word Count": len(context_text.split()),
61
- "Sentence Count": len(nltk.sent_tokenize(context_text)),
62
- "Question Length": len(question),
63
- "Question Words": len(question.split())
64
- }
65
-
66
- stats_df = pd.DataFrame(list(context_stats.items()), columns=['Metric', 'Value'])
67
- output_html.append('<h4>Input Statistics</h4>')
68
- output_html.append(df_to_html_table(stats_df))
69
-
70
- # Question Analysis
71
- output_html.append('<h3 class="task-subheader">Question Analysis</h3>')
72
-
73
- # Classify question type
74
- question_lower = question.lower().strip()
75
- question_type = classify_question_type(question_lower)
76
-
77
- output_html.append(f"""
78
- <div class="card">
79
- <div class="card-header">
80
- <h4 class="mb-0">Question Classification</h4>
81
- </div>
82
- <div class="card-body">
83
- <p><strong>Question:</strong> {question}</p>
84
- <p><strong>Type:</strong> {question_type['type']}</p>
85
- <p><strong>Expected Answer:</strong> {question_type['expected']}</p>
86
- <p><strong>Keywords:</strong> {', '.join(question_type['keywords'])}</p>
87
- </div>
88
- </div>
89
- """)
90
-
91
- # Extractive Question Answering using Transformer
92
- output_html.append('<h3 class="task-subheader">Transformer-based Answer Extraction</h3>')
93
-
94
- try:
95
- qa_pipeline = load_qa_pipeline()
96
-
97
- # Get answer from the model
98
- result = qa_pipeline(question=question, context=context_text)
99
-
100
- answer = result['answer']
101
- confidence = result['score']
102
- start_pos = result['start']
103
- end_pos = result['end']
104
-
105
- # Create confidence visualization
106
- fig, ax = plt.subplots(1, 1, figsize=(8, 4))
107
-
108
- # Confidence bar
109
- colors = ['red' if confidence < 0.3 else 'orange' if confidence < 0.7 else 'green']
110
- bars = ax.barh(['Confidence'], [confidence], color=colors[0])
111
- ax.set_xlim(0, 1)
112
- ax.set_xlabel('Confidence Score')
113
- ax.set_title('Answer Confidence')
114
-
115
- # Add confidence threshold line
116
- ax.axvline(x=confidence_threshold, color='red', linestyle='--', label=f'Threshold ({confidence_threshold})')
117
- ax.legend()
118
-
119
- # Add value labels
120
- for bar in bars:
121
- width = bar.get_width()
122
- ax.text(width/2, bar.get_y() + bar.get_height()/2,
123
- f'{width:.3f}', ha='center', va='center', fontweight='bold')
124
-
125
- plt.tight_layout()
126
- output_html.append(fig_to_html(fig))
127
- plt.close()
128
-
129
- # Display answer with context highlighting
130
- confidence_status = "High" if confidence >= 0.7 else "Medium" if confidence >= 0.3 else "Low"
131
- confidence_color = "#4CAF50" if confidence >= 0.7 else "#FF9800" if confidence >= 0.3 else "#F44336"
132
-
133
- output_html.append(f"""
134
- <div class="card" style="border-color: {confidence_color};">
135
- <div class="card-header" style="background-color: {confidence_color}22;">
136
- <h4 class="mb-0">📝 Extracted Answer</h4>
137
- </div>
138
- <div class="card-body">
139
- <div class="alert alert-light">
140
- <strong>Answer:</strong> <span class="badge bg-warning text-dark fs-6">{answer}</span>
141
- </div>
142
- <p><strong>Confidence:</strong> {confidence:.3f} ({confidence_status})</p>
143
- <p><strong>Position in Text:</strong> Characters {start_pos}-{end_pos}</p>
144
- </div>
145
- </div>
146
- """)
147
-
148
- # Show context with answer highlighted
149
- highlighted_context = highlight_answer_in_context(context_text, start_pos, end_pos)
150
- output_html.append(f"""
151
- <div class="card">
152
- <div class="card-header">
153
- <h4 class="mb-0">📄 Context with Highlighted Answer</h4>
154
- </div>
155
- <div class="card-body">
156
- <div style="line-height: 1.6; border: 1px solid #ddd; padding: 1rem; border-radius: 5px;">
157
- {highlighted_context}
158
- </div>
159
- </div>
160
- </div>
161
- """)
162
-
163
- except Exception as e:
164
- output_html.append(f'<div class="alert alert-danger">❌ Error in transformer QA: {str(e)}</div>')
165
-
166
- # Alternative: TF-IDF based answer extraction
167
- output_html.append('<h3 class="task-subheader">TF-IDF Based Answer Extraction</h3>')
168
-
169
- try:
170
- tfidf_answer = extract_answer_tfidf(context_text, question)
171
-
172
- output_html.append(f"""
173
- <div class="alert alert-success">
174
- <h4>🔍 TF-IDF Based Answer</h4>
175
- <div class="alert alert-light">
176
- <strong>Most Relevant Sentence:</strong> {tfidf_answer['sentence']}
177
- </div>
178
- <p><strong>Similarity Score:</strong> {tfidf_answer['score']:.3f}</p>
179
- <p><strong>Method:</strong> Cosine similarity between question and context sentences using TF-IDF vectors</p>
180
- </div>
181
- """)
182
-
183
- except Exception as e:
184
- output_html.append(f'<div class="alert alert-danger">❌ Error in TF-IDF QA: {str(e)}</div>')
185
-
186
- # Answer Quality Assessment
187
- output_html.append('<h3 class="task-subheader">Answer Quality Assessment</h3>')
188
-
189
- if 'confidence' in locals():
190
- quality_metrics = assess_answer_quality(question, answer, confidence, context_text)
191
-
192
- # Create quality assessment visualization
193
- fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
194
-
195
- # Quality metrics radar chart
196
- categories = list(quality_metrics.keys())
197
- values = list(quality_metrics.values())
198
-
199
- ax1.bar(categories, values, color=['#4CAF50', '#2196F3', '#FF9800', '#9C27B0'])
200
- ax1.set_ylim(0, 1)
201
- ax1.set_title('Answer Quality Metrics')
202
- ax1.set_ylabel('Score')
203
- plt.setp(ax1.get_xticklabels(), rotation=45, ha='right')
204
-
205
- # Overall quality score
206
- overall_score = sum(values) / len(values)
207
- quality_label = "Excellent" if overall_score >= 0.8 else "Good" if overall_score >= 0.6 else "Fair" if overall_score >= 0.4 else "Poor"
208
-
209
- ax2.pie([overall_score, 1-overall_score], labels=[f'{quality_label}\n({overall_score:.2f})', 'Room for Improvement'],
210
- colors=['#4CAF50', '#E0E0E0'], startangle=90)
211
- ax2.set_title('Overall Answer Quality')
212
-
213
- plt.tight_layout()
214
- output_html.append(fig_to_html(fig))
215
- plt.close()
216
-
217
- # Quality metrics table
218
- quality_df = pd.DataFrame([
219
- {'Metric': 'Confidence', 'Score': f"{quality_metrics['Confidence']:.3f}", 'Description': 'Model confidence in the answer'},
220
- {'Metric': 'Relevance', 'Score': f"{quality_metrics['Relevance']:.3f}", 'Description': 'Semantic similarity to question'},
221
- {'Metric': 'Completeness', 'Score': f"{quality_metrics['Completeness']:.3f}", 'Description': 'Answer length appropriateness'},
222
- {'Metric': 'Context Match', 'Score': f"{quality_metrics['Context_Match']:.3f}", 'Description': 'How well answer fits context'}
223
- ])
224
-
225
- output_html.append('<h4>Quality Assessment Details</h4>')
226
- output_html.append(df_to_html_table(quality_df))
227
-
228
- # Question-Answer Pairs Suggestions
229
- output_html.append('<h3 class="task-subheader">Suggested Follow-up Questions</h3>')
230
-
231
- try:
232
- suggested_questions = generate_followup_questions(context_text, question, answer if 'answer' in locals() else "")
233
-
234
- output_html.append('<div class="alert alert-warning">')
235
- output_html.append('<h4>💡 Follow-up Questions:</h4>')
236
- output_html.append('<ul>')
237
- for i, q in enumerate(suggested_questions, 1):
238
- output_html.append(f'<li><strong>Q{i}:</strong> {q}</li>')
239
- output_html.append('</ul>')
240
- output_html.append('</div>')
241
-
242
- except Exception as e:
243
- output_html.append(f'<div class="alert alert-danger">❌ Error generating suggestions: {str(e)}</div>')
244
-
245
- except Exception as e:
246
- output_html.append(f'<div class="alert alert-danger">❌ Unexpected error: {str(e)}</div>')
247
-
248
- output_html.append('</div>')
249
- return "\n".join(output_html)
250
-
251
- def classify_question_type(question):
252
- """Classify the type of question and expected answer format."""
253
- question = question.lower().strip()
254
-
255
- # Question word patterns
256
- patterns = {
257
- 'what': {'type': 'Definition/Fact', 'expected': 'Entity, concept, or description'},
258
- 'who': {'type': 'Person', 'expected': 'Person name or group'},
259
- 'when': {'type': 'Time', 'expected': 'Date, time, or temporal expression'},
260
- 'where': {'type': 'Location', 'expected': 'Place, location, or spatial reference'},
261
- 'why': {'type': 'Reason/Cause', 'expected': 'Explanation or causal relationship'},
262
- 'how': {'type': 'Method/Process', 'expected': 'Process, method, or manner'},
263
- 'which': {'type': 'Selection', 'expected': 'Specific choice from options'},
264
- 'how much': {'type': 'Quantity', 'expected': 'Numerical amount or quantity'},
265
- 'how many': {'type': 'Count', 'expected': 'Numerical count'},
266
- 'is': {'type': 'Yes/No', 'expected': 'Boolean answer'},
267
- 'are': {'type': 'Yes/No', 'expected': 'Boolean answer'},
268
- 'can': {'type': 'Ability/Possibility', 'expected': 'Yes/No with explanation'},
269
- 'will': {'type': 'Future/Prediction', 'expected': 'Future state or prediction'},
270
- 'did': {'type': 'Past Action', 'expected': 'Yes/No about past events'}
271
- }
272
-
273
- # Extract keywords from question
274
- words = question.split()
275
- keywords = [word for word in words if len(word) > 2 and word not in ['the', 'and', 'but', 'for']]
276
-
277
- # Determine question type
278
- for pattern, info in patterns.items():
279
- if question.startswith(pattern):
280
- return {
281
- 'type': info['type'],
282
- 'expected': info['expected'],
283
- 'keywords': keywords[:5] # Top 5 keywords
284
- }
285
-
286
- # Default classification
287
- return {
288
- 'type': 'General',
289
- 'expected': 'Text span or explanation',
290
- 'keywords': keywords[:5]
291
- }
292
-
293
- def extract_answer_tfidf(context, question):
294
- """Extract answer using TF-IDF similarity."""
295
- # Split context into sentences
296
- sentences = nltk.sent_tokenize(context)
297
-
298
- if len(sentences) == 0:
299
- return {'sentence': 'No sentences found', 'score': 0.0}
300
-
301
- # Create TF-IDF vectors
302
- vectorizer = TfidfVectorizer(stop_words='english', lowercase=True)
303
-
304
- # Combine question with sentences for vectorization
305
- texts = [question] + sentences
306
- tfidf_matrix = vectorizer.fit_transform(texts)
307
-
308
- # Calculate cosine similarity between question and each sentence
309
- question_vector = tfidf_matrix[0:1]
310
- sentence_vectors = tfidf_matrix[1:]
311
-
312
- similarities = cosine_similarity(question_vector, sentence_vectors).flatten()
313
-
314
- # Find the most similar sentence
315
- best_idx = np.argmax(similarities)
316
- best_sentence = sentences[best_idx]
317
- best_score = similarities[best_idx]
318
-
319
- return {
320
- 'sentence': best_sentence,
321
- 'score': best_score
322
- }
323
-
324
- def highlight_answer_in_context(context, start_pos, end_pos):
325
- """Highlight the answer span in the context."""
326
- before = context[:start_pos]
327
- answer = context[start_pos:end_pos]
328
- after = context[end_pos:]
329
-
330
- highlighted = f'{before}<mark style="background-color: #FFEB3B; padding: 2px 4px; border-radius: 3px; font-weight: bold;">{answer}</mark>{after}'
331
-
332
- return highlighted
333
-
334
- def assess_answer_quality(question, answer, confidence, context):
335
- """Assess the quality of the extracted answer."""
336
- metrics = {}
337
-
338
- # Confidence score (from model)
339
- metrics['Confidence'] = confidence
340
-
341
- # Relevance (simple keyword overlap)
342
- question_words = set(question.lower().split())
343
- answer_words = set(answer.lower().split())
344
- overlap = len(question_words.intersection(answer_words))
345
- metrics['Relevance'] = min(overlap / max(len(question_words), 1), 1.0)
346
-
347
- # Completeness (answer length appropriateness)
348
- answer_length = len(answer.split())
349
- if answer_length == 0:
350
- metrics['Completeness'] = 0.0
351
- elif answer_length < 3:
352
- metrics['Completeness'] = 0.6
353
- elif answer_length <= 20:
354
- metrics['Completeness'] = 1.0
355
- else:
356
- metrics['Completeness'] = 0.8 # Very long answers might be too verbose
357
-
358
- # Context match (how well the answer fits in context)
359
- answer_in_context = answer.lower() in context.lower()
360
- metrics['Context_Match'] = 1.0 if answer_in_context else 0.5
361
-
362
- return metrics
363
-
364
- def generate_followup_questions(context, original_question, answer):
365
- """Generate relevant follow-up questions based on the context and answer."""
366
- suggestions = []
367
-
368
- # Extract key entities and concepts from context
369
- words = context.split()
370
-
371
- # Template-based question generation
372
- templates = [
373
- f"What else can you tell me about {answer}?",
374
- "Can you provide more details about this topic?",
375
- "What are the implications of this information?",
376
- "How does this relate to other concepts mentioned?",
377
- "What evidence supports this answer?"
378
- ]
379
-
380
- # Add context-specific questions
381
- if "when" not in original_question.lower():
382
- suggestions.append("When did this happen?")
383
-
384
- if "where" not in original_question.lower():
385
- suggestions.append("Where did this take place?")
386
-
387
- if "why" not in original_question.lower():
388
- suggestions.append("Why is this significant?")
389
-
390
- if "how" not in original_question.lower():
391
- suggestions.append("How does this work?")
392
-
393
- # Combine and limit suggestions
394
- all_suggestions = templates + suggestions
395
- return all_suggestions[:5] # Return top 5 suggestions
396
-
397
- def qa_api_handler(context, question):
398
- """API handler for question answering that returns structured data."""
399
- try:
400
- qa_pipeline = load_qa_pipeline()
401
- result = qa_pipeline(question=question, context=context)
402
-
403
- return {
404
- "answer": result['answer'],
405
- "confidence": result['score'],
406
- "start_position": result['start'],
407
- "end_position": result['end'],
408
- "success": True,
409
- "error": None
410
- }
411
- except Exception as e:
412
- return {
413
- "answer": "",
414
- "confidence": 0.0,
415
- "start_position": 0,
416
- "end_position": 0,
417
- "success": False,
418
- "error": str(e)
419
- }
420
-
421
- def process_question_with_context(context_text, question):
422
- """Process a question with the given context and return a formatted result."""
423
- if not context_text or not context_text.strip():
424
- return {
425
- "success": False,
426
- "error": "No context text provided",
427
- "html": '<div class="alert alert-warning">⚠️ No context text provided.</div>'
428
- }
429
-
430
- if not question or not question.strip():
431
- return {
432
- "success": False,
433
- "error": "No question provided",
434
- "html": '<div class="alert alert-warning">⚠️ Please enter a question.</div>'
435
- }
436
-
437
- try:
438
- qa_pipeline = load_qa_pipeline()
439
- result = qa_pipeline(question=question, context=context_text)
440
-
441
- answer = result['answer']
442
- confidence = result['score']
443
- start_pos = result['start']
444
- end_pos = result['end']
445
-
446
- # Determine confidence level
447
- confidence_status = "High" if confidence >= 0.7 else "Medium" if confidence >= 0.3 else "Low"
448
- confidence_color = "#4CAF50" if confidence >= 0.7 else "#FF9800" if confidence >= 0.3 else "#F44336"
449
-
450
- # Highlight answer in context
451
- highlighted_context = highlight_answer_in_context(context_text, start_pos, end_pos)
452
-
453
- # Create formatted HTML result
454
- html_result = f"""
455
- <div class="card">
456
- <div class="card-header">
457
- <h5 class="mb-0">📝 Answer Found!</h5>
458
- </div>
459
- <div class="card-body">
460
- <div class="alert alert-light">
461
- <p><strong>Question:</strong> {question}</p>
462
- <p><strong>Answer:</strong> <span class="badge bg-warning text-dark fs-6">{answer}</span></p>
463
- <p><strong>Confidence:</strong> {confidence:.3f} ({confidence_status})</p>
464
- </div>
465
-
466
- <div class="alert alert-light">
467
- <h6>📄 Context with Highlighted Answer:</h6>
468
- <div style="line-height: 1.6; font-size: 0.9rem; max-height: 200px; overflow-y: auto;">
469
- {highlighted_context}
470
- </div>
471
- </div>
472
-
473
- <div class="alert alert-info">
474
- <strong>Quality Assessment:</strong>
475
- <ul class="mb-0">
476
- <li>Confidence: {confidence_status} ({confidence:.1%})</li>
477
- <li>Answer found at position: {start_pos}-{end_pos}</li>
478
- <li>Answer length: {len(answer.split())} words</li>
479
- </ul>
480
- </div>
481
- </div>
482
- </div>
483
- """
484
-
485
- return {
486
- "success": True,
487
- "answer": answer,
488
- "confidence": confidence,
489
- "html": html_result
490
- }
491
-
492
- except Exception as e:
493
- error_html = f'<div class="alert alert-danger">❌ Error processing question: {str(e)}</div>'
494
- return {
495
- "success": False,
496
- "error": str(e),
497
- "html": error_html
498
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.pyplot as plt
2
+ import pandas as pd
3
+ import numpy as np
4
+ from transformers import pipeline
5
+ import nltk
6
+ from collections import Counter
7
+ import re
8
+ from sklearn.feature_extraction.text import TfidfVectorizer
9
+ from sklearn.metrics.pairwise import cosine_similarity
10
+
11
+ from utils.model_loader import load_qa_pipeline
12
+ from utils.helpers import fig_to_html, df_to_html_table
13
+
14
+ def question_answering_handler(context_text, question, answer_type="extractive", confidence_threshold=0.5):
15
+ """Show question answering capabilities with comprehensive analysis."""
16
+ output_html = []
17
+
18
+ # Add result area container
19
+ output_html.append('<div class="result-area">')
20
+ output_html.append('<h2 class="task-header">Question Answering System</h2>')
21
+
22
+ output_html.append("""
23
+ <div class="alert alert-info">
24
+ <i class="fas fa-info-circle"></i>
25
+ Question Answering (QA) systems extract or generate answers to questions based on a given context or knowledge base.
26
+ This system can handle both extractive (finding answers in text) and abstractive (generating new answers) approaches.
27
+ </div>
28
+ """)
29
+
30
+ # Model info
31
+ output_html.append("""
32
+ <div class="alert alert-info">
33
+ <h4><i class="fas fa-tools"></i> Models & Techniques Used:</h4>
34
+ <ul>
35
+ <li><b>RoBERTa-SQuAD2</b> - Fine-tuned transformer model for extractive QA (F1: ~83.7 on SQuAD 2.0)</li>
36
+ <li><b>BERT-based QA</b> - Bidirectional encoder representations for understanding context</li>
37
+ <li><b>TF-IDF Similarity</b> - Traditional approach for finding relevant text spans</li>
38
+ <li><b>Confidence Scoring</b> - Model uncertainty estimation for answer reliability</li>
39
+ </ul>
40
+ </div>
41
+ """)
42
+
43
+ try:
44
+ # Validate inputs
45
+ if not context_text or not context_text.strip():
46
+ output_html.append('<div class="alert alert-warning">⚠️ Please provide a context text for question answering.</div>')
47
+ output_html.append('</div>')
48
+ return "\n".join(output_html)
49
+
50
+ if not question or not question.strip():
51
+ output_html.append('<div class="alert alert-warning">⚠️ Please provide a question to answer.</div>')
52
+ output_html.append('</div>')
53
+ return "\n".join(output_html)
54
+
55
+ # Display input information
56
+ output_html.append('<h3 class="task-subheader">Input Analysis</h3>')
57
+
58
+ context_stats = {
59
+ "Context Length": len(context_text),
60
+ "Word Count": len(context_text.split()),
61
+ "Sentence Count": len(nltk.sent_tokenize(context_text)),
62
+ "Question Length": len(question),
63
+ "Question Words": len(question.split())
64
+ }
65
+
66
+ stats_df = pd.DataFrame(list(context_stats.items()), columns=['Metric', 'Value'])
67
+ output_html.append('<h4>Input Statistics</h4>')
68
+ output_html.append(df_to_html_table(stats_df))
69
+
70
+ # Question Analysis
71
+ output_html.append('<h3 class="task-subheader">Question Analysis</h3>')
72
+
73
+ # Classify question type
74
+ question_lower = question.lower().strip()
75
+ question_type = classify_question_type(question_lower)
76
+
77
+ output_html.append(f"""
78
+ <div class="card">
79
+ <div class="card-header">
80
+ <h4 class="mb-0">Question Classification</h4>
81
+ </div>
82
+ <div class="card-body">
83
+ <p><strong>Question:</strong> {question}</p>
84
+ <p><strong>Type:</strong> {question_type['type']}</p>
85
+ <p><strong>Expected Answer:</strong> {question_type['expected']}</p>
86
+ <p><strong>Keywords:</strong> {', '.join(question_type['keywords'])}</p>
87
+ </div>
88
+ </div>
89
+ """)
90
+
91
+ # Extractive Question Answering using Transformer
92
+ output_html.append('<h3 class="task-subheader">Transformer-based Answer Extraction</h3>')
93
+
94
+ try:
95
+ qa_pipeline = load_qa_pipeline()
96
+
97
+ # Get answer from the model
98
+ result = qa_pipeline(question=question, context=context_text)
99
+
100
+ answer = result['answer']
101
+ confidence = result['score']
102
+ start_pos = result['start']
103
+ end_pos = result['end']
104
+
105
+ # Create confidence visualization
106
+ fig, ax = plt.subplots(1, 1, figsize=(8, 4))
107
+
108
+ # Confidence bar
109
+ colors = ['red' if confidence < 0.3 else 'orange' if confidence < 0.7 else 'green']
110
+ bars = ax.barh(['Confidence'], [confidence], color=colors[0])
111
+ ax.set_xlim(0, 1)
112
+ ax.set_xlabel('Confidence Score')
113
+ ax.set_title('Answer Confidence')
114
+
115
+ # Add confidence threshold line
116
+ ax.axvline(x=confidence_threshold, color='red', linestyle='--', label=f'Threshold ({confidence_threshold})')
117
+ ax.legend()
118
+
119
+ # Add value labels
120
+ for bar in bars:
121
+ width = bar.get_width()
122
+ ax.text(width/2, bar.get_y() + bar.get_height()/2,
123
+ f'{width:.3f}', ha='center', va='center', fontweight='bold')
124
+
125
+ plt.tight_layout()
126
+ output_html.append(fig_to_html(fig))
127
+ plt.close()
128
+
129
+ # Display answer with context highlighting
130
+ confidence_status = "High" if confidence >= 0.7 else "Medium" if confidence >= 0.3 else "Low"
131
+ confidence_color = "#4CAF50" if confidence >= 0.7 else "#FF9800" if confidence >= 0.3 else "#F44336"
132
+
133
+ output_html.append(f"""
134
+ <div class="card" style="border-color: {confidence_color};">
135
+ <div class="card-header" style="background-color: {confidence_color}22;">
136
+ <h4 class="mb-0">📝 Extracted Answer</h4>
137
+ </div>
138
+ <div class="card-body">
139
+ <div class="alert alert-light">
140
+ <strong>Answer:</strong> <span class="badge bg-warning text-dark fs-6">{answer}</span>
141
+ </div>
142
+ <p><strong>Confidence:</strong> {confidence:.3f} ({confidence_status})</p>
143
+ <p><strong>Position in Text:</strong> Characters {start_pos}-{end_pos}</p>
144
+ </div>
145
+ </div>
146
+ """)
147
+
148
+ # Show context with answer highlighted
149
+ highlighted_context = highlight_answer_in_context(context_text, start_pos, end_pos)
150
+ output_html.append(f"""
151
+ <div class="card">
152
+ <div class="card-header">
153
+ <h4 class="mb-0">📄 Context with Highlighted Answer</h4>
154
+ </div>
155
+ <div class="card-body">
156
+ <div style="line-height: 1.6; border: 1px solid #ddd; padding: 1rem; border-radius: 5px;">
157
+ {highlighted_context}
158
+ </div>
159
+ </div>
160
+ </div>
161
+ """)
162
+
163
+ except Exception as e:
164
+ output_html.append(f'<div class="alert alert-danger">❌ Error in transformer QA: {str(e)}</div>')
165
+
166
+ # Alternative: TF-IDF based answer extraction
167
+ output_html.append('<h3 class="task-subheader">TF-IDF Based Answer Extraction</h3>')
168
+
169
+ try:
170
+ tfidf_answer = extract_answer_tfidf(context_text, question)
171
+
172
+ output_html.append(f"""
173
+ <div class="alert alert-success">
174
+ <h4>🔍 TF-IDF Based Answer</h4>
175
+ <div class="alert alert-light">
176
+ <strong>Most Relevant Sentence:</strong> {tfidf_answer['sentence']}
177
+ </div>
178
+ <p><strong>Similarity Score:</strong> {tfidf_answer['score']:.3f}</p>
179
+ <p><strong>Method:</strong> Cosine similarity between question and context sentences using TF-IDF vectors</p>
180
+ </div>
181
+ """)
182
+
183
+ except Exception as e:
184
+ output_html.append(f'<div class="alert alert-danger">❌ Error in TF-IDF QA: {str(e)}</div>')
185
+
186
+ # Answer Quality Assessment
187
+ output_html.append('<h3 class="task-subheader">Answer Quality Assessment</h3>')
188
+
189
+ if 'confidence' in locals():
190
+ quality_metrics = assess_answer_quality(question, answer, confidence, context_text)
191
+
192
+ # Create quality assessment visualization
193
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))
194
+
195
+ # Quality metrics radar chart
196
+ categories = list(quality_metrics.keys())
197
+ values = list(quality_metrics.values())
198
+
199
+ ax1.bar(categories, values, color=['#4CAF50', '#2196F3', '#FF9800', '#9C27B0'])
200
+ ax1.set_ylim(0, 1)
201
+ ax1.set_title('Answer Quality Metrics')
202
+ ax1.set_ylabel('Score')
203
+ plt.setp(ax1.get_xticklabels(), rotation=45, ha='right')
204
+
205
+ # Overall quality score
206
+ overall_score = sum(values) / len(values)
207
+ quality_label = "Excellent" if overall_score >= 0.8 else "Good" if overall_score >= 0.6 else "Fair" if overall_score >= 0.4 else "Poor"
208
+
209
+ ax2.pie([overall_score, 1-overall_score], labels=[f'{quality_label}\n({overall_score:.2f})', 'Room for Improvement'],
210
+ colors=['#4CAF50', '#E0E0E0'], startangle=90)
211
+ ax2.set_title('Overall Answer Quality')
212
+
213
+ plt.tight_layout()
214
+ output_html.append(fig_to_html(fig))
215
+ plt.close()
216
+
217
+ # Quality metrics table
218
+ quality_df = pd.DataFrame([
219
+ {'Metric': 'Confidence', 'Score': f"{quality_metrics['Confidence']:.3f}", 'Description': 'Model confidence in the answer'},
220
+ {'Metric': 'Relevance', 'Score': f"{quality_metrics['Relevance']:.3f}", 'Description': 'Semantic similarity to question'},
221
+ {'Metric': 'Completeness', 'Score': f"{quality_metrics['Completeness']:.3f}", 'Description': 'Answer length appropriateness'},
222
+ {'Metric': 'Context Match', 'Score': f"{quality_metrics['Context_Match']:.3f}", 'Description': 'How well answer fits context'}
223
+ ])
224
+
225
+ output_html.append('<h4>Quality Assessment Details</h4>')
226
+ output_html.append(df_to_html_table(quality_df))
227
+
228
+ # Question-Answer Pairs Suggestions
229
+ output_html.append('<h3 class="task-subheader">Suggested Follow-up Questions</h3>')
230
+
231
+ try:
232
+ suggested_questions = generate_followup_questions(context_text, question, answer if 'answer' in locals() else "")
233
+
234
+ output_html.append('<div class="alert alert-warning">')
235
+ output_html.append('<h4>💡 Follow-up Questions:</h4>')
236
+ output_html.append('<ul>')
237
+ for i, q in enumerate(suggested_questions, 1):
238
+ output_html.append(f'<li><strong>Q{i}:</strong> {q}</li>')
239
+ output_html.append('</ul>')
240
+ output_html.append('</div>')
241
+
242
+ except Exception as e:
243
+ output_html.append(f'<div class="alert alert-danger">❌ Error generating suggestions: {str(e)}</div>')
244
+
245
+ except Exception as e:
246
+ output_html.append(f'<div class="alert alert-danger">❌ Unexpected error: {str(e)}</div>')
247
+
248
+ output_html.append('</div>')
249
+
250
+ # Add About section at the end
251
+ output_html.append(get_about_section())
252
+
253
+ return "\n".join(output_html)
254
+
255
+ def classify_question_type(question):
256
+ """Classify the type of question and expected answer format."""
257
+ question = question.lower().strip()
258
+
259
+ # Question word patterns
260
+ patterns = {
261
+ 'what': {'type': 'Definition/Fact', 'expected': 'Entity, concept, or description'},
262
+ 'who': {'type': 'Person', 'expected': 'Person name or group'},
263
+ 'when': {'type': 'Time', 'expected': 'Date, time, or temporal expression'},
264
+ 'where': {'type': 'Location', 'expected': 'Place, location, or spatial reference'},
265
+ 'why': {'type': 'Reason/Cause', 'expected': 'Explanation or causal relationship'},
266
+ 'how': {'type': 'Method/Process', 'expected': 'Process, method, or manner'},
267
+ 'which': {'type': 'Selection', 'expected': 'Specific choice from options'},
268
+ 'how much': {'type': 'Quantity', 'expected': 'Numerical amount or quantity'},
269
+ 'how many': {'type': 'Count', 'expected': 'Numerical count'},
270
+ 'is': {'type': 'Yes/No', 'expected': 'Boolean answer'},
271
+ 'are': {'type': 'Yes/No', 'expected': 'Boolean answer'},
272
+ 'can': {'type': 'Ability/Possibility', 'expected': 'Yes/No with explanation'},
273
+ 'will': {'type': 'Future/Prediction', 'expected': 'Future state or prediction'},
274
+ 'did': {'type': 'Past Action', 'expected': 'Yes/No about past events'}
275
+ }
276
+
277
+ # Extract keywords from question
278
+ words = question.split()
279
+ keywords = [word for word in words if len(word) > 2 and word not in ['the', 'and', 'but', 'for']]
280
+
281
+ # Determine question type
282
+ for pattern, info in patterns.items():
283
+ if question.startswith(pattern):
284
+ return {
285
+ 'type': info['type'],
286
+ 'expected': info['expected'],
287
+ 'keywords': keywords[:5] # Top 5 keywords
288
+ }
289
+
290
+ # Default classification
291
+ return {
292
+ 'type': 'General',
293
+ 'expected': 'Text span or explanation',
294
+ 'keywords': keywords[:5]
295
+ }
296
+
297
+ def extract_answer_tfidf(context, question):
298
+ """Extract answer using TF-IDF similarity."""
299
+ # Split context into sentences
300
+ sentences = nltk.sent_tokenize(context)
301
+
302
+ if len(sentences) == 0:
303
+ return {'sentence': 'No sentences found', 'score': 0.0}
304
+
305
+ # Create TF-IDF vectors
306
+ vectorizer = TfidfVectorizer(stop_words='english', lowercase=True)
307
+
308
+ # Combine question with sentences for vectorization
309
+ texts = [question] + sentences
310
+ tfidf_matrix = vectorizer.fit_transform(texts)
311
+
312
+ # Calculate cosine similarity between question and each sentence
313
+ question_vector = tfidf_matrix[0:1]
314
+ sentence_vectors = tfidf_matrix[1:]
315
+
316
+ similarities = cosine_similarity(question_vector, sentence_vectors).flatten()
317
+
318
+ # Find the most similar sentence
319
+ best_idx = np.argmax(similarities)
320
+ best_sentence = sentences[best_idx]
321
+ best_score = similarities[best_idx]
322
+
323
+ return {
324
+ 'sentence': best_sentence,
325
+ 'score': best_score
326
+ }
327
+
328
+ def highlight_answer_in_context(context, start_pos, end_pos):
329
+ """Highlight the answer span in the context."""
330
+ before = context[:start_pos]
331
+ answer = context[start_pos:end_pos]
332
+ after = context[end_pos:]
333
+
334
+ highlighted = f'{before}<mark style="background-color: #FFEB3B; padding: 2px 4px; border-radius: 3px; font-weight: bold;">{answer}</mark>{after}'
335
+
336
+ return highlighted
337
+
338
+ def assess_answer_quality(question, answer, confidence, context):
339
+ """Assess the quality of the extracted answer."""
340
+ metrics = {}
341
+
342
+ # Confidence score (from model)
343
+ metrics['Confidence'] = confidence
344
+
345
+ # Relevance (simple keyword overlap)
346
+ question_words = set(question.lower().split())
347
+ answer_words = set(answer.lower().split())
348
+ overlap = len(question_words.intersection(answer_words))
349
+ metrics['Relevance'] = min(overlap / max(len(question_words), 1), 1.0)
350
+
351
+ # Completeness (answer length appropriateness)
352
+ answer_length = len(answer.split())
353
+ if answer_length == 0:
354
+ metrics['Completeness'] = 0.0
355
+ elif answer_length < 3:
356
+ metrics['Completeness'] = 0.6
357
+ elif answer_length <= 20:
358
+ metrics['Completeness'] = 1.0
359
+ else:
360
+ metrics['Completeness'] = 0.8 # Very long answers might be too verbose
361
+
362
+ # Context match (how well the answer fits in context)
363
+ answer_in_context = answer.lower() in context.lower()
364
+ metrics['Context_Match'] = 1.0 if answer_in_context else 0.5
365
+
366
+ return metrics
367
+
368
+ def generate_followup_questions(context, original_question, answer):
369
+ """Generate relevant follow-up questions based on the context and answer."""
370
+ suggestions = []
371
+
372
+ # Extract key entities and concepts from context
373
+ words = context.split()
374
+
375
+ # Template-based question generation
376
+ templates = [
377
+ f"What else can you tell me about {answer}?",
378
+ "Can you provide more details about this topic?",
379
+ "What are the implications of this information?",
380
+ "How does this relate to other concepts mentioned?",
381
+ "What evidence supports this answer?"
382
+ ]
383
+
384
+ # Add context-specific questions
385
+ if "when" not in original_question.lower():
386
+ suggestions.append("When did this happen?")
387
+
388
+ if "where" not in original_question.lower():
389
+ suggestions.append("Where did this take place?")
390
+
391
+ if "why" not in original_question.lower():
392
+ suggestions.append("Why is this significant?")
393
+
394
+ if "how" not in original_question.lower():
395
+ suggestions.append("How does this work?")
396
+
397
+ # Combine and limit suggestions
398
+ all_suggestions = templates + suggestions
399
+ return all_suggestions[:5] # Return top 5 suggestions
400
+
401
+ def qa_api_handler(context, question):
402
+ """API handler for question answering that returns structured data."""
403
+ try:
404
+ qa_pipeline = load_qa_pipeline()
405
+ result = qa_pipeline(question=question, context=context)
406
+
407
+ return {
408
+ "answer": result['answer'],
409
+ "confidence": result['score'],
410
+ "start_position": result['start'],
411
+ "end_position": result['end'],
412
+ "success": True,
413
+ "error": None
414
+ }
415
+ except Exception as e:
416
+ return {
417
+ "answer": "",
418
+ "confidence": 0.0,
419
+ "start_position": 0,
420
+ "end_position": 0,
421
+ "success": False,
422
+ "error": str(e)
423
+ }
424
+
425
+ def process_question_with_context(context_text, question):
426
+ """Process a question with the given context and return a formatted result."""
427
+ if not context_text or not context_text.strip():
428
+ return {
429
+ "success": False,
430
+ "error": "No context text provided",
431
+ "html": '<div class="alert alert-warning">⚠️ No context text provided.</div>'
432
+ }
433
+
434
+ if not question or not question.strip():
435
+ return {
436
+ "success": False,
437
+ "error": "No question provided",
438
+ "html": '<div class="alert alert-warning">⚠️ Please enter a question.</div>'
439
+ }
440
+
441
+ try:
442
+ qa_pipeline = load_qa_pipeline()
443
+ result = qa_pipeline(question=question, context=context_text)
444
+
445
+ answer = result['answer']
446
+ confidence = result['score']
447
+ start_pos = result['start']
448
+ end_pos = result['end']
449
+
450
+ # Determine confidence level
451
+ confidence_status = "High" if confidence >= 0.7 else "Medium" if confidence >= 0.3 else "Low"
452
+ confidence_color = "#4CAF50" if confidence >= 0.7 else "#FF9800" if confidence >= 0.3 else "#F44336"
453
+
454
+ # Highlight answer in context
455
+ highlighted_context = highlight_answer_in_context(context_text, start_pos, end_pos)
456
+
457
+ # Create formatted HTML result
458
+ html_result = f"""
459
+ <div class="card">
460
+ <div class="card-header">
461
+ <h5 class="mb-0">📝 Answer Found!</h5>
462
+ </div>
463
+ <div class="card-body">
464
+ <div class="alert alert-light">
465
+ <p><strong>Question:</strong> {question}</p>
466
+ <p><strong>Answer:</strong> <span class="badge bg-warning text-dark fs-6">{answer}</span></p>
467
+ <p><strong>Confidence:</strong> {confidence:.3f} ({confidence_status})</p>
468
+ </div>
469
+
470
+ <div class="alert alert-light">
471
+ <h6>📄 Context with Highlighted Answer:</h6>
472
+ <div style="line-height: 1.6; font-size: 0.9rem; max-height: 200px; overflow-y: auto;">
473
+ {highlighted_context}
474
+ </div>
475
+ </div>
476
+
477
+ <div class="alert alert-info">
478
+ <strong>Quality Assessment:</strong>
479
+ <ul class="mb-0">
480
+ <li>Confidence: {confidence_status} ({confidence:.1%})</li>
481
+ <li>Answer found at position: {start_pos}-{end_pos}</li>
482
+ <li>Answer length: {len(answer.split())} words</li>
483
+ </ul>
484
+ </div>
485
+ </div>
486
+ </div>
487
+ """
488
+
489
+ return {
490
+ "success": True,
491
+ "answer": answer,
492
+ "confidence": confidence,
493
+ "html": html_result
494
+ }
495
+
496
+ except Exception as e:
497
+ error_html = f'<div class="alert alert-danger">❌ Error processing question: {str(e)}</div>'
498
+ return {
499
+ "success": False,
500
+ "error": str(e),
501
+ "html": error_html
502
+ }
503
+
504
+ def get_about_section():
505
+ """Generate the About Question Answering section"""
506
+ return """
507
+ <div class="card mt-4">
508
+ <div class="card-header bg-primary text-white">
509
+ <h4><i class="fas fa-info-circle me-2"></i>About Question Answering</h4>
510
+ </div>
511
+ <div class="card-body">
512
+ <h5>What is Question Answering?</h5>
513
+ <p>Question Answering (QA) is an NLP technique that automatically finds answers to questions posed in natural language. It involves understanding both the question and the context to extract or generate relevant answers.</p>
514
+
515
+ <h5>Applications of Question Answering:</h5>
516
+ <ul>
517
+ <li><strong>Customer Support</strong> - Automatically answering customer queries from knowledge bases</li>
518
+ <li><strong>Educational Systems</strong> - Helping students find answers in textbooks and materials</li>
519
+ <li><strong>Information Retrieval</strong> - Extracting specific information from large documents</li>
520
+ <li><strong>Virtual Assistants</strong> - Powering AI assistants like Siri, Alexa, and Google Assistant</li>
521
+ <li><strong>Research Tools</strong> - Helping researchers quickly find relevant information in papers</li>
522
+ <li><strong>Legal Analysis</strong> - Finding relevant clauses and information in legal documents</li>
523
+ </ul>
524
+
525
+ <h5>How It Works:</h5>
526
+ <p>Our system uses transformer-based models to understand questions and find relevant answers in the provided context. It analyzes question types, extracts key information, and provides confidence scores for the answers found.</p>
527
+ </div>
528
+ </div>
529
+ """