Spaces:
Sleeping
Sleeping
File size: 16,383 Bytes
73b3691 |
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 |
import os
import logging
import json
import gradio as gr
import pandas as pd
from datasets import load_dataset
import random
from openai import OpenAI
from typing import List, Tuple
import numpy as np
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialize OpenAI client
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# Load the dataset
dataset = load_dataset("serhany/scaling-qa")
# Define sample inputs
samples = [
{
"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.",
"answer": "Switzerland"
},
{
"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.",
"answer": "Paris"
},
{
"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).",
"answer": "China"
}
]
def generate_questions(context: str, answer: str) -> List[str]:
try:
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are a helpful assistant that generates diverse questions based on given context and answer."},
{"role": "user", "content": f"Based on this context: '{context}' and answer: '{answer}', generate 5 diverse questions which when asked to the context returns the answer."}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "question_generator",
"strict": True,
"schema": {
"type": "object",
"properties": {
"question1": {"type": "string"},
"question2": {"type": "string"},
"question3": {"type": "string"},
"question4": {"type": "string"},
"question5": {"type": "string"}
},
"required": ["question1", "question2", "question3", "question4", "question5"],
"additionalProperties": False
}
}
}
)
json_response = response.choices[0].message.content
logger.info(f"Raw JSON response: {json_response}")
parsed_response = json.loads(json_response)
questions = [parsed_response[f"question{i}"] for i in range(1, 6)]
return questions
except Exception as e:
logger.error(f"Error in generate_questions: {e}")
return [f"Failed to generate question {i}" for i in range(1, 6)]
def generate_answer(context: str, question: str) -> str:
try:
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are a helpful assistant that provides concise answers based on the given context."},
{"role": "user", "content": f"Context: {context}\n\nQuestion: {question}\n\nProvide a concise answer to the question based on the given context."}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "answer_generator",
"strict": True,
"schema": {
"type": "object",
"properties": {
"answer": {"type": "string"}
},
"required": ["answer"],
"additionalProperties": False
}
}
}
)
json_response = response.choices[0].message.content
logger.info(f"Raw JSON response: {json_response}")
parsed_response = json.loads(json_response)
return parsed_response["answer"]
except Exception as e:
logger.error(f"Error in generate_answer: {e}")
return "Failed to generate answer"
def calculate_structural_diversity(questions: List[str]) -> List[float]:
try:
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are an expert in linguistic analysis, specializing in question structure and diversity."},
{"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)}"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "structural_diversity_analyzer",
"strict": True,
"schema": {
"type": "object",
"properties": {
"diversity_scores": {
"type": "array",
"items": {
"type": "number",
}
},
"explanation": {"type": "string"}
},
"required": ["diversity_scores", "explanation"],
"additionalProperties": False
}
}
}
)
json_response = response.choices[0].message.content
logger.info(f"Raw JSON response: {json_response}")
parsed_response = json.loads(json_response)
diversity_scores = parsed_response["diversity_scores"]
explanation = parsed_response["explanation"]
logger.info(f"Structural Diversity Explanation: {explanation}")
return diversity_scores
except Exception as e:
logger.error(f"Error in calculate_structural_diversity: {e}")
return [0.5] * len(questions) # Return neutral scores in case of error
def calculate_semantic_relevance(context: str, answer: str, questions: List[str]) -> List[float]:
try:
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are an expert in semantic analysis, specializing in evaluating the relevance of questions to a given context and answer."},
{"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)}"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "semantic_relevance_analyzer",
"strict": True,
"schema": {
"type": "object",
"properties": {
"relevance_scores": {
"type": "array",
"items": {
"type": "number",
}
},
"explanation": {"type": "string"}
},
"required": ["relevance_scores", "explanation"],
"additionalProperties": False
}
}
}
)
json_response = response.choices[0].message.content
logger.info(f"Raw JSON response: {json_response}")
parsed_response = json.loads(json_response)
relevance_scores = parsed_response["relevance_scores"]
explanation = parsed_response["explanation"]
logger.info(f"Semantic Relevance Explanation: {explanation}")
return relevance_scores
except Exception as e:
logger.error(f"Error in calculate_semantic_relevance: {e}")
return [0.5] * len(questions) # Return neutral scores in case of error
def check_answer_precision(context: str, questions: List[str], original_answer: str) -> Tuple[List[float], List[str]]:
precision_scores = []
generated_answers = []
for question in questions:
generated_answer = generate_answer(context, question)
generated_answers.append(generated_answer)
# Use OpenAI to evaluate answer precision
try:
response = client.chat.completions.create(
model="gpt-4o-2024-08-06",
messages=[
{"role": "system", "content": "You are an expert in evaluating answer precision."},
{"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:\n\nOriginal Answer: {original_answer}\nGenerated Answer: {generated_answer}"}
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "answer_precision_evaluator",
"strict": True,
"schema": {
"type": "object",
"properties": {
"precision_score": {
"type": "number",
}
},
"required": ["precision_score"],
"additionalProperties": False
}
}
}
)
json_response = response.choices[0].message.content
parsed_response = json.loads(json_response)
precision_score = parsed_response["precision_score"]
precision_scores.append(precision_score)
except Exception as e:
logger.error(f"Error in evaluating answer precision: {e}")
precision_scores.append(0.5) # Neutral score in case of error
return precision_scores, generated_answers
def calculate_composite_scores(sd_scores: List[float], sr_scores: List[float], ap_scores: List[float]) -> List[float]:
return [0.3 * sd + 0.3 * sr + 0.4 * ap for sd, sr, ap in zip(sd_scores, sr_scores, ap_scores)]
def rank_questions_with_details(context: str, answer: str) -> Tuple[pd.DataFrame, List[pd.DataFrame], str]:
questions = generate_questions(context, answer)
sd_scores = calculate_structural_diversity(questions)
sr_scores = calculate_semantic_relevance(context, answer, questions)
ap_scores, generated_answers = check_answer_precision(context, questions, answer)
composite_scores = calculate_composite_scores(sd_scores, sr_scores, ap_scores)
# Create detailed scores dataframe
detailed_scores = pd.DataFrame({
'Question': questions,
'Answer Precision': ap_scores,
'Composite Score': composite_scores,
'Structural Diversity': sd_scores,
'Semantic Relevance': sr_scores,
'Generated Answer': generated_answers
})
detailed_scores = detailed_scores.sort_values('Composite Score', ascending=False).reset_index(drop=True)
# Create separate ranking dataframes for each metric
metrics = ['Answer Precision', 'Composite Score', 'Structural Diversity', 'Semantic Relevance']
rankings = []
for metric in metrics:
df = pd.DataFrame({
'Rank': range(1, 6),
'Question': [questions[i] for i in np.argsort(detailed_scores[metric])[::-1]],
f'{metric}': sorted(detailed_scores[metric], reverse=True)
})
if metric == 'Answer Precision':
df['Generated Answer'] = [generated_answers[i] for i in np.argsort(detailed_scores[metric])[::-1]]
rankings.append(df)
best_question = detailed_scores.iloc[0]['Question']
return detailed_scores, rankings, best_question
def gradio_interface(context: str, answer: str) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, str]:
detailed_scores, rankings, best_question = rank_questions_with_details(context, answer)
return (
detailed_scores,
rankings[0], # Answer Precision Ranking
rankings[1], # Composite Score Ranking
rankings[2], # Structural Diversity Ranking
rankings[3], # Semantic Relevance Ranking
f"Best Question: {best_question}"
)
def use_sample(sample_index: int) -> Tuple[str, str]:
return samples[sample_index]["context"], samples[sample_index]["answer"]
def get_random_entry():
random_index = random.randint(0, len(dataset['train']) - 1)
entry = dataset['train'][random_index]
return entry['context'], entry['answer'], entry['question']
# Create Gradio interface
with gr.Blocks(theme=gr.themes.Default()) as iface:
gr.Markdown("# Question Generator and Ranker")
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.")
with gr.Row():
with gr.Column(scale=1):
context_input = gr.Textbox(lines=5, label="Context")
answer_input = gr.Textbox(lines=2, label="Answer")
submit_button = gr.Button("Generate Questions")
with gr.Row():
sample_buttons = [gr.Button(f"Sample {i+1}") for i in range(3)]
random_button = gr.Button("Random Dataset Entry")
with gr.Column(scale=2):
original_question_output = gr.Dataframe(label="Original Question from Dataset", visible=False)
best_question_output = gr.Textbox(label="Best Generated Question")
detailed_scores_output = gr.DataFrame(label="Detailed Scores")
with gr.Row():
with gr.Column():
answer_precision_ranking_output = gr.DataFrame(label="Answer Precision Ranking")
with gr.Column():
composite_ranking_output = gr.DataFrame(label="Composite Score Ranking")
with gr.Row():
with gr.Column():
structural_diversity_ranking_output = gr.DataFrame(label="Structural Diversity Ranking")
with gr.Column():
semantic_relevance_ranking_output = gr.DataFrame(label="Semantic Relevance Ranking")
def process_random_entry():
context, answer, original_question = get_random_entry()
return (
context,
answer,
pd.DataFrame({'Original Question': [original_question]}),
gr.update(visible=True)
)
submit_button.click(
fn=gradio_interface,
inputs=[context_input, answer_input],
outputs=[
detailed_scores_output,
answer_precision_ranking_output,
composite_ranking_output,
structural_diversity_ranking_output,
semantic_relevance_ranking_output,
best_question_output
]
)
# Set up sample button functionality
for i, button in enumerate(sample_buttons):
button.click(
fn=lambda i=i: use_sample(i),
outputs=[context_input, answer_input]
)
# Set up random button functionality
random_button.click(
fn=process_random_entry,
outputs=[
context_input,
answer_input,
original_question_output,
original_question_output
]
)
# Launch the app
if __name__ == "__main__":
iface.launch() |