Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -2,7 +2,7 @@ import os
|
|
2 |
import json
|
3 |
import numpy as np
|
4 |
from datasets import load_dataset
|
5 |
-
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
|
6 |
import torch
|
7 |
from sklearn.metrics import f1_score
|
8 |
import re
|
@@ -12,311 +12,143 @@ from huggingface_hub import login
|
|
12 |
import gradio as gr
|
13 |
import pandas as pd
|
14 |
from datetime import datetime
|
|
|
15 |
|
|
|
16 |
def normalize_answer(s):
|
17 |
-
"""Normalize answer for evaluation"""
|
18 |
def remove_articles(text):
|
19 |
return re.sub(r'\b(a|an|the)\b', ' ', text)
|
20 |
-
|
21 |
def white_space_fix(text):
|
22 |
return ' '.join(text.split())
|
23 |
-
|
24 |
def remove_punc(text):
|
25 |
exclude = set(string.punctuation)
|
26 |
return ''.join(ch for ch in text if ch not in exclude)
|
27 |
-
|
28 |
def lower(text):
|
29 |
return text.lower()
|
30 |
-
|
31 |
return white_space_fix(remove_articles(remove_punc(lower(s))))
|
32 |
|
33 |
def f1_score_qa(prediction, ground_truth):
|
34 |
-
"""Calculate F1 score for QA"""
|
35 |
prediction_tokens = normalize_answer(prediction).split()
|
36 |
ground_truth_tokens = normalize_answer(ground_truth).split()
|
37 |
-
|
38 |
-
if len(prediction_tokens) == 0 or len(ground_truth_tokens) == 0:
|
39 |
-
return int(prediction_tokens == ground_truth_tokens)
|
40 |
-
|
41 |
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
|
42 |
num_same = sum(common.values())
|
43 |
-
|
44 |
if num_same == 0:
|
45 |
return 0
|
46 |
-
|
47 |
precision = 1.0 * num_same / len(prediction_tokens)
|
48 |
recall = 1.0 * num_same / len(ground_truth_tokens)
|
49 |
-
|
50 |
-
return f1
|
51 |
|
52 |
def exact_match_score(prediction, ground_truth):
|
53 |
-
"""Calculate exact match score"""
|
54 |
return normalize_answer(prediction) == normalize_answer(ground_truth)
|
55 |
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
print("Loading model and tokenizer...")
|
69 |
-
model_name = "AvocadoMuffin/roberta-cuad-qa-v2"
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
model =
|
74 |
-
qa_pipeline = pipeline("question-answering", model=model, tokenizer=tokenizer)
|
75 |
-
print("✓ Model loaded successfully")
|
76 |
-
return qa_pipeline, hf_token
|
77 |
-
except Exception as e:
|
78 |
-
print(f"✗ Error loading model: {e}")
|
79 |
-
return None, None
|
80 |
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
progress(0.1, desc="Loading CUAD dataset...")
|
90 |
-
|
91 |
-
# Load dataset - use QA format version (JSON, no PDFs)
|
92 |
-
try:
|
93 |
-
# Try the QA-specific version first (much faster, JSON format)
|
94 |
-
dataset = load_dataset("theatticusproject/cuad-qa", trust_remote_code=True, token=hf_token)
|
95 |
-
test_data = dataset["test"]
|
96 |
-
print(f"✓ Loaded CUAD-QA dataset with {len(test_data)} samples")
|
97 |
-
except Exception as e:
|
98 |
-
try:
|
99 |
-
# Fallback to original but limit to avoid PDF downloads
|
100 |
-
dataset = load_dataset("cuad", split="test[:1000]", trust_remote_code=True, token=hf_token)
|
101 |
-
test_data = dataset
|
102 |
-
print(f"✓ Loaded CUAD dataset with {len(test_data)} samples")
|
103 |
-
except Exception as e2:
|
104 |
-
return f"❌ Error loading dataset: {e2}", pd.DataFrame(), None
|
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 |
-
exact_matches.append(em)
|
141 |
-
f1_scores.append(f1)
|
142 |
-
|
143 |
-
predictions.append({
|
144 |
-
"Sample_ID": i+1,
|
145 |
-
"Question": question[:100] + "..." if len(question) > 100 else question,
|
146 |
-
"Predicted_Answer": predicted_answer,
|
147 |
-
"Ground_Truth": ground_truth,
|
148 |
-
"Exact_Match": em,
|
149 |
-
"F1_Score": round(f1, 3),
|
150 |
-
"Confidence": round(result["score"], 3)
|
151 |
-
})
|
152 |
-
|
153 |
-
except Exception as e:
|
154 |
-
print(f"Error processing sample {i}: {e}")
|
155 |
-
continue
|
156 |
-
|
157 |
-
progress(0.9, desc="Calculating final metrics...")
|
158 |
|
159 |
-
#
|
160 |
-
|
161 |
-
|
162 |
|
163 |
-
|
164 |
-
|
|
|
|
|
|
|
|
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
## 🎯 Overall Performance
|
170 |
-
- **Model**: AvocadoMuffin/roberta-cuad-qa-v3
|
171 |
-
- **Dataset**: CUAD (Contract Understanding Atticus Dataset)
|
172 |
-
- **Samples Evaluated**: {len(exact_matches)}
|
173 |
-
- **Evaluation Date**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
174 |
-
## 📈 Metrics
|
175 |
-
- **Exact Match Score**: {avg_exact_match:.2f}%
|
176 |
-
- **F1 Score**: {avg_f1_score:.2f}%
|
177 |
-
## 🔍 Performance Analysis
|
178 |
-
- **High Confidence Predictions**: {len([p for p in predictions if p['Confidence'] > 0.8])} ({len([p for p in predictions if p['Confidence'] > 0.8])/len(predictions)*100:.1f}%)
|
179 |
-
- **Perfect Matches**: {len([p for p in predictions if p['Exact_Match'] == 1])} ({len([p for p in predictions if p['Exact_Match'] == 1])/len(predictions)*100:.1f}%)
|
180 |
-
- **High F1 Scores (>0.8)**: {len([p for p in predictions if p['F1_Score'] > 0.8])} ({len([p for p in predictions if p['F1_Score'] > 0.8])/len(predictions)*100:.1f}%)
|
181 |
-
"""
|
182 |
|
183 |
-
|
184 |
-
df
|
|
|
185 |
|
186 |
-
# Save results
|
187 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
188 |
-
results_file = f"
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
try:
|
201 |
-
with open(results_file, "w") as f:
|
202 |
-
json.dump(detailed_results, f, indent=2)
|
203 |
-
print(f"✓ Results saved to {results_file}")
|
204 |
-
except Exception as e:
|
205 |
-
print(f"⚠ Warning: Could not save results file: {e}")
|
206 |
-
results_file = None
|
207 |
-
|
208 |
-
progress(1.0, desc="✅ Evaluation completed!")
|
209 |
-
|
210 |
-
return results_summary, df, results_file
|
211 |
|
212 |
-
def create_gradio_interface():
|
213 |
-
"""Create Gradio interface for CUAD evaluation"""
|
214 |
-
|
215 |
-
with gr.Blocks(title="CUAD Model Evaluator", theme=gr.themes.Soft()) as demo:
|
216 |
-
gr.HTML("""
|
217 |
-
<div style="text-align: center; padding: 20px;">
|
218 |
-
<h1>🏛️ CUAD Model Evaluation Dashboard</h1>
|
219 |
-
<p>Evaluate your CUAD (Contract Understanding Atticus Dataset) Question Answering model</p>
|
220 |
-
<p><strong>Model:</strong> AvocadoMuffin/roberta-cuad-qa-v2</p>
|
221 |
-
</div>
|
222 |
-
""")
|
223 |
-
|
224 |
-
with gr.Row():
|
225 |
-
with gr.Column(scale=1):
|
226 |
-
gr.HTML("<h3>⚙️ Evaluation Settings</h3>")
|
227 |
-
|
228 |
-
num_samples = gr.Slider(
|
229 |
-
minimum=10,
|
230 |
-
maximum=500,
|
231 |
-
value=100,
|
232 |
-
step=10,
|
233 |
-
label="Number of samples to evaluate",
|
234 |
-
info="Choose between 10-500 samples (more samples = more accurate but slower)"
|
235 |
-
)
|
236 |
-
|
237 |
-
evaluate_btn = gr.Button(
|
238 |
-
"🚀 Start Evaluation",
|
239 |
-
variant="primary",
|
240 |
-
size="lg"
|
241 |
-
)
|
242 |
-
|
243 |
-
gr.HTML("""
|
244 |
-
<div style="margin-top: 20px; padding: 15px; background-color: #f0f0f0; border-radius: 8px;">
|
245 |
-
<h4>📋 What this evaluates:</h4>
|
246 |
-
<ul>
|
247 |
-
<li><strong>Exact Match</strong>: Percentage of perfect predictions</li>
|
248 |
-
<li><strong>F1 Score</strong>: Token-level overlap between prediction and ground truth</li>
|
249 |
-
<li><strong>Confidence</strong>: Model's confidence in its predictions</li>
|
250 |
-
</ul>
|
251 |
-
</div>
|
252 |
-
""")
|
253 |
-
|
254 |
-
with gr.Column(scale=2):
|
255 |
-
gr.HTML("<h3>📊 Results</h3>")
|
256 |
-
|
257 |
-
results_summary = gr.Markdown(
|
258 |
-
value="Click '🚀 Start Evaluation' to begin...",
|
259 |
-
label="Evaluation Summary"
|
260 |
-
)
|
261 |
-
|
262 |
-
gr.HTML("<hr>")
|
263 |
-
|
264 |
-
with gr.Row():
|
265 |
-
gr.HTML("<h3>📋 Detailed Results</h3>")
|
266 |
-
|
267 |
-
with gr.Row():
|
268 |
-
detailed_results = gr.Dataframe(
|
269 |
-
label="Sample-by-Sample Results",
|
270 |
-
interactive=False,
|
271 |
-
wrap=True
|
272 |
-
)
|
273 |
-
|
274 |
-
with gr.Row():
|
275 |
-
download_file = gr.File(
|
276 |
-
label="📥 Download Complete Results (JSON)",
|
277 |
-
visible=False
|
278 |
-
)
|
279 |
-
|
280 |
-
# Event handlers
|
281 |
-
def handle_evaluation(num_samples):
|
282 |
-
summary, df, file_path = run_evaluation(num_samples)
|
283 |
-
if file_path and os.path.exists(file_path):
|
284 |
-
return summary, df, gr.update(visible=True, value=file_path)
|
285 |
-
else:
|
286 |
-
return summary, df, gr.update(visible=False)
|
287 |
-
|
288 |
-
evaluate_btn.click(
|
289 |
-
fn=handle_evaluation,
|
290 |
-
inputs=[num_samples],
|
291 |
-
outputs=[results_summary, detailed_results, download_file],
|
292 |
-
show_progress=True
|
293 |
-
)
|
294 |
-
|
295 |
-
# Footer
|
296 |
-
gr.HTML("""
|
297 |
-
<div style="text-align: center; margin-top: 30px; padding: 20px; color: #666;">
|
298 |
-
<p>�� Powered by Hugging Face Transformers & Gradio</p>
|
299 |
-
<p>📚 CUAD Dataset by The Atticus Project</p>
|
300 |
-
</div>
|
301 |
-
""")
|
302 |
-
|
303 |
-
return demo
|
304 |
-
|
305 |
if __name__ == "__main__":
|
306 |
-
|
307 |
-
print(
|
308 |
-
|
309 |
-
|
310 |
-
if torch.cuda.is_available():
|
311 |
-
print(f"✓ CUDA available: {torch.cuda.get_device_name(0)}")
|
312 |
-
else:
|
313 |
-
print("! Running on CPU")
|
314 |
-
|
315 |
-
# Create and launch Gradio interface
|
316 |
-
demo = create_gradio_interface()
|
317 |
-
demo.launch(
|
318 |
-
server_name="0.0.0.0",
|
319 |
-
server_port=7860,
|
320 |
-
share=True,
|
321 |
-
debug=True
|
322 |
-
)
|
|
|
2 |
import json
|
3 |
import numpy as np
|
4 |
from datasets import load_dataset
|
5 |
+
from transformers import AutoTokenizer, AutoModelForQuestionAnswering
|
6 |
import torch
|
7 |
from sklearn.metrics import f1_score
|
8 |
import re
|
|
|
12 |
import gradio as gr
|
13 |
import pandas as pd
|
14 |
from datetime import datetime
|
15 |
+
import matplotlib.pyplot as plt
|
16 |
|
17 |
+
# Normalization functions (same as extractor)
|
18 |
def normalize_answer(s):
|
|
|
19 |
def remove_articles(text):
|
20 |
return re.sub(r'\b(a|an|the)\b', ' ', text)
|
|
|
21 |
def white_space_fix(text):
|
22 |
return ' '.join(text.split())
|
|
|
23 |
def remove_punc(text):
|
24 |
exclude = set(string.punctuation)
|
25 |
return ''.join(ch for ch in text if ch not in exclude)
|
|
|
26 |
def lower(text):
|
27 |
return text.lower()
|
|
|
28 |
return white_space_fix(remove_articles(remove_punc(lower(s))))
|
29 |
|
30 |
def f1_score_qa(prediction, ground_truth):
|
|
|
31 |
prediction_tokens = normalize_answer(prediction).split()
|
32 |
ground_truth_tokens = normalize_answer(ground_truth).split()
|
|
|
|
|
|
|
|
|
33 |
common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
|
34 |
num_same = sum(common.values())
|
|
|
35 |
if num_same == 0:
|
36 |
return 0
|
|
|
37 |
precision = 1.0 * num_same / len(prediction_tokens)
|
38 |
recall = 1.0 * num_same / len(ground_truth_tokens)
|
39 |
+
return (2 * precision * recall) / (precision + recall)
|
|
|
40 |
|
41 |
def exact_match_score(prediction, ground_truth):
|
|
|
42 |
return normalize_answer(prediction) == normalize_answer(ground_truth)
|
43 |
|
44 |
+
# Identical confidence calculation to extractor
|
45 |
+
def calculate_confidence(model, tokenizer, question, context):
|
46 |
+
inputs = tokenizer(
|
47 |
+
question,
|
48 |
+
context,
|
49 |
+
return_tensors="pt",
|
50 |
+
truncation=True,
|
51 |
+
max_length=512,
|
52 |
+
stride=128,
|
53 |
+
padding=True
|
54 |
+
)
|
|
|
|
|
|
|
55 |
|
56 |
+
if torch.cuda.is_available():
|
57 |
+
inputs = {k: v.cuda() for k, v in inputs.items()}
|
58 |
+
model = model.cuda()
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
+
with torch.no_grad():
|
61 |
+
outputs = model(**inputs)
|
62 |
+
|
63 |
+
start_probs = torch.softmax(outputs.start_logits, dim=1)
|
64 |
+
end_probs = torch.softmax(outputs.end_logits, dim=1)
|
65 |
+
answer_start = torch.argmax(outputs.start_logits)
|
66 |
+
answer_end = torch.argmax(outputs.end_logits) + 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
start_prob = start_probs[0, answer_start].item()
|
69 |
+
end_prob = end_probs[0, answer_end-1].item()
|
70 |
+
confidence = np.sqrt(start_prob * end_prob)
|
71 |
|
72 |
+
answer_tokens = inputs["input_ids"][0][answer_start:answer_end]
|
73 |
+
answer = tokenizer.decode(answer_tokens, skip_special_tokens=True).strip()
|
74 |
|
75 |
+
return answer, float(confidence)
|
76 |
+
|
77 |
+
def run_evaluation(num_samples=100):
|
78 |
+
# Authenticate
|
79 |
+
if token := os.getenv("HF_TOKEN"):
|
80 |
+
login(token=token)
|
81 |
|
82 |
+
# Load model same as extractor
|
83 |
+
model_name = "AvocadoMuffin/roberta-cuad-qa-v2"
|
84 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
85 |
+
model = AutoModelForQuestionAnswering.from_pretrained(model_name)
|
86 |
+
|
87 |
+
# Load CUAD dataset
|
88 |
+
dataset = load_dataset("theatticusproject/cuad-qa", token=token)
|
89 |
+
test_data = dataset["test"].select(range(min(num_samples, len(dataset["test"]))))
|
90 |
+
|
91 |
+
results = []
|
92 |
+
for example in test_data:
|
93 |
+
context = example["context"]
|
94 |
+
question = example["question"]
|
95 |
+
gt_answer = example["answers"]["text"][0] if example["answers"]["text"] else ""
|
96 |
|
97 |
+
pred_answer, confidence = calculate_confidence(model, tokenizer, question, context)
|
98 |
+
|
99 |
+
results.append({
|
100 |
+
"question": question,
|
101 |
+
"prediction": pred_answer,
|
102 |
+
"ground_truth": gt_answer,
|
103 |
+
"confidence": confidence,
|
104 |
+
"exact_match": exact_match_score(pred_answer, gt_answer),
|
105 |
+
"f1": f1_score_qa(pred_answer, gt_answer)
|
106 |
+
})
|
107 |
+
|
108 |
+
# Generate report
|
109 |
+
df = pd.DataFrame(results)
|
110 |
+
avg_metrics = {
|
111 |
+
"exact_match": df["exact_match"].mean() * 100,
|
112 |
+
"f1": df["f1"].mean() * 100,
|
113 |
+
"confidence": df["confidence"].mean() * 100
|
114 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
115 |
|
116 |
+
# Confidence calibration analysis
|
117 |
+
high_conf_correct = df[(df["confidence"] > 0.8) & (df["exact_match"] == 1)].shape[0]
|
118 |
+
high_conf_total = df[df["confidence"] > 0.8].shape[0]
|
119 |
|
120 |
+
report = f"""
|
121 |
+
CUAD Evaluation Report (n={len(df)})
|
122 |
+
========================
|
123 |
+
Accuracy:
|
124 |
+
- Exact Match: {avg_metrics['exact_match']:.2f}%
|
125 |
+
- F1 Score: {avg_metrics['f1']:.2f}%
|
126 |
|
127 |
+
Confidence Analysis:
|
128 |
+
- Avg Confidence: {avg_metrics['confidence']:.2f}%
|
129 |
+
- High-Confidence (>80%) Accuracy: {high_conf_correct}/{high_conf_total} ({high_conf_correct/max(1,high_conf_total)*100:.1f}%)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
|
131 |
+
Confidence vs Accuracy:
|
132 |
+
{df[['confidence', 'exact_match']].corr().iloc[0,1]:.3f} correlation
|
133 |
+
"""
|
134 |
|
135 |
+
# Save results
|
136 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
137 |
+
results_file = f"cuad_eval_{timestamp}.json"
|
138 |
+
with open(results_file, "w") as f:
|
139 |
+
json.dump({
|
140 |
+
"metrics": avg_metrics,
|
141 |
+
"samples": results,
|
142 |
+
"config": {
|
143 |
+
"model": model_name,
|
144 |
+
"confidence_method": "geometric_mean_start_end_probs"
|
145 |
+
}
|
146 |
+
}, f, indent=2)
|
147 |
+
|
148 |
+
return report, df, results_file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
if __name__ == "__main__":
|
151 |
+
report, df, _ = run_evaluation()
|
152 |
+
print(report)
|
153 |
+
print("\nSample predictions:")
|
154 |
+
print(df.head())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|