Serhan Yılmaz commited on
Commit
c1fa8ac
·
1 Parent(s): e2fcdb3

Add application file

Browse files
Files changed (2) hide show
  1. app.py +215 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cohere
2
+ import numpy as np
3
+ from sentence_transformers import SentenceTransformer
4
+ from transformers import pipeline
5
+ from typing import List, Tuple
6
+ import os
7
+ from dotenv import load_dotenv
8
+ import logging
9
+ import json
10
+ import gradio as gr
11
+ import pandas as pd
12
+
13
+ # Set up logging
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
+
17
+ load_dotenv() # This loads the variables from .env
18
+
19
+ # Initialize Cohere client, SentenceTransformer model, and QA pipeline
20
+ co = cohere.Client(api_key = os.environ.get("COHERE_API_KEY"))
21
+ sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
22
+ qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
23
+
24
+ def generate_questions(context: str, answer: str) -> List[str]:
25
+ try:
26
+ response = co.chat(
27
+ model="command-r",
28
+ message=f"Based on this context: '{context}' and answer: '{answer}', generate 5 diverse questions which when asked to the context returns the answer.",
29
+ response_format={
30
+ "type": "json_object",
31
+ "schema": {
32
+ "type": "object",
33
+ "required": ["question1", "question2", "question3", "question4", "question5"],
34
+ "properties": {
35
+ "question1": {"type": "string"},
36
+ "question2": {"type": "string"},
37
+ "question3": {"type": "string"},
38
+ "question4": {"type": "string"},
39
+ "question5": {"type": "string"}
40
+ }
41
+ }
42
+ }
43
+ )
44
+
45
+ json_response = response.text
46
+ logger.info(f"Raw JSON response: {json_response}")
47
+
48
+ parsed_response = json.loads(json_response)
49
+ questions = [parsed_response[f"question{i}"] for i in range(1, 6)]
50
+ return questions
51
+ except Exception as e:
52
+ logger.error(f"Error in generate_questions: {e}")
53
+ return [f"Failed to generate question {i}" for i in range(1, 6)]
54
+
55
+ def calculate_structural_diversity(questions: List[str]) -> List[float]:
56
+ def get_question_type(q):
57
+ q = q.lower()
58
+ if q.startswith('what'): return 1
59
+ elif q.startswith('why'): return 2
60
+ elif q.startswith('how'): return 3
61
+ elif q.startswith('when'): return 4
62
+ elif q.startswith('where'): return 5
63
+ else: return 0
64
+
65
+ lengths = [len(q.split()) for q in questions]
66
+ types = [get_question_type(q) for q in questions]
67
+
68
+ length_scores = [1 - (abs(l - np.mean(lengths)) / np.max(lengths)) for l in lengths]
69
+ type_scores = [len(set(types)) / len(types) for _ in types]
70
+
71
+ return [(l + t) / 2 for l, t in zip(length_scores, type_scores)]
72
+
73
+ def calculate_semantic_relevance(context: str, answer: str, questions: List[str]) -> List[float]:
74
+ context_embedding = sentence_model.encode(context + " " + answer)
75
+ question_embeddings = sentence_model.encode(questions)
76
+
77
+ similarities = [np.dot(context_embedding, q_emb) / (np.linalg.norm(context_embedding) * np.linalg.norm(q_emb))
78
+ for q_emb in question_embeddings]
79
+
80
+ return [(sim + 1) / 2 for sim in similarities] # Normalize to 0-1 range
81
+
82
+ def check_answer_precision(context: str, questions: List[str], original_answer: str) -> Tuple[List[float], List[str]]:
83
+ precision_scores = []
84
+ generated_answers = []
85
+ for question in questions:
86
+ result = qa_pipeline(question=question, context=context)
87
+ generated_answer = result['answer']
88
+ generated_answers.append(generated_answer)
89
+ answer_embedding = sentence_model.encode(original_answer)
90
+ generated_embedding = sentence_model.encode(generated_answer)
91
+ similarity = np.dot(answer_embedding, generated_embedding) / (np.linalg.norm(answer_embedding) * np.linalg.norm(generated_embedding))
92
+ precision_scores.append((similarity + 1) / 2) # Normalize to 0-1 range
93
+ return precision_scores, generated_answers
94
+
95
+ def calculate_composite_scores(sd_scores: List[float], sr_scores: List[float], ap_scores: List[float]) -> List[float]:
96
+ return [0.2 * sd + 0.4 * sr + 0.4 * ap for sd, sr, ap in zip(sd_scores, sr_scores, ap_scores)]
97
+
98
+ def rank_questions_with_details(context: str, answer: str) -> Tuple[pd.DataFrame, List[pd.DataFrame], str]:
99
+ questions = generate_questions(context, answer)
100
+
101
+ sd_scores = calculate_structural_diversity(questions)
102
+ sr_scores = calculate_semantic_relevance(context, answer, questions)
103
+ ap_scores, generated_answers = check_answer_precision(context, questions, answer)
104
+
105
+ composite_scores = calculate_composite_scores(sd_scores, sr_scores, ap_scores)
106
+
107
+ # Create detailed scores dataframe
108
+ detailed_scores = pd.DataFrame({
109
+ 'Question': questions,
110
+ 'Composite Score': composite_scores,
111
+ 'Structural Diversity': sd_scores,
112
+ 'Semantic Relevance': sr_scores,
113
+ 'Answer Precision': ap_scores,
114
+ 'Generated Answer': generated_answers
115
+ })
116
+ detailed_scores = detailed_scores.sort_values('Composite Score', ascending=False).reset_index(drop=True)
117
+
118
+ # Create separate ranking dataframes for each metric
119
+ metrics = ['Composite Score', 'Structural Diversity', 'Semantic Relevance', 'Answer Precision']
120
+ rankings = []
121
+
122
+ for metric in metrics:
123
+ df = pd.DataFrame({
124
+ 'Rank': range(1, 6),
125
+ 'Question': [questions[i] for i in np.argsort(detailed_scores[metric])[::-1]],
126
+ f'{metric}': sorted(detailed_scores[metric], reverse=True)
127
+ })
128
+ rankings.append(df)
129
+
130
+ best_question = detailed_scores.iloc[0]['Question']
131
+
132
+ return detailed_scores, rankings, best_question
133
+
134
+ # Define sample inputs
135
+ samples = [
136
+ {
137
+ "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.",
138
+ "answer": "Switzerland"
139
+ },
140
+ {
141
+ "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.",
142
+ "answer": "Paris"
143
+ },
144
+ {
145
+ "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).",
146
+ "answer": "China"
147
+ }
148
+ ]
149
+
150
+ def gradio_interface(context: str, answer: str) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame, str]:
151
+ detailed_scores, rankings, best_question = rank_questions_with_details(context, answer)
152
+ return (
153
+ detailed_scores,
154
+ rankings[0], # Composite Score Ranking
155
+ rankings[1], # Structural Diversity Ranking
156
+ rankings[2], # Semantic Relevance Ranking
157
+ rankings[3], # Answer Precision Ranking
158
+ f"Best Question: {best_question}"
159
+ )
160
+
161
+ def use_sample(sample_index: int) -> Tuple[str, str]:
162
+ return samples[sample_index]["context"], samples[sample_index]["answer"]
163
+
164
+ # Create Gradio interface with improved layout and sample buttons
165
+ with gr.Blocks(theme=gr.themes.Default()) as iface:
166
+ gr.Markdown("# Question Generator and Ranker")
167
+ gr.Markdown("Enter a context and an answer to generate and rank questions, or use one of the sample inputs.")
168
+
169
+ with gr.Row():
170
+ with gr.Column(scale=1):
171
+ context_input = gr.Textbox(lines=5, label="Context")
172
+ answer_input = gr.Textbox(lines=2, label="Answer")
173
+ submit_button = gr.Button("Generate Questions")
174
+
175
+ with gr.Row():
176
+ sample_buttons = [gr.Button(f"Sample {i+1}") for i in range(3)]
177
+
178
+ with gr.Column(scale=2):
179
+ best_question_output = gr.Textbox(label="Best Question")
180
+ detailed_scores_output = gr.DataFrame(label="Detailed Scores")
181
+
182
+ with gr.Row():
183
+ with gr.Column():
184
+ composite_ranking_output = gr.DataFrame(label="Composite Score Ranking")
185
+ with gr.Column():
186
+ structural_diversity_ranking_output = gr.DataFrame(label="Structural Diversity Ranking")
187
+
188
+ with gr.Row():
189
+ with gr.Column():
190
+ semantic_relevance_ranking_output = gr.DataFrame(label="Semantic Relevance Ranking")
191
+ with gr.Column():
192
+ answer_precision_ranking_output = gr.DataFrame(label="Answer Precision Ranking")
193
+
194
+ submit_button.click(
195
+ fn=gradio_interface,
196
+ inputs=[context_input, answer_input],
197
+ outputs=[
198
+ detailed_scores_output,
199
+ composite_ranking_output,
200
+ structural_diversity_ranking_output,
201
+ semantic_relevance_ranking_output,
202
+ answer_precision_ranking_output,
203
+ best_question_output
204
+ ]
205
+ )
206
+
207
+ # Set up sample button functionality
208
+ for i, button in enumerate(sample_buttons):
209
+ button.click(
210
+ fn=lambda i=i: use_sample(i),
211
+ outputs=[context_input, answer_input]
212
+ )
213
+
214
+
215
+ iface.launch()
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ gradio
2
+ cohere
3
+ numpy
4
+ sentence-transformers
5
+ transformers
6
+ python-dotenv
7
+ pandas