Serhan Yılmaz commited on
Commit
e65e67f
·
1 Parent(s): c1ff2ef
Files changed (1) hide show
  1. pipeline_gradio_experimental.py +587 -0
pipeline_gradio_experimental.py ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import logging
3
+ import json
4
+ import gradio as gr
5
+ import pandas as pd
6
+ from datasets import load_dataset
7
+ import random
8
+ from openai import OpenAI
9
+ from typing import List, Tuple
10
+ from dotenv import load_dotenv
11
+ import numpy as np
12
+
13
+ # Set up logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ # Load environment variables
18
+ load_dotenv()
19
+
20
+ # Initialize OpenAI client
21
+ client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
22
+
23
+ # Load the dataset
24
+ dataset = load_dataset("serhany/scaling-qa")
25
+
26
+ # Define sample inputs
27
+ samples = [
28
+ {
29
+ "context": "Albert Einstein is an Austrian scientist, who has completed his higher education in ETH Zurich in Zurich, Switzerland. He was later a faculty at Princeton University.",
30
+ "answer": "Switzerland"
31
+ },
32
+ {
33
+ "context": "The Eiffel Tower, located in Paris, France, is one of the most famous landmarks in the world. It was constructed in 1889 as the entrance arch to the 1889 World's Fair. The tower is 324 meters (1,063 ft) tall and is the tallest structure in Paris.",
34
+ "answer": "Paris"
35
+ },
36
+ {
37
+ "context": "The Great Wall of China is a series of fortifications and walls built across the historical northern borders of ancient Chinese states and Imperial China to protect against nomadic invasions. It is the largest man-made structure in the world, with a total length of more than 13,000 miles (21,000 kilometers).",
38
+ "answer": "China"
39
+ }
40
+ ]
41
+
42
+ def generate_basic_question(context: str, answer: str) -> str:
43
+ try:
44
+ response = client.chat.completions.create(
45
+ model="gpt-4o-2024-08-06",
46
+ messages=[
47
+ {"role": "system", "content": "You are a helpful assistant that generates diverse questions based on given context and answer."},
48
+ {"role": "user", "content": f"Based on this context: '{context}' and answer: '{answer}', generate a single question which when asked to the context returns the answer. Provide only the question, without any additional text."}
49
+ ],
50
+ response_format={
51
+ "type": "json_schema",
52
+ "json_schema": {
53
+ "name": "single_question_generator",
54
+ "strict": True,
55
+ "schema": {
56
+ "type": "object",
57
+ "properties": {
58
+ "question": {"type": "string"}
59
+ },
60
+ "required": ["question"],
61
+ "additionalProperties": False
62
+ }
63
+ }
64
+ }
65
+ )
66
+
67
+ json_response = response.choices[0].message.content
68
+ logger.info(f"Raw JSON response: {json_response}")
69
+
70
+ parsed_response = json.loads(json_response)
71
+ return parsed_response["question"]
72
+ except Exception as e:
73
+ logger.error(f"Error in generate_single_question: {e}")
74
+ return "Failed to generate question"
75
+
76
+
77
+ def generate_single_question(context: str, answer: str, existing_questions: List[str]) -> str:
78
+ try:
79
+ existing_questions_str = "\n".join(existing_questions)
80
+ response = client.chat.completions.create(
81
+ model="gpt-4o-2024-08-06",
82
+ messages=[
83
+ {"role": "system", "content": "You are a helpful assistant that generates diverse questions based on given context and answer."},
84
+ {"role": "user", "content": f"Based on this context: '{context}' and answer: '{answer}', generate a single question which when asked to the context returns the answer. The question should be distinct from these existing questions:\n{existing_questions_str}\n\nProvide only the new question, without any additional text."}
85
+ ],
86
+ response_format={
87
+ "type": "json_schema",
88
+ "json_schema": {
89
+ "name": "single_question_generator",
90
+ "strict": True,
91
+ "schema": {
92
+ "type": "object",
93
+ "properties": {
94
+ "question": {"type": "string"}
95
+ },
96
+ "required": ["question"],
97
+ "additionalProperties": False
98
+ }
99
+ }
100
+ }
101
+ )
102
+
103
+ json_response = response.choices[0].message.content
104
+ logger.info(f"Raw JSON response: {json_response}")
105
+
106
+ parsed_response = json.loads(json_response)
107
+ return parsed_response["question"]
108
+ except Exception as e:
109
+ logger.error(f"Error in generate_single_question: {e}")
110
+ return "Failed to generate question"
111
+
112
+ ############################# Experimental Code - Begin ########################################
113
+
114
+ # def is_question_distinct(new_question: str, existing_questions: List[str]) -> bool:
115
+ # try:
116
+ # existing_questions_str = "\n".join(existing_questions)
117
+ # response = client.chat.completions.create(
118
+ # model="gpt-4o-2024-08-06",
119
+ # messages=[
120
+ # {"role": "system", "content": "You are an expert in linguistic analysis, specializing in question comparison."},
121
+ # {"role": "user", "content": f"Compare the following new question to the list of existing questions. Determine if the new question is distinct in meaning and structure from all existing questions. Respond with true if it's distinct, false if it's too similar to any existing question.\n\nNew question: {new_question}\n\nExisting questions:\n{existing_questions_str}"}
122
+ # ],
123
+ # response_format={
124
+ # "type": "json_schema",
125
+ # "json_schema": {
126
+ # "name": "distinctness_checker",
127
+ # "strict": True,
128
+ # "schema": {
129
+ # "type": "object",
130
+ # "properties": {
131
+ # "is_distinct": {"type": "boolean"}
132
+ # },
133
+ # "required": ["is_distinct"],
134
+ # "additionalProperties": False
135
+ # }
136
+ # }
137
+ # }
138
+ # )
139
+
140
+ # json_response = response.choices[0].message.content
141
+ # logger.info(f"Raw JSON response: {json_response}")
142
+
143
+ # parsed_response = json.loads(json_response)
144
+ # return parsed_response["is_distinct"]
145
+ # except Exception as e:
146
+ # logger.error(f"Error in is_question_distinct: {e}")
147
+ # return False # Assume not distinct in case of error
148
+
149
+ ############################# Experimental Code - End ########################################
150
+
151
+ def is_question_distinct(new_question: str, existing_questions: List[str]) -> bool:
152
+ # Convert the new question to lowercase and remove any leading/trailing whitespace
153
+ new_question_normalized = new_question.strip().lower()
154
+
155
+ # Check if the normalized new question is already in the list of existing questions
156
+ for question in existing_questions:
157
+ if new_question_normalized == question.strip().lower():
158
+ return False
159
+
160
+ # If we've made it through the loop, the question is distinct
161
+ return True
162
+
163
+ def generate_questions(context: str, answer: str) -> List[str]:
164
+ questions = []
165
+ max_attempts = 10 # Maximum number of attempts to generate distinct questions
166
+
167
+ while len(questions) < 5 and max_attempts > 0:
168
+ new_question = generate_single_question(context, answer, questions)
169
+ if new_question != "Failed to generate question" and is_question_distinct(new_question, questions):
170
+ questions.append(new_question)
171
+ else:
172
+ max_attempts -= 1
173
+
174
+ # If we couldn't generate 5 distinct questions, fill the rest with placeholder messages
175
+ while len(questions) < 5:
176
+ questions.append(f"Failed to generate distinct question {len(questions) + 1}")
177
+
178
+ return questions
179
+
180
+ def generate_answer(context: str, question: str) -> str:
181
+ try:
182
+ response = client.chat.completions.create(
183
+ model="gpt-4o-2024-08-06",
184
+ messages=[
185
+ {"role": "system", "content": "You are a helpful assistant that provides concise answers based on the given context."},
186
+ {"role": "user", "content": f"Context: {context}\n\nQuestion: {question}\n\nProvide a concise answer to the question based on the given context."}
187
+ ],
188
+ response_format={
189
+ "type": "json_schema",
190
+ "json_schema": {
191
+ "name": "answer_generator",
192
+ "strict": True,
193
+ "schema": {
194
+ "type": "object",
195
+ "properties": {
196
+ "answer": {"type": "string"}
197
+ },
198
+ "required": ["answer"],
199
+ "additionalProperties": False
200
+ }
201
+ }
202
+ }
203
+ )
204
+
205
+ json_response = response.choices[0].message.content
206
+ logger.info(f"Raw JSON response: {json_response}")
207
+
208
+ parsed_response = json.loads(json_response)
209
+ return parsed_response["answer"]
210
+ except Exception as e:
211
+ logger.error(f"Error in generate_answer: {e}")
212
+ return "Failed to generate answer"
213
+
214
+ def calculate_structural_diversity(questions: List[str]) -> List[float]:
215
+ try:
216
+ response = client.chat.completions.create(
217
+ model="gpt-4o-2024-08-06",
218
+ messages=[
219
+ {"role": "system", "content": "You are an expert in linguistic analysis, specializing in question structure and diversity."},
220
+ {"role": "user", "content": f"Analyze the structural diversity of the following questions and provide a diversity score for each on a scale of 0 to 1, where 1 is highly diverse:\n\n{json.dumps(questions)}"}
221
+ ],
222
+ response_format={
223
+ "type": "json_schema",
224
+ "json_schema": {
225
+ "name": "structural_diversity_analyzer",
226
+ "strict": True,
227
+ "schema": {
228
+ "type": "object",
229
+ "properties": {
230
+ "diversity_scores": {
231
+ "type": "array",
232
+ "items": {
233
+ "type": "number"
234
+ }
235
+ },
236
+ "explanation": {"type": "string"}
237
+ },
238
+ "required": ["diversity_scores", "explanation"],
239
+ "additionalProperties": False
240
+ }
241
+ }
242
+ }
243
+ )
244
+
245
+ json_response = response.choices[0].message.content
246
+ logger.info(f"Raw JSON response: {json_response}")
247
+
248
+ parsed_response = json.loads(json_response)
249
+ diversity_scores = parsed_response["diversity_scores"]
250
+ explanation = parsed_response["explanation"]
251
+
252
+ logger.info(f"Structural Diversity Explanation: {explanation}")
253
+
254
+ return diversity_scores
255
+ except Exception as e:
256
+ logger.error(f"Error in calculate_structural_diversity: {e}")
257
+ return [0.5] * len(questions) # Return neutral scores in case of error
258
+
259
+ def calculate_semantic_relevance(context: str, answer: str, questions: List[str]) -> List[float]:
260
+ try:
261
+ response = client.chat.completions.create(
262
+ model="gpt-4o-2024-08-06",
263
+ messages=[
264
+ {"role": "system", "content": "You are an expert in semantic analysis, specializing in evaluating the relevance of questions to a given context and answer."},
265
+ {"role": "user", "content": f"Analyze the semantic relevance of the following questions to the given context and answer. Provide a relevance score for each question on a scale of 0 to 1, where 1 is highly relevant:\n\nContext: {context}\nAnswer: {answer}\nQuestions: {json.dumps(questions)}"}
266
+ ],
267
+ response_format={
268
+ "type": "json_schema",
269
+ "json_schema": {
270
+ "name": "semantic_relevance_analyzer",
271
+ "strict": True,
272
+ "schema": {
273
+ "type": "object",
274
+ "properties": {
275
+ "relevance_scores": {
276
+ "type": "array",
277
+ "items": {
278
+ "type": "number"
279
+ }
280
+ },
281
+ "explanation": {"type": "string"}
282
+ },
283
+ "required": ["relevance_scores", "explanation"],
284
+ "additionalProperties": False
285
+ }
286
+ }
287
+ }
288
+ )
289
+
290
+ json_response = response.choices[0].message.content
291
+ logger.info(f"Raw JSON response: {json_response}")
292
+
293
+ parsed_response = json.loads(json_response)
294
+ relevance_scores = parsed_response["relevance_scores"]
295
+ explanation = parsed_response["explanation"]
296
+
297
+ logger.info(f"Semantic Relevance Explanation: {explanation}")
298
+
299
+ return relevance_scores
300
+ except Exception as e:
301
+ logger.error(f"Error in calculate_semantic_relevance: {e}")
302
+ return [0.5] * len(questions) # Return neutral scores in case of error
303
+
304
+ # def check_answer_precision(context: str, questions: List[str], original_answer: str) -> Tuple[List[float], List[str]]:
305
+ # precision_scores = []
306
+ # generated_answers = []
307
+ # for question in questions:
308
+ # generated_answer = generate_answer(context, question)
309
+ # generated_answers.append(generated_answer)
310
+
311
+ # # Use OpenAI to evaluate answer precision
312
+ # try:
313
+ # response = client.chat.completions.create(
314
+ # model="gpt-4o-2024-08-06",
315
+ # messages=[
316
+ # {"role": "system", "content": "You are an expert in evaluating answer precision."},
317
+ # {"role": "user", "content": f"Compare the following two answers and provide a precision score from 0 to 1, where 1 means the answers are identical in meaning or point in the same direction. For example, Answer 1: religious plays and Answer 2: Elizabeth I forbade all religious plays in 1558.
318
+ # :\n\nOriginal Answer: {original_answer}\nGenerated Answer: {generated_answer}"}
319
+ # ],
320
+ # response_format={
321
+ # "type": "json_schema",
322
+ # "json_schema": {
323
+ # "name": "answer_precision_evaluator",
324
+ # "strict": True,
325
+ # "schema": {
326
+ # "type": "object",
327
+ # "properties": {
328
+ # "precision_score": {
329
+ # "type": "number"
330
+ # }
331
+ # },
332
+ # "required": ["precision_score"],
333
+ # "additionalProperties": False
334
+ # }
335
+ # }
336
+ # }
337
+ # )
338
+
339
+ # json_response = response.choices[0].message.content
340
+ # parsed_response = json.loads(json_response)
341
+ # precision_score = parsed_response["precision_score"]
342
+ # precision_scores.append(precision_score)
343
+ # except Exception as e:
344
+ # logger.error(f"Error in evaluating answer precision: {e}")
345
+ # precision_scores.append(0.5) # Neutral score in case of error
346
+
347
+ # return precision_scores, generated_answers
348
+
349
+ def check_answer_precision(context: str, questions: List[str], original_answer: str) -> Tuple[List[float], List[str]]:
350
+ precision_scores = []
351
+ generated_answers = []
352
+ for question in questions:
353
+ generated_answer = generate_answer(context, question)
354
+ generated_answers.append(generated_answer)
355
+
356
+ # Use OpenAI to evaluate answer precision
357
+ try:
358
+ response = client.chat.completions.create(
359
+ model="gpt-4o-2024-08-06",
360
+ messages=[
361
+ {"role": "system", "content": "You are an expert in evaluating answer precision."},
362
+ {"role": "user", "content": f"""Given the context, the original question, and the original answer, evaluate how close the new answer is to the original answer. Provide a precision score from 0 to 1, where 1 means the answers are identical in meaning and 0 means they are completely unrelated.
363
+
364
+ Example:
365
+ Context: The end of medieval drama came about due to a number of factors, including the weakening power of the Catholic Church, the Protestant Reformation and the banning of religious plays in many countries. Elizabeth I forbid all religious plays in 1558 and the great cycle plays had been silenced by the 1580s. Similarly, religious plays were banned in the Netherlands in 1539, the Papal States in 1547 and in Paris in 1548. The abandonment of these plays destroyed the international theatre that had thereto existed and forced each country to develop its own form of drama. It also allowed dramatists to turn to secular subjects and the reviving interest in Greek and Roman theatre provided them with the perfect opportunity.
366
+ Question: What was banned that led to the demise of medieval drama?
367
+ Original Answer: religious plays
368
+ New Answer: Elizabeth I forbade all religious plays in 1558.
369
+ Precision Score: 0.6
370
+
371
+ New Answer: Religious plays were suppressed.
372
+ Precision Score: 0.75
373
+
374
+ New Answer: Religious plays
375
+ Precision Score: 1.0
376
+
377
+ Now evaluate the following:
378
+ Context: {context}
379
+ Question: {question}
380
+ Original Answer: {original_answer}
381
+ New Answer: {generated_answer}
382
+
383
+ Provide only the precision score as a number between 0 and 1."""}
384
+ ],
385
+ response_format={
386
+ "type": "json_schema",
387
+ "json_schema": {
388
+ "name": "answer_precision_evaluator",
389
+ "strict": True,
390
+ "schema": {
391
+ "type": "object",
392
+ "properties": {
393
+ "precision_score": {
394
+ "type": "number"
395
+ }
396
+ },
397
+ "required": ["precision_score"],
398
+ "additionalProperties": False
399
+ }
400
+ }
401
+ }
402
+ )
403
+
404
+ json_response = response.choices[0].message.content
405
+ parsed_response = json.loads(json_response)
406
+ precision_score = parsed_response["precision_score"]
407
+ precision_scores.append(precision_score)
408
+ except Exception as e:
409
+ logger.error(f"Error in evaluating answer precision: {e}")
410
+ precision_scores.append(0.5) # Neutral score in case of error
411
+
412
+ return precision_scores, generated_answers
413
+
414
+
415
+ def calculate_composite_scores(sd_scores: List[float], sr_scores: List[float], ap_scores: List[float]) -> List[float]:
416
+ return [0.3 * sd + 0.3 * sr + 0.4 * ap for sd, sr, ap in zip(sd_scores, sr_scores, ap_scores)]
417
+
418
+ # def rank_questions_with_details(context: str, answer: str) -> Tuple[pd.DataFrame, List[pd.DataFrame], str]:
419
+ # questions = generate_questions(context, answer)
420
+
421
+ # sd_scores = calculate_structural_diversity(questions)
422
+ # sr_scores = calculate_semantic_relevance(context, answer, questions)
423
+ # ap_scores, generated_answers = check_answer_precision(context, questions, answer)
424
+
425
+ # composite_scores = calculate_composite_scores(sd_scores, sr_scores, ap_scores)
426
+
427
+ # # Create detailed scores dataframe
428
+ # detailed_scores = pd.DataFrame({
429
+ # 'Question': questions,
430
+ # 'Answer Precision': ap_scores,
431
+ # 'Composite Score': composite_scores,
432
+ # 'Structural Diversity': sd_scores,
433
+ # 'Semantic Relevance': sr_scores,
434
+ # 'Generated Answer': generated_answers
435
+ # })
436
+ # detailed_scores = detailed_scores.sort_values('Composite Score', ascending=False).reset_index(drop=True)
437
+
438
+ # # Create separate ranking dataframes for each metric
439
+ # metrics = ['Answer Precision', 'Composite Score', 'Structural Diversity', 'Semantic Relevance']
440
+ # rankings = []
441
+
442
+ # for metric in metrics:
443
+ # df = pd.DataFrame({
444
+ # 'Rank': range(1, 6),
445
+ # 'Question': [questions[i] for i in np.argsort(detailed_scores[metric])[::-1]],
446
+ # f'{metric}': sorted(detailed_scores[metric], reverse=True)
447
+ # })
448
+ # if metric == 'Answer Precision':
449
+ # df['Generated Answer'] = [generated_answers[i] for i in np.argsort(detailed_scores[metric])[::-1]]
450
+ # rankings.append(df)
451
+
452
+ # best_question = detailed_scores.iloc[0]['Question']
453
+
454
+ # return detailed_scores, rankings, best_question
455
+
456
+ def rank_questions_with_details(context: str, answer: str) -> Tuple[pd.DataFrame, List[pd.DataFrame], str]:
457
+ questions = generate_questions(context, answer)
458
+
459
+ sd_scores = calculate_structural_diversity(questions)
460
+ sr_scores = calculate_semantic_relevance(context, answer, questions)
461
+ ap_scores, generated_answers = check_answer_precision(context, questions, answer)
462
+
463
+ composite_scores = calculate_composite_scores(sd_scores, sr_scores, ap_scores)
464
+
465
+ # Create detailed scores dataframe
466
+ detailed_scores = pd.DataFrame({
467
+ 'Question': questions,
468
+ 'Answer Precision': ap_scores,
469
+ 'Composite Score': composite_scores,
470
+ 'Structural Diversity': sd_scores,
471
+ 'Semantic Relevance': sr_scores,
472
+ 'Generated Answer': generated_answers
473
+ })
474
+ detailed_scores = detailed_scores.sort_values('Composite Score', ascending=False).reset_index(drop=True)
475
+
476
+ # Create separate ranking dataframes for each metric
477
+ metrics = ['Answer Precision', 'Composite Score', 'Structural Diversity', 'Semantic Relevance']
478
+ rankings = []
479
+
480
+ for metric in metrics:
481
+ df = pd.DataFrame({
482
+ 'Rank': range(1, 6),
483
+ 'Question': [questions[i] for i in np.argsort(detailed_scores[metric])[::-1]],
484
+ f'{metric}': sorted(detailed_scores[metric], reverse=True)
485
+ })
486
+ if metric == 'Answer Precision':
487
+ df['Generated Answer'] = [generated_answers[i] for i in np.argsort(detailed_scores[metric])[::-1]]
488
+ rankings.append(df)
489
+
490
+ best_question = detailed_scores.iloc[0]['Question']
491
+
492
+ return detailed_scores, rankings, best_question
493
+
494
+ def gradio_interface(context: str, answer: str) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, str]:
495
+ detailed_scores, rankings, best_question = rank_questions_with_details(context, answer)
496
+ return (
497
+ detailed_scores,
498
+ rankings[0], # Answer Precision Ranking
499
+ rankings[1], # Composite Score Ranking
500
+ rankings[2], # Structural Diversity Ranking
501
+ rankings[3], # Semantic Relevance Ranking
502
+ f"Best Question: {best_question}"
503
+ )
504
+
505
+ def use_sample(sample_index: int) -> Tuple[str, str]:
506
+ return samples[sample_index]["context"], samples[sample_index]["answer"]
507
+
508
+ def get_random_entry():
509
+ random_index = random.randint(0, len(dataset['train']) - 1)
510
+ entry = dataset['train'][random_index]
511
+ return entry['context'], entry['answer'], entry['question']
512
+
513
+ # Create Gradio interface
514
+ with gr.Blocks(theme=gr.themes.Default()) as iface:
515
+ gr.Markdown("# Question Generator and Ranker")
516
+ gr.Markdown("Enter a context and an answer to generate and rank questions, use one of the sample inputs, or get a random entry from the dataset.")
517
+
518
+ with gr.Row():
519
+ with gr.Column(scale=1):
520
+ context_input = gr.Textbox(lines=5, label="Context")
521
+ answer_input = gr.Textbox(lines=2, label="Answer")
522
+ submit_button = gr.Button("Generate Questions")
523
+
524
+ with gr.Row():
525
+ sample_buttons = [gr.Button(f"Sample {i+1}") for i in range(3)]
526
+ random_button = gr.Button("Random Dataset Entry")
527
+
528
+ with gr.Column(scale=2):
529
+ original_question_output = gr.Dataframe(label="Original Question from Dataset", visible=False)
530
+ best_question_output = gr.Textbox(label="Best Generated Question")
531
+ detailed_scores_output = gr.DataFrame(label="Detailed Scores")
532
+
533
+ with gr.Row():
534
+ with gr.Column():
535
+ answer_precision_ranking_output = gr.DataFrame(label="Answer Precision Ranking")
536
+ with gr.Column():
537
+ composite_ranking_output = gr.DataFrame(label="Composite Score Ranking")
538
+
539
+ with gr.Row():
540
+ with gr.Column():
541
+ structural_diversity_ranking_output = gr.DataFrame(label="Structural Diversity Ranking")
542
+ with gr.Column():
543
+ semantic_relevance_ranking_output = gr.DataFrame(label="Semantic Relevance Ranking")
544
+
545
+ def process_random_entry():
546
+ context, answer, original_question = get_random_entry()
547
+ return (
548
+ context,
549
+ answer,
550
+ pd.DataFrame({'Original Question': [original_question]}),
551
+ gr.update(visible=True)
552
+ )
553
+
554
+ submit_button.click(
555
+ fn=gradio_interface,
556
+ inputs=[context_input, answer_input],
557
+ outputs=[
558
+ detailed_scores_output,
559
+ answer_precision_ranking_output,
560
+ composite_ranking_output,
561
+ structural_diversity_ranking_output,
562
+ semantic_relevance_ranking_output,
563
+ best_question_output
564
+ ]
565
+ )
566
+
567
+ # Set up sample button functionality
568
+ for i, button in enumerate(sample_buttons):
569
+ button.click(
570
+ fn=lambda i=i: use_sample(i),
571
+ outputs=[context_input, answer_input]
572
+ )
573
+
574
+ # Set up random button functionality
575
+ random_button.click(
576
+ fn=process_random_entry,
577
+ outputs=[
578
+ context_input,
579
+ answer_input,
580
+ original_question_output,
581
+ original_question_output
582
+ ]
583
+ )
584
+
585
+ # Launch the app
586
+ if __name__ == "__main__":
587
+ iface.launch()