Add files using upload-large-folder tool
Browse files- code/evaluation_code/level1/evaluation_FED.py +174 -0
- code/evaluation_code/level1/evaluation_ISA.py +211 -0
- code/evaluation_code/level1/evaluation_MER.py +206 -0
- code/evaluation_code/level1/evaluation_MESA.py +215 -0
- code/evaluation_code/level1/evaluation_MSA.py +200 -0
- code/evaluation_code/level1/evaluation_OSA.py +200 -0
- code/evaluation_code/level1/evaluation_SCEA.py +193 -0
- code/evaluation_code/level1/evaluation_SIA.py +218 -0
- code/evaluation_code/level1/evaluation_SOER.py +199 -0
- code/evaluation_code/level1/evaluation_SPER.py +195 -0
- code/evaluation_code/level2/evaluation_DPTM.py +263 -0
- code/evaluation_code/level2/evaluation_EBIA.py +325 -0
- code/evaluation_code/level2/evaluation_HU.py +228 -0
- code/evaluation_code/level2/evaluation_IAVE.py +316 -0
- code/evaluation_code/level2/evaluation_MABSA.py +341 -0
- code/evaluation_code/level2/evaluation_MDER.py +257 -0
- code/evaluation_code/level2/evaluation_MQE.py +369 -0
- code/evaluation_code/level2/evaluation_MSD.py +301 -0
- code/evaluation_code/level3/evaluation_EER.py +262 -0
- code/evaluation_code/level3/evaluation_EI.py +269 -0
- code/evaluation_code/level3/evaluation_LR.py +226 -0
- code/evaluation_code/level3/evaluation_MECPE.py +304 -0
- code/evaluation_code/level3/evaluation_SD.py +264 -0
- code/evaluation_code/level3/evaluation_SFA.py +411 -0
- code/test_code/test_affectgpt.py +285 -0
- code/test_code/test_emotionllama.py +364 -0
- code/test_code/test_gemini_2.5_flash.py +227 -0
- code/test_code/test_gemini_2.5_pro.py +211 -0
- code/test_code/test_gpt41.py +230 -0
- code/test_code/test_gpt4o.py +246 -0
- code/test_code/test_humanomni.py +241 -0
- code/test_code/test_internvl.py +253 -0
- code/test_code/test_llavanext.py +158 -0
- code/test_code/test_llavaonevison.py +126 -0
- code/test_code/test_minicpm.py +123 -0
- code/test_code/test_qwen25_omni.py +177 -0
- code/test_code/test_qwenvl.py +183 -0
- code/test_code/test_r1omni.py +232 -0
- code/test_code/test_videollama3.py +144 -0
- code/train_code/train_gemini.py +412 -0
- code/train_code/train_gpt4o.py +108 -0
- code/train_code/train_gpt5.py +196 -0
- data/with_prompt/level3/FilmStim.json +0 -0
- data/with_prompt/level3/MUStARD.json +0 -0
- data/without_prompt/level1/CMU-MOSI.json +0 -0
- data/without_prompt/level1/EmoSet.json +0 -0
- data/without_prompt/level1/FMSA-SC.json +0 -0
- data/without_prompt/level1/MER2023.json +0 -0
- data/without_prompt/level1/Memotion.json +0 -0
- data/without_prompt/level1/RAVDSS_song.json +0 -0
code/evaluation_code/level1/evaluation_FED.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
patterns = [
|
| 21 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 22 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 23 |
+
r"\b(positive|negative|neutral)\b",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
for pattern in patterns:
|
| 27 |
+
match = re.search(pattern, model_output.lower())
|
| 28 |
+
if match:
|
| 29 |
+
emotion = match.group(1).lower()
|
| 30 |
+
if emotion in ["positive", "negative", "neutral"]:
|
| 31 |
+
return emotion, True, None
|
| 32 |
+
|
| 33 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 34 |
+
return None, False, "invalid_emotion_label"
|
| 35 |
+
elif any(
|
| 36 |
+
word in model_output.lower() for word in ["positive", "negative", "neutral"]
|
| 37 |
+
):
|
| 38 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 39 |
+
else:
|
| 40 |
+
return None, False, "no_emotion_pattern"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def evaluate_face_expression_emotion_detection(result_file_path):
|
| 44 |
+
|
| 45 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 46 |
+
results = json.load(f)
|
| 47 |
+
|
| 48 |
+
predictions = []
|
| 49 |
+
ground_truths = []
|
| 50 |
+
detailed_results = []
|
| 51 |
+
extraction_errors = defaultdict(list)
|
| 52 |
+
prediction_errors = defaultdict(list)
|
| 53 |
+
|
| 54 |
+
for item in results:
|
| 55 |
+
item_id = item["id"]
|
| 56 |
+
model_output = item["model_output"]
|
| 57 |
+
gt_label = item["ground_truth"].lower()
|
| 58 |
+
|
| 59 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 60 |
+
|
| 61 |
+
detailed_item = {
|
| 62 |
+
"id": item_id,
|
| 63 |
+
"model_output": model_output,
|
| 64 |
+
"extracted_prediction": pred_label,
|
| 65 |
+
"ground_truth": gt_label,
|
| 66 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 67 |
+
"valid": is_valid,
|
| 68 |
+
}
|
| 69 |
+
detailed_results.append(detailed_item)
|
| 70 |
+
if not is_valid:
|
| 71 |
+
extraction_errors[error_type].append(item_id)
|
| 72 |
+
elif pred_label != gt_label:
|
| 73 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 74 |
+
prediction_errors[error_pattern].append(item_id)
|
| 75 |
+
|
| 76 |
+
if is_valid:
|
| 77 |
+
predictions.append(pred_label)
|
| 78 |
+
ground_truths.append(gt_label)
|
| 79 |
+
|
| 80 |
+
if len(predictions) == 0:
|
| 81 |
+
return {
|
| 82 |
+
"error": "No valid predictions found",
|
| 83 |
+
"total_samples": len(results),
|
| 84 |
+
"extraction_errors": dict(extraction_errors),
|
| 85 |
+
}
|
| 86 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 87 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 88 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 89 |
+
|
| 90 |
+
labels = ["positive", "negative", "neutral"]
|
| 91 |
+
cm = confusion_matrix(ground_truths, predictions, labels=labels)
|
| 92 |
+
|
| 93 |
+
class_report = classification_report(
|
| 94 |
+
ground_truths, predictions, target_names=labels, output_dict=True
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
evaluation_result = {
|
| 98 |
+
"task_info": {
|
| 99 |
+
"task_name": "face.expression.emotion.detection",
|
| 100 |
+
"dataset": "CH-SIMS",
|
| 101 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 102 |
+
"total_samples": len(results),
|
| 103 |
+
"valid_predictions": len(predictions),
|
| 104 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 105 |
+
},
|
| 106 |
+
"metrics": {
|
| 107 |
+
"ACC": round(accuracy, 4),
|
| 108 |
+
"WAF": round(weighted_f1, 4),
|
| 109 |
+
"Macro_F1": round(macro_f1, 4),
|
| 110 |
+
},
|
| 111 |
+
"per_class_metrics": {
|
| 112 |
+
label: {
|
| 113 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 114 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 115 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 116 |
+
"support": int(class_report[label]["support"]),
|
| 117 |
+
}
|
| 118 |
+
for label in labels
|
| 119 |
+
},
|
| 120 |
+
"confusion_matrix": {"labels": labels, "matrix": cm.tolist()},
|
| 121 |
+
"error_analysis": {
|
| 122 |
+
"extraction_errors": {
|
| 123 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 124 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 125 |
+
},
|
| 126 |
+
"prediction_errors": {
|
| 127 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 128 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 129 |
+
},
|
| 130 |
+
},
|
| 131 |
+
"distribution": {
|
| 132 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 133 |
+
"predictions": dict(Counter(predictions)),
|
| 134 |
+
},
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
base_name = result_file_path.replace(".json", "")
|
| 138 |
+
|
| 139 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 140 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 141 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 142 |
+
|
| 143 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 144 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 145 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 146 |
+
|
| 147 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 148 |
+
if problem_samples:
|
| 149 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 150 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 151 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if problem_samples:
|
| 155 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 156 |
+
|
| 157 |
+
return evaluation_result
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if __name__ == "__main__":
|
| 162 |
+
result_file = "model_result.json"
|
| 163 |
+
|
| 164 |
+
try:
|
| 165 |
+
evaluation_result = evaluate_face_expression_emotion_detection(result_file)
|
| 166 |
+
|
| 167 |
+
except FileNotFoundError:
|
| 168 |
+
print(f"Error: File not found {result_file}")
|
| 169 |
+
except json.JSONDecodeError:
|
| 170 |
+
print(f"Error: {result_file} Invalid format")
|
| 171 |
+
except Exception as e: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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
valid_emotions = [
|
| 21 |
+
"amusement",
|
| 22 |
+
"anger",
|
| 23 |
+
"awe",
|
| 24 |
+
"contentment",
|
| 25 |
+
"disgust",
|
| 26 |
+
"excitement",
|
| 27 |
+
"fear",
|
| 28 |
+
"sadness",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
patterns = [
|
| 32 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 33 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 34 |
+
r"\b(amusement|anger|awe|contentment|disgust|excitement|fear|sadness)\b",
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
for pattern in patterns:
|
| 38 |
+
match = re.search(pattern, model_output.lower())
|
| 39 |
+
if match:
|
| 40 |
+
emotion = match.group(1).lower()
|
| 41 |
+
if emotion in valid_emotions:
|
| 42 |
+
return emotion, True, None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 46 |
+
return None, False, "invalid_emotion_label"
|
| 47 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 48 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 49 |
+
else:
|
| 50 |
+
return None, False, "no_emotion_pattern"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def evaluate_image_sentiment_analysis(result_file_path):
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 58 |
+
results = json.load(f)
|
| 59 |
+
|
| 60 |
+
predictions = []
|
| 61 |
+
ground_truths = []
|
| 62 |
+
detailed_results = []
|
| 63 |
+
extraction_errors = defaultdict(list)
|
| 64 |
+
prediction_errors = defaultdict(list)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
emotion_labels = [
|
| 68 |
+
"amusement",
|
| 69 |
+
"anger",
|
| 70 |
+
"awe",
|
| 71 |
+
"contentment",
|
| 72 |
+
"disgust",
|
| 73 |
+
"excitement",
|
| 74 |
+
"fear",
|
| 75 |
+
"sadness",
|
| 76 |
+
]
|
| 77 |
+
|
| 78 |
+
for item in results:
|
| 79 |
+
item_id = item["id"]
|
| 80 |
+
model_output = item["model_output"]
|
| 81 |
+
gt_label = item["ground_truth"].lower()
|
| 82 |
+
|
| 83 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 84 |
+
|
| 85 |
+
detailed_item = {
|
| 86 |
+
"id": item_id,
|
| 87 |
+
"model_output": model_output,
|
| 88 |
+
"extracted_prediction": pred_label,
|
| 89 |
+
"ground_truth": gt_label,
|
| 90 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 91 |
+
"valid": is_valid,
|
| 92 |
+
}
|
| 93 |
+
detailed_results.append(detailed_item)
|
| 94 |
+
|
| 95 |
+
if not is_valid:
|
| 96 |
+
extraction_errors[error_type].append(item_id)
|
| 97 |
+
elif pred_label != gt_label:
|
| 98 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 99 |
+
prediction_errors[error_pattern].append(item_id)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if is_valid:
|
| 103 |
+
predictions.append(pred_label)
|
| 104 |
+
ground_truths.append(gt_label)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if len(predictions) == 0:
|
| 108 |
+
return {
|
| 109 |
+
"error": "No valid predictions found",
|
| 110 |
+
"total_samples": len(results),
|
| 111 |
+
"extraction_errors": dict(extraction_errors),
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 116 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 117 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
cm = confusion_matrix(ground_truths, predictions, labels=emotion_labels)
|
| 121 |
+
|
| 122 |
+
class_report = classification_report(
|
| 123 |
+
ground_truths,
|
| 124 |
+
predictions,
|
| 125 |
+
target_names=emotion_labels,
|
| 126 |
+
output_dict=True,
|
| 127 |
+
zero_division=0,
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
evaluation_result = {
|
| 131 |
+
"task_info": {
|
| 132 |
+
"task_name": "image.sentiment.analysis",
|
| 133 |
+
"dataset": "EmoSet",
|
| 134 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 135 |
+
"total_samples": len(results),
|
| 136 |
+
"valid_predictions": len(predictions),
|
| 137 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 138 |
+
},
|
| 139 |
+
"metrics": {
|
| 140 |
+
"ACC": round(accuracy, 4),
|
| 141 |
+
"WAF": round(weighted_f1, 4),
|
| 142 |
+
"Macro_F1": round(macro_f1, 4),
|
| 143 |
+
},
|
| 144 |
+
"per_class_metrics": {
|
| 145 |
+
label: {
|
| 146 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 147 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 148 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 149 |
+
"support": int(class_report[label]["support"]),
|
| 150 |
+
}
|
| 151 |
+
for label in emotion_labels
|
| 152 |
+
if label in class_report
|
| 153 |
+
},
|
| 154 |
+
"confusion_matrix": {"labels": emotion_labels, "matrix": cm.tolist()},
|
| 155 |
+
"error_analysis": {
|
| 156 |
+
"extraction_errors": {
|
| 157 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 158 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 159 |
+
},
|
| 160 |
+
"prediction_errors": {
|
| 161 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 162 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 163 |
+
},
|
| 164 |
+
},
|
| 165 |
+
"distribution": {
|
| 166 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 167 |
+
"predictions": dict(Counter(predictions)),
|
| 168 |
+
},
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
base_name = result_file_path.replace(".json", "")
|
| 172 |
+
|
| 173 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 174 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 175 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 176 |
+
|
| 177 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 178 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 179 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 180 |
+
|
| 181 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 182 |
+
if problem_samples:
|
| 183 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 184 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 185 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
print(f"Evaluation completed: {len(results)} samples")
|
| 189 |
+
print(
|
| 190 |
+
f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, WAF={evaluation_result['metrics']['WAF']}"
|
| 191 |
+
)
|
| 192 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 193 |
+
print(f"Results saved to: {eval_output_file}")
|
| 194 |
+
if problem_samples:
|
| 195 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 196 |
+
|
| 197 |
+
return evaluation_result
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if __name__ == "__main__":
|
| 201 |
+
result_file = "model_result.json"
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
evaluation_result = evaluate_image_sentiment_analysis(result_file)
|
| 205 |
+
|
| 206 |
+
except FileNotFoundError:
|
| 207 |
+
print(f"Error: File not found {result_file}")
|
| 208 |
+
except json.JSONDecodeError:
|
| 209 |
+
print(f"Error: {result_file} Invalid format")
|
| 210 |
+
except Exception as e:
|
| 211 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level1/evaluation_MER.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
valid_emotions = ["happy", "sad", "neutral", "angry", "worried", "surprise"]
|
| 22 |
+
|
| 23 |
+
patterns = [
|
| 24 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 25 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 26 |
+
r"\b(happy|sad|neutral|angry|worried|surprise)\b",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
for pattern in patterns:
|
| 30 |
+
match = re.search(pattern, model_output.lower())
|
| 31 |
+
if match:
|
| 32 |
+
emotion = match.group(1).lower()
|
| 33 |
+
if emotion in valid_emotions:
|
| 34 |
+
return emotion, True, None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 38 |
+
return None, False, "invalid_emotion_label"
|
| 39 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 40 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 41 |
+
else:
|
| 42 |
+
return None, False, "no_emotion_pattern"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def evaluate_multimodal_emotion_recognition(result_file_path):
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 50 |
+
results = json.load(f)
|
| 51 |
+
|
| 52 |
+
predictions = []
|
| 53 |
+
ground_truths = []
|
| 54 |
+
detailed_results = []
|
| 55 |
+
extraction_errors = defaultdict(list)
|
| 56 |
+
prediction_errors = defaultdict(list)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
emotion_labels = ["happy", "sad", "neutral", "angry", "worried", "surprise"]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
for item in results:
|
| 63 |
+
item_id = item["id"]
|
| 64 |
+
model_output = item["model_output"]
|
| 65 |
+
gt_label = item["ground_truth"].lower()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
detailed_item = {
|
| 72 |
+
"id": item_id,
|
| 73 |
+
"model_output": model_output,
|
| 74 |
+
"extracted_prediction": pred_label,
|
| 75 |
+
"ground_truth": gt_label,
|
| 76 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 77 |
+
"valid": is_valid,
|
| 78 |
+
}
|
| 79 |
+
detailed_results.append(detailed_item)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if not is_valid:
|
| 83 |
+
extraction_errors[error_type].append(item_id)
|
| 84 |
+
elif pred_label != gt_label:
|
| 85 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 86 |
+
prediction_errors[error_pattern].append(item_id)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
if is_valid:
|
| 90 |
+
predictions.append(pred_label)
|
| 91 |
+
ground_truths.append(gt_label)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if len(predictions) == 0:
|
| 95 |
+
return {
|
| 96 |
+
"error": "No valid predictions found",
|
| 97 |
+
"total_samples": len(results),
|
| 98 |
+
"extraction_errors": dict(extraction_errors),
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 103 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 104 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
cm = confusion_matrix(ground_truths, predictions, labels=emotion_labels)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class_report = classification_report(
|
| 111 |
+
ground_truths,
|
| 112 |
+
predictions,
|
| 113 |
+
target_names=emotion_labels,
|
| 114 |
+
output_dict=True,
|
| 115 |
+
zero_division=0,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
evaluation_result = {
|
| 120 |
+
"task_info": {
|
| 121 |
+
"task_name": "multimodal.emotion.recognition",
|
| 122 |
+
"dataset": "MER2023",
|
| 123 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 124 |
+
"total_samples": len(results),
|
| 125 |
+
"valid_predictions": len(predictions),
|
| 126 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 127 |
+
},
|
| 128 |
+
"metrics": {
|
| 129 |
+
"ACC": round(accuracy, 4),
|
| 130 |
+
"WAF": round(weighted_f1, 4),
|
| 131 |
+
"Macro_F1": round(macro_f1, 4),
|
| 132 |
+
},
|
| 133 |
+
"per_class_metrics": {
|
| 134 |
+
label: {
|
| 135 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 136 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 137 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 138 |
+
"support": int(class_report[label]["support"]),
|
| 139 |
+
}
|
| 140 |
+
for label in emotion_labels
|
| 141 |
+
if label in class_report
|
| 142 |
+
},
|
| 143 |
+
"confusion_matrix": {"labels": emotion_labels, "matrix": cm.tolist()},
|
| 144 |
+
"error_analysis": {
|
| 145 |
+
"extraction_errors": {
|
| 146 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 147 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 148 |
+
},
|
| 149 |
+
"prediction_errors": {
|
| 150 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 151 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 152 |
+
},
|
| 153 |
+
},
|
| 154 |
+
"distribution": {
|
| 155 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 156 |
+
"predictions": dict(Counter(predictions)),
|
| 157 |
+
},
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
base_name = result_file_path.replace(".json", "")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 165 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 166 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 170 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 171 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 175 |
+
if problem_samples:
|
| 176 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 177 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 178 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
print(f"Evaluation completed: {len(results)} samples")
|
| 182 |
+
print(
|
| 183 |
+
f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, WAF={evaluation_result['metrics']['WAF']}"
|
| 184 |
+
)
|
| 185 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 186 |
+
print(f"Results saved to: {eval_output_file}")
|
| 187 |
+
if problem_samples:
|
| 188 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 189 |
+
|
| 190 |
+
return evaluation_result
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if __name__ == "__main__":
|
| 195 |
+
result_file = "model_result.json"
|
| 196 |
+
|
| 197 |
+
try:
|
| 198 |
+
evaluation_result = evaluate_multimodal_emotion_recognition(result_file)
|
| 199 |
+
|
| 200 |
+
except FileNotFoundError:
|
| 201 |
+
print(f"Error: File not found {result_file}")
|
| 202 |
+
except json.JSONDecodeError:
|
| 203 |
+
print(f"Error: {result_file} Invalid format")
|
| 204 |
+
except Exception as e:
|
| 205 |
+
print(f"Evaluation failed: {str(e)}")
|
| 206 |
+
|
code/evaluation_code/level1/evaluation_MESA.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
valid_emotions = [
|
| 22 |
+
"very_positive",
|
| 23 |
+
"positive",
|
| 24 |
+
"neutral",
|
| 25 |
+
"negative",
|
| 26 |
+
"very_negative",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
patterns = [
|
| 31 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 32 |
+
r"['\"]emotion['\"]:\s*['\"]([a-z_]+)['\"]",
|
| 33 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 34 |
+
r"emotion['\"]?\s*:\s*['\"]?([a-z_]+)['\"]?",
|
| 35 |
+
r"\b(very_positive|very_negative|positive|negative|neutral)\b",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
for pattern in patterns:
|
| 39 |
+
match = re.search(pattern, model_output.lower())
|
| 40 |
+
if match:
|
| 41 |
+
emotion = match.group(1).lower()
|
| 42 |
+
if emotion in valid_emotions:
|
| 43 |
+
return emotion, True, None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 47 |
+
return None, False, "invalid_emotion_label"
|
| 48 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 49 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 50 |
+
else:
|
| 51 |
+
return None, False, "no_emotion_pattern"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def evaluate_meme_sentiment_analysis(result_file_path):
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 59 |
+
results = json.load(f)
|
| 60 |
+
|
| 61 |
+
predictions = []
|
| 62 |
+
ground_truths = []
|
| 63 |
+
detailed_results = []
|
| 64 |
+
extraction_errors = defaultdict(list)
|
| 65 |
+
prediction_errors = defaultdict(list)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
sentiment_labels = [
|
| 69 |
+
"very_positive",
|
| 70 |
+
"positive",
|
| 71 |
+
"neutral",
|
| 72 |
+
"negative",
|
| 73 |
+
"very_negative",
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
for item in results:
|
| 78 |
+
item_id = item["id"]
|
| 79 |
+
model_output = item["model_output"]
|
| 80 |
+
gt_label = item["ground_truth"].lower()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
detailed_item = {
|
| 87 |
+
"id": item_id,
|
| 88 |
+
"model_output": model_output,
|
| 89 |
+
"extracted_prediction": pred_label,
|
| 90 |
+
"ground_truth": gt_label,
|
| 91 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 92 |
+
"valid": is_valid,
|
| 93 |
+
}
|
| 94 |
+
detailed_results.append(detailed_item)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if not is_valid:
|
| 98 |
+
extraction_errors[error_type].append(item_id)
|
| 99 |
+
elif pred_label != gt_label:
|
| 100 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 101 |
+
prediction_errors[error_pattern].append(item_id)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if is_valid:
|
| 105 |
+
predictions.append(pred_label)
|
| 106 |
+
ground_truths.append(gt_label)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if len(predictions) == 0:
|
| 110 |
+
return {
|
| 111 |
+
"error": "No valid predictions found",
|
| 112 |
+
"total_samples": len(results),
|
| 113 |
+
"extraction_errors": dict(extraction_errors),
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 118 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 119 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
cm = confusion_matrix(ground_truths, predictions, labels=sentiment_labels)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class_report = classification_report(
|
| 126 |
+
ground_truths,
|
| 127 |
+
predictions,
|
| 128 |
+
target_names=sentiment_labels,
|
| 129 |
+
output_dict=True,
|
| 130 |
+
zero_division=0,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
evaluation_result = {
|
| 135 |
+
"task_info": {
|
| 136 |
+
"task_name": "meme.sentiment.analysis",
|
| 137 |
+
"dataset": "Memotion",
|
| 138 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 139 |
+
"total_samples": len(results),
|
| 140 |
+
"valid_predictions": len(predictions),
|
| 141 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 142 |
+
},
|
| 143 |
+
"metrics": {
|
| 144 |
+
"ACC": round(accuracy, 4),
|
| 145 |
+
"WAF": round(weighted_f1, 4),
|
| 146 |
+
"Macro_F1": round(macro_f1, 4),
|
| 147 |
+
},
|
| 148 |
+
"per_class_metrics": {
|
| 149 |
+
label: {
|
| 150 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 151 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 152 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 153 |
+
"support": int(class_report[label]["support"]),
|
| 154 |
+
}
|
| 155 |
+
for label in sentiment_labels
|
| 156 |
+
if label in class_report
|
| 157 |
+
},
|
| 158 |
+
"confusion_matrix": {"labels": sentiment_labels, "matrix": cm.tolist()},
|
| 159 |
+
"error_analysis": {
|
| 160 |
+
"extraction_errors": {
|
| 161 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 162 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 163 |
+
},
|
| 164 |
+
"prediction_errors": {
|
| 165 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 166 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 167 |
+
},
|
| 168 |
+
},
|
| 169 |
+
"distribution": {
|
| 170 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 171 |
+
"predictions": dict(Counter(predictions)),
|
| 172 |
+
},
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
base_name = result_file_path.replace(".json", "")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 180 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 181 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 185 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 186 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 190 |
+
if problem_samples:
|
| 191 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 192 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 193 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if problem_samples:
|
| 197 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 198 |
+
|
| 199 |
+
return evaluation_result
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
if __name__ == "__main__":
|
| 204 |
+
result_file = "model_result.json"
|
| 205 |
+
|
| 206 |
+
try:
|
| 207 |
+
evaluation_result = evaluate_meme_sentiment_analysis(result_file)
|
| 208 |
+
|
| 209 |
+
except FileNotFoundError:
|
| 210 |
+
print(f"Error: File not found {result_file}")
|
| 211 |
+
except json.JSONDecodeError:
|
| 212 |
+
print(f"Error: {result_file} Invalid format")
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f"Evaluation failed: {str(e)}")
|
| 215 |
+
|
code/evaluation_code/level1/evaluation_MSA.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
valid_emotions = ["neutral", "negative", "positive"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
patterns = [
|
| 25 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 26 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 27 |
+
r"\b(neutral|negative|positive)\b",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
for pattern in patterns:
|
| 31 |
+
match = re.search(pattern, model_output.lower())
|
| 32 |
+
if match:
|
| 33 |
+
emotion = match.group(1).lower()
|
| 34 |
+
if emotion in valid_emotions:
|
| 35 |
+
return emotion, True, None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 39 |
+
return None, False, "invalid_emotion_label"
|
| 40 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 41 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 42 |
+
else:
|
| 43 |
+
return None, False, "no_emotion_pattern"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def evaluate_multimodal_sentiment_analysis(result_file_path):
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 51 |
+
results = json.load(f)
|
| 52 |
+
|
| 53 |
+
predictions = []
|
| 54 |
+
ground_truths = []
|
| 55 |
+
detailed_results = []
|
| 56 |
+
extraction_errors = defaultdict(list)
|
| 57 |
+
prediction_errors = defaultdict(list)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
sentiment_labels = ["positive", "neutral", "negative"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
for item in results:
|
| 64 |
+
item_id = item["id"]
|
| 65 |
+
model_output = item["model_output"]
|
| 66 |
+
gt_label = item["ground_truth"].lower()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
detailed_item = {
|
| 73 |
+
"id": item_id,
|
| 74 |
+
"model_output": model_output,
|
| 75 |
+
"extracted_prediction": pred_label,
|
| 76 |
+
"ground_truth": gt_label,
|
| 77 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 78 |
+
"valid": is_valid,
|
| 79 |
+
}
|
| 80 |
+
detailed_results.append(detailed_item)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
if not is_valid:
|
| 84 |
+
extraction_errors[error_type].append(item_id)
|
| 85 |
+
elif pred_label != gt_label:
|
| 86 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 87 |
+
prediction_errors[error_pattern].append(item_id)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if is_valid:
|
| 91 |
+
predictions.append(pred_label)
|
| 92 |
+
ground_truths.append(gt_label)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if len(predictions) == 0:
|
| 96 |
+
return {
|
| 97 |
+
"error": "No valid predictions found",
|
| 98 |
+
"total_samples": len(results),
|
| 99 |
+
"extraction_errors": dict(extraction_errors),
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 104 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 105 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
cm = confusion_matrix(ground_truths, predictions, labels=sentiment_labels)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class_report = classification_report(
|
| 112 |
+
ground_truths,
|
| 113 |
+
predictions,
|
| 114 |
+
target_names=sentiment_labels,
|
| 115 |
+
output_dict=True,
|
| 116 |
+
zero_division=0,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
evaluation_result = {
|
| 121 |
+
"task_info": {
|
| 122 |
+
"task_name": "multimodal.sentiment.analysis",
|
| 123 |
+
"dataset": "CH-SIMSv2",
|
| 124 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 125 |
+
"total_samples": len(results),
|
| 126 |
+
"valid_predictions": len(predictions),
|
| 127 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 128 |
+
},
|
| 129 |
+
"metrics": {
|
| 130 |
+
"ACC": round(accuracy, 4),
|
| 131 |
+
"WAF": round(weighted_f1, 4),
|
| 132 |
+
"Macro_F1": round(macro_f1, 4),
|
| 133 |
+
},
|
| 134 |
+
"per_class_metrics": {
|
| 135 |
+
label: {
|
| 136 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 137 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 138 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 139 |
+
"support": int(class_report[label]["support"]),
|
| 140 |
+
}
|
| 141 |
+
for label in sentiment_labels
|
| 142 |
+
if label in class_report
|
| 143 |
+
},
|
| 144 |
+
"confusion_matrix": {"labels": sentiment_labels, "matrix": cm.tolist()},
|
| 145 |
+
"error_analysis": {
|
| 146 |
+
"extraction_errors": {
|
| 147 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 148 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 149 |
+
},
|
| 150 |
+
"prediction_errors": {
|
| 151 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 152 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 153 |
+
},
|
| 154 |
+
},
|
| 155 |
+
"distribution": {
|
| 156 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 157 |
+
"predictions": dict(Counter(predictions)),
|
| 158 |
+
},
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
base_name = result_file_path.replace(".json", "")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 166 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 167 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 171 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 172 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 176 |
+
if problem_samples:
|
| 177 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 178 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 179 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if problem_samples:
|
| 183 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 184 |
+
|
| 185 |
+
return evaluation_result
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
result_file = "model_result.json"
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
evaluation_result = evaluate_multimodal_sentiment_analysis(result_file)
|
| 194 |
+
|
| 195 |
+
except FileNotFoundError:
|
| 196 |
+
print(f"Error: File not found {result_file}")
|
| 197 |
+
except json.JSONDecodeError:
|
| 198 |
+
print(f"Error: {result_file} Invalid format")
|
| 199 |
+
except Exception as e:
|
| 200 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level1/evaluation_OSA.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
valid_emotions = ["neutral", "negative", "positive"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
patterns = [
|
| 25 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 26 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 27 |
+
r"\b(neutral|negative|positive)\b",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
for pattern in patterns:
|
| 31 |
+
match = re.search(pattern, model_output.lower())
|
| 32 |
+
if match:
|
| 33 |
+
emotion = match.group(1).lower()
|
| 34 |
+
if emotion in valid_emotions:
|
| 35 |
+
return emotion, True, None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 39 |
+
return None, False, "invalid_emotion_label"
|
| 40 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 41 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 42 |
+
else:
|
| 43 |
+
return None, False, "no_emotion_pattern"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def evaluate_opinion_sentiment_analysis(result_file_path):
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 51 |
+
results = json.load(f)
|
| 52 |
+
|
| 53 |
+
predictions = []
|
| 54 |
+
ground_truths = []
|
| 55 |
+
detailed_results = []
|
| 56 |
+
extraction_errors = defaultdict(list)
|
| 57 |
+
prediction_errors = defaultdict(list)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
sentiment_labels = ["positive", "neutral", "negative"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
for item in results:
|
| 64 |
+
item_id = item["id"]
|
| 65 |
+
model_output = item["model_output"]
|
| 66 |
+
gt_label = item["ground_truth"].lower()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
detailed_item = {
|
| 73 |
+
"id": item_id,
|
| 74 |
+
"model_output": model_output,
|
| 75 |
+
"extracted_prediction": pred_label,
|
| 76 |
+
"ground_truth": gt_label,
|
| 77 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 78 |
+
"valid": is_valid,
|
| 79 |
+
}
|
| 80 |
+
detailed_results.append(detailed_item)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
if not is_valid:
|
| 84 |
+
extraction_errors[error_type].append(item_id)
|
| 85 |
+
elif pred_label != gt_label:
|
| 86 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 87 |
+
prediction_errors[error_pattern].append(item_id)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if is_valid:
|
| 91 |
+
predictions.append(pred_label)
|
| 92 |
+
ground_truths.append(gt_label)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if len(predictions) == 0:
|
| 96 |
+
return {
|
| 97 |
+
"error": "No valid predictions found",
|
| 98 |
+
"total_samples": len(results),
|
| 99 |
+
"extraction_errors": dict(extraction_errors),
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 104 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 105 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
cm = confusion_matrix(ground_truths, predictions, labels=sentiment_labels)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class_report = classification_report(
|
| 112 |
+
ground_truths,
|
| 113 |
+
predictions,
|
| 114 |
+
target_names=sentiment_labels,
|
| 115 |
+
output_dict=True,
|
| 116 |
+
zero_division=0,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
evaluation_result = {
|
| 121 |
+
"task_info": {
|
| 122 |
+
"task_name": "opinion.sentiment.analysis",
|
| 123 |
+
"dataset": "CMU-MOSI",
|
| 124 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 125 |
+
"total_samples": len(results),
|
| 126 |
+
"valid_predictions": len(predictions),
|
| 127 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 128 |
+
},
|
| 129 |
+
"metrics": {
|
| 130 |
+
"ACC": round(accuracy, 4),
|
| 131 |
+
"WAF": round(weighted_f1, 4),
|
| 132 |
+
"Macro_F1": round(macro_f1, 4),
|
| 133 |
+
},
|
| 134 |
+
"per_class_metrics": {
|
| 135 |
+
label: {
|
| 136 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 137 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 138 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 139 |
+
"support": int(class_report[label]["support"]),
|
| 140 |
+
}
|
| 141 |
+
for label in sentiment_labels
|
| 142 |
+
if label in class_report
|
| 143 |
+
},
|
| 144 |
+
"confusion_matrix": {"labels": sentiment_labels, "matrix": cm.tolist()},
|
| 145 |
+
"error_analysis": {
|
| 146 |
+
"extraction_errors": {
|
| 147 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 148 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 149 |
+
},
|
| 150 |
+
"prediction_errors": {
|
| 151 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 152 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 153 |
+
},
|
| 154 |
+
},
|
| 155 |
+
"distribution": {
|
| 156 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 157 |
+
"predictions": dict(Counter(predictions)),
|
| 158 |
+
},
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
base_name = result_file_path.replace(".json", "")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 166 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 167 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 171 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 172 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 176 |
+
if problem_samples:
|
| 177 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 178 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 179 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if problem_samples:
|
| 183 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 184 |
+
|
| 185 |
+
return evaluation_result
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
if __name__ == "__main__":
|
| 190 |
+
result_file = "model_result.json"
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
evaluation_result = evaluate_opinion_sentiment_analysis(result_file)
|
| 194 |
+
|
| 195 |
+
except FileNotFoundError:
|
| 196 |
+
print(f"Error: File not found {result_file}")
|
| 197 |
+
except json.JSONDecodeError:
|
| 198 |
+
print(f"Error: {result_file} Invalid format")
|
| 199 |
+
except Exception as e:
|
| 200 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level1/evaluation_SCEA.py
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def extract_emotion_from_output(model_output):
|
| 9 |
+
|
| 10 |
+
if not model_output:
|
| 11 |
+
return None, False, "empty_output"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
valid_emotions = ['weak negative', 'strong negative', 'neutral', 'strong positive', 'weak positive']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
patterns = [
|
| 18 |
+
r"['\"]emotion['\"]:\s*['\"]([^'\"]+)['\"]",
|
| 19 |
+
r"emotion['\"]?\s*:\s*['\"]?([^'\"]+)['\"]?",
|
| 20 |
+
r"\b(weak\s+negative|strong\s+negative|neutral|strong\s+positive|weak\s+positive)\b"
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
for pattern in patterns:
|
| 24 |
+
match = re.search(pattern, model_output.lower(), re.IGNORECASE)
|
| 25 |
+
if match:
|
| 26 |
+
emotion = match.group(1).lower().strip()
|
| 27 |
+
if emotion in valid_emotions:
|
| 28 |
+
return emotion, True, None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 32 |
+
return None, False, "invalid_emotion_label"
|
| 33 |
+
elif any(word in model_output.lower() for word in ['negative', 'positive', 'neutral']):
|
| 34 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 35 |
+
else:
|
| 36 |
+
return None, False, "no_emotion_pattern"
|
| 37 |
+
|
| 38 |
+
def evaluate_stock_comment_emotion_analysis(result_file_path):
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 43 |
+
results = json.load(f)
|
| 44 |
+
|
| 45 |
+
predictions = []
|
| 46 |
+
ground_truths = []
|
| 47 |
+
detailed_results = []
|
| 48 |
+
extraction_errors = defaultdict(list)
|
| 49 |
+
prediction_errors = defaultdict(list)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
sentiment_labels = ['strong negative', 'weak negative', 'neutral', 'weak positive', 'strong positive']
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
for item in results:
|
| 56 |
+
item_id = item['id']
|
| 57 |
+
model_output = item['model_output']
|
| 58 |
+
gt_label = item['ground_truth'].lower()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
detailed_item = {
|
| 65 |
+
'id': item_id,
|
| 66 |
+
'model_output': model_output,
|
| 67 |
+
'extracted_prediction': pred_label,
|
| 68 |
+
'ground_truth': gt_label,
|
| 69 |
+
'correct': pred_label == gt_label if pred_label else False,
|
| 70 |
+
'valid': is_valid
|
| 71 |
+
}
|
| 72 |
+
detailed_results.append(detailed_item)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if not is_valid:
|
| 76 |
+
extraction_errors[error_type].append(item_id)
|
| 77 |
+
elif pred_label != gt_label:
|
| 78 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 79 |
+
prediction_errors[error_pattern].append(item_id)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if is_valid:
|
| 83 |
+
predictions.append(pred_label)
|
| 84 |
+
ground_truths.append(gt_label)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if len(predictions) == 0:
|
| 88 |
+
return {
|
| 89 |
+
'error': 'No valid predictions found',
|
| 90 |
+
'total_samples': len(results),
|
| 91 |
+
'extraction_errors': dict(extraction_errors)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 96 |
+
weighted_f1 = f1_score(ground_truths, predictions, average='weighted')
|
| 97 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
cm = confusion_matrix(ground_truths, predictions, labels=sentiment_labels)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class_report = classification_report(ground_truths, predictions,
|
| 104 |
+
target_names=sentiment_labels,
|
| 105 |
+
output_dict=True,
|
| 106 |
+
zero_division=0)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
evaluation_result = {
|
| 110 |
+
'task_info': {
|
| 111 |
+
'task_name': 'stock.comment.emotion.analysis',
|
| 112 |
+
'dataset': 'FMSA-SC',
|
| 113 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 114 |
+
'total_samples': len(results),
|
| 115 |
+
'valid_predictions': len(predictions),
|
| 116 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 117 |
+
},
|
| 118 |
+
'metrics': {
|
| 119 |
+
'ACC': round(accuracy, 4),
|
| 120 |
+
'WAF': round(weighted_f1, 4),
|
| 121 |
+
'Macro_F1': round(macro_f1, 4)
|
| 122 |
+
},
|
| 123 |
+
'per_class_metrics': {
|
| 124 |
+
label: {
|
| 125 |
+
'precision': round(class_report[label]['precision'], 4),
|
| 126 |
+
'recall': round(class_report[label]['recall'], 4),
|
| 127 |
+
'f1_score': round(class_report[label]['f1-score'], 4),
|
| 128 |
+
'support': int(class_report[label]['support'])
|
| 129 |
+
} for label in sentiment_labels if label in class_report
|
| 130 |
+
},
|
| 131 |
+
'confusion_matrix': {
|
| 132 |
+
'labels': sentiment_labels,
|
| 133 |
+
'matrix': cm.tolist()
|
| 134 |
+
},
|
| 135 |
+
'error_analysis': {
|
| 136 |
+
'extraction_errors': {
|
| 137 |
+
error_type: {
|
| 138 |
+
'count': len(sample_ids),
|
| 139 |
+
'sample_ids': sample_ids
|
| 140 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 141 |
+
},
|
| 142 |
+
'prediction_errors': {
|
| 143 |
+
error_pattern: {
|
| 144 |
+
'count': len(sample_ids),
|
| 145 |
+
'sample_ids': sample_ids
|
| 146 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 147 |
+
}
|
| 148 |
+
},
|
| 149 |
+
'distribution': {
|
| 150 |
+
'ground_truth': dict(Counter(ground_truths)),
|
| 151 |
+
'predictions': dict(Counter(predictions))
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
base_name = result_file_path.replace('.json', '')
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 160 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 161 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 165 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 166 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
problem_samples = [item for item in detailed_results if not item['correct']]
|
| 170 |
+
if problem_samples:
|
| 171 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 172 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 173 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if problem_samples:
|
| 177 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 178 |
+
|
| 179 |
+
return evaluation_result
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
result_file = "model_result.json"
|
| 184 |
+
|
| 185 |
+
try:
|
| 186 |
+
evaluation_result = evaluate_stock_comment_emotion_analysis(result_file)
|
| 187 |
+
|
| 188 |
+
except FileNotFoundError:
|
| 189 |
+
print(f"Error: File not found {result_file}")
|
| 190 |
+
except json.JSONDecodeError:
|
| 191 |
+
print(f"Error: {result_file} Invalid format")
|
| 192 |
+
except Exception as e:
|
| 193 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level1/evaluation_SIA.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
valid_emotions = [
|
| 22 |
+
"strong negative",
|
| 23 |
+
"moderate negative",
|
| 24 |
+
"slight negative",
|
| 25 |
+
"neutral",
|
| 26 |
+
"slight positive",
|
| 27 |
+
"moderate positive",
|
| 28 |
+
"strong positive",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
patterns = [
|
| 33 |
+
r"['\"]emotion['\"]:\s*['\"]([^'\"]+)['\"]",
|
| 34 |
+
r"emotion['\"]?\s*:\s*['\"]?([^'\"]+)['\"]?",
|
| 35 |
+
r"\b(strong\s+negative|moderate\s+negative|slight\s+negative|neutral|slight\s+positive|moderate\s+positive|strong\s+positive)\b",
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
for pattern in patterns:
|
| 39 |
+
match = re.search(pattern, model_output.lower(), re.IGNORECASE)
|
| 40 |
+
if match:
|
| 41 |
+
emotion = match.group(1).lower().strip()
|
| 42 |
+
if emotion in valid_emotions:
|
| 43 |
+
return emotion, True, None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 47 |
+
return None, False, "invalid_emotion_label"
|
| 48 |
+
elif any(
|
| 49 |
+
word in model_output.lower() for word in ["negative", "positive", "neutral"]
|
| 50 |
+
):
|
| 51 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 52 |
+
else:
|
| 53 |
+
return None, False, "no_emotion_pattern"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def evaluate_sentiment_intensity_analysis(result_file_path):
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 61 |
+
results = json.load(f)
|
| 62 |
+
|
| 63 |
+
predictions = []
|
| 64 |
+
ground_truths = []
|
| 65 |
+
detailed_results = []
|
| 66 |
+
extraction_errors = defaultdict(list)
|
| 67 |
+
prediction_errors = defaultdict(list)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
intensity_labels = [
|
| 71 |
+
"strong negative",
|
| 72 |
+
"moderate negative",
|
| 73 |
+
"slight negative",
|
| 74 |
+
"neutral",
|
| 75 |
+
"slight positive",
|
| 76 |
+
"moderate positive",
|
| 77 |
+
"strong positive",
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
for item in results:
|
| 82 |
+
item_id = item["id"]
|
| 83 |
+
model_output = item["model_output"]
|
| 84 |
+
gt_label = item["ground_truth"].lower()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
detailed_item = {
|
| 91 |
+
"id": item_id,
|
| 92 |
+
"model_output": model_output,
|
| 93 |
+
"extracted_prediction": pred_label,
|
| 94 |
+
"ground_truth": gt_label,
|
| 95 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 96 |
+
"valid": is_valid,
|
| 97 |
+
}
|
| 98 |
+
detailed_results.append(detailed_item)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if not is_valid:
|
| 102 |
+
extraction_errors[error_type].append(item_id)
|
| 103 |
+
elif pred_label != gt_label:
|
| 104 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 105 |
+
prediction_errors[error_pattern].append(item_id)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
if is_valid:
|
| 109 |
+
predictions.append(pred_label)
|
| 110 |
+
ground_truths.append(gt_label)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
if len(predictions) == 0:
|
| 114 |
+
return {
|
| 115 |
+
"error": "No valid predictions found",
|
| 116 |
+
"total_samples": len(results),
|
| 117 |
+
"extraction_errors": dict(extraction_errors),
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 122 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 123 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
cm = confusion_matrix(ground_truths, predictions, labels=intensity_labels)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class_report = classification_report(
|
| 130 |
+
ground_truths,
|
| 131 |
+
predictions,
|
| 132 |
+
target_names=intensity_labels,
|
| 133 |
+
output_dict=True,
|
| 134 |
+
zero_division=0,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
evaluation_result = {
|
| 139 |
+
"task_info": {
|
| 140 |
+
"task_name": "sentiment.intensity.analysis",
|
| 141 |
+
"dataset": "CMU-MOSEI",
|
| 142 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 143 |
+
"total_samples": len(results),
|
| 144 |
+
"valid_predictions": len(predictions),
|
| 145 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 146 |
+
},
|
| 147 |
+
"metrics": {
|
| 148 |
+
"ACC": round(accuracy, 4),
|
| 149 |
+
"WAF": round(weighted_f1, 4),
|
| 150 |
+
"Macro_F1": round(macro_f1, 4),
|
| 151 |
+
},
|
| 152 |
+
"per_class_metrics": {
|
| 153 |
+
label: {
|
| 154 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 155 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 156 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 157 |
+
"support": int(class_report[label]["support"]),
|
| 158 |
+
}
|
| 159 |
+
for label in intensity_labels
|
| 160 |
+
if label in class_report
|
| 161 |
+
},
|
| 162 |
+
"confusion_matrix": {"labels": intensity_labels, "matrix": cm.tolist()},
|
| 163 |
+
"error_analysis": {
|
| 164 |
+
"extraction_errors": {
|
| 165 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 166 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 167 |
+
},
|
| 168 |
+
"prediction_errors": {
|
| 169 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 170 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 171 |
+
},
|
| 172 |
+
},
|
| 173 |
+
"distribution": {
|
| 174 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 175 |
+
"predictions": dict(Counter(predictions)),
|
| 176 |
+
},
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
base_name = result_file_path.replace(".json", "")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 184 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 185 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 189 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 190 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 194 |
+
if problem_samples:
|
| 195 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 196 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 197 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if problem_samples:
|
| 201 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 202 |
+
|
| 203 |
+
return evaluation_result
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__ == "__main__":
|
| 208 |
+
result_file = "model_result.json"
|
| 209 |
+
|
| 210 |
+
try:
|
| 211 |
+
evaluation_result = evaluate_sentiment_intensity_analysis(result_file)
|
| 212 |
+
|
| 213 |
+
except FileNotFoundError:
|
| 214 |
+
print(f"Error: File not found {result_file}")
|
| 215 |
+
except json.JSONDecodeError:
|
| 216 |
+
print(f"Error: {result_file} Invalid format")
|
| 217 |
+
except Exception as e:
|
| 218 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from collections import Counter, defaultdict
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
from sklearn.metrics import (
|
| 8 |
+
accuracy_score,
|
| 9 |
+
classification_report,
|
| 10 |
+
confusion_matrix,
|
| 11 |
+
f1_score,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def extract_emotion_from_output(model_output):
|
| 16 |
+
|
| 17 |
+
if not model_output:
|
| 18 |
+
return None, False, "empty_output"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
valid_emotions = ["neutral", "calm", "happy", "sad", "angry", "fearful"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
patterns = [
|
| 25 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 26 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 27 |
+
r"\b(neutral|calm|happy|sad|angry|fearful)\b",
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
for pattern in patterns:
|
| 31 |
+
match = re.search(pattern, model_output.lower())
|
| 32 |
+
if match:
|
| 33 |
+
emotion = match.group(1).lower()
|
| 34 |
+
if emotion in valid_emotions:
|
| 35 |
+
return emotion, True, None
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 39 |
+
return None, False, "invalid_emotion_label"
|
| 40 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 41 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 42 |
+
else:
|
| 43 |
+
return None, False, "no_emotion_pattern"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def evaluate_song_emotion_recognition(result_file_path):
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
with open(result_file_path, "r", encoding="utf-8") as f:
|
| 51 |
+
results = json.load(f)
|
| 52 |
+
|
| 53 |
+
predictions = []
|
| 54 |
+
ground_truths = []
|
| 55 |
+
detailed_results = []
|
| 56 |
+
extraction_errors = defaultdict(list)
|
| 57 |
+
prediction_errors = defaultdict(list)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
emotion_labels = ["neutral", "calm", "happy", "sad", "angry", "fearful"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
for item in results:
|
| 64 |
+
item_id = item["id"]
|
| 65 |
+
model_output = item["model_output"]
|
| 66 |
+
gt_label = item["ground_truth"].lower()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
detailed_item = {
|
| 73 |
+
"id": item_id,
|
| 74 |
+
"model_output": model_output,
|
| 75 |
+
"extracted_prediction": pred_label,
|
| 76 |
+
"ground_truth": gt_label,
|
| 77 |
+
"correct": pred_label == gt_label if pred_label else False,
|
| 78 |
+
"valid": is_valid,
|
| 79 |
+
}
|
| 80 |
+
detailed_results.append(detailed_item)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
if not is_valid:
|
| 84 |
+
extraction_errors[error_type].append(item_id)
|
| 85 |
+
elif pred_label != gt_label:
|
| 86 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 87 |
+
prediction_errors[error_pattern].append(item_id)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if is_valid:
|
| 91 |
+
predictions.append(pred_label)
|
| 92 |
+
ground_truths.append(gt_label)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
if len(predictions) == 0:
|
| 96 |
+
return {
|
| 97 |
+
"error": "No valid predictions found",
|
| 98 |
+
"total_samples": len(results),
|
| 99 |
+
"extraction_errors": dict(extraction_errors),
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 104 |
+
weighted_f1 = f1_score(ground_truths, predictions, average="weighted")
|
| 105 |
+
macro_f1 = f1_score(ground_truths, predictions, average="macro")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
cm = confusion_matrix(ground_truths, predictions, labels=emotion_labels)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class_report = classification_report(
|
| 112 |
+
ground_truths,
|
| 113 |
+
predictions,
|
| 114 |
+
target_names=emotion_labels,
|
| 115 |
+
output_dict=True,
|
| 116 |
+
zero_division=0,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
evaluation_result = {
|
| 121 |
+
"task_info": {
|
| 122 |
+
"task_name": "song.emotion.recognition",
|
| 123 |
+
"dataset": "RAVDESS",
|
| 124 |
+
"evaluation_time": datetime.now().isoformat(),
|
| 125 |
+
"total_samples": len(results),
|
| 126 |
+
"valid_predictions": len(predictions),
|
| 127 |
+
"extraction_success_rate": round(len(predictions) / len(results), 4),
|
| 128 |
+
},
|
| 129 |
+
"metrics": {
|
| 130 |
+
"ACC": round(accuracy, 4),
|
| 131 |
+
"WAF": round(weighted_f1, 4),
|
| 132 |
+
"Macro_F1": round(macro_f1, 4),
|
| 133 |
+
},
|
| 134 |
+
"per_class_metrics": {
|
| 135 |
+
label: {
|
| 136 |
+
"precision": round(class_report[label]["precision"], 4),
|
| 137 |
+
"recall": round(class_report[label]["recall"], 4),
|
| 138 |
+
"f1_score": round(class_report[label]["f1-score"], 4),
|
| 139 |
+
"support": int(class_report[label]["support"]),
|
| 140 |
+
}
|
| 141 |
+
for label in emotion_labels
|
| 142 |
+
if label in class_report
|
| 143 |
+
},
|
| 144 |
+
"confusion_matrix": {"labels": emotion_labels, "matrix": cm.tolist()},
|
| 145 |
+
"error_analysis": {
|
| 146 |
+
"extraction_errors": {
|
| 147 |
+
error_type: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 148 |
+
for error_type, sample_ids in extraction_errors.items()
|
| 149 |
+
},
|
| 150 |
+
"prediction_errors": {
|
| 151 |
+
error_pattern: {"count": len(sample_ids), "sample_ids": sample_ids}
|
| 152 |
+
for error_pattern, sample_ids in prediction_errors.items()
|
| 153 |
+
},
|
| 154 |
+
},
|
| 155 |
+
"distribution": {
|
| 156 |
+
"ground_truth": dict(Counter(ground_truths)),
|
| 157 |
+
"predictions": dict(Counter(predictions)),
|
| 158 |
+
},
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
base_name = result_file_path.replace(".json", "")
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 166 |
+
with open(eval_output_file, "w", encoding="utf-8") as f:
|
| 167 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 171 |
+
with open(detailed_output_file, "w", encoding="utf-8") as f:
|
| 172 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
problem_samples = [item for item in detailed_results if not item["correct"]]
|
| 176 |
+
if problem_samples:
|
| 177 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 178 |
+
with open(problem_report_file, "w", encoding="utf-8") as f:
|
| 179 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 180 |
+
|
| 181 |
+
if problem_samples:
|
| 182 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 183 |
+
|
| 184 |
+
return evaluation_result
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
result_file = "model_result.json"
|
| 190 |
+
|
| 191 |
+
try:
|
| 192 |
+
evaluation_result = evaluate_song_emotion_recognition(result_file)
|
| 193 |
+
|
| 194 |
+
except FileNotFoundError:
|
| 195 |
+
print(f"Error: File not found {result_file}")
|
| 196 |
+
except json.JSONDecodeError:
|
| 197 |
+
print(f"Error: {result_file} Invalid format")
|
| 198 |
+
except Exception as e:
|
| 199 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level1/evaluation_SPER.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def extract_emotion_from_output(model_output):
|
| 9 |
+
|
| 10 |
+
if not model_output:
|
| 11 |
+
return None, False, "empty_output"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
valid_emotions = ['neutral', 'calm', 'happy', 'sad', 'angry', 'fearful', 'surprised', 'surprise','disgust']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
patterns = [
|
| 18 |
+
r"['\"]emotion['\"]:\s*['\"](\w+)['\"]",
|
| 19 |
+
r"emotion['\"]?\s*:\s*['\"]?(\w+)['\"]?",
|
| 20 |
+
r"\b(neutral|calm|happy|sad|angry|fearful|surprised|disgust)\b"
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
for pattern in patterns:
|
| 24 |
+
match = re.search(pattern, model_output.lower())
|
| 25 |
+
if match:
|
| 26 |
+
emotion = match.group(1).lower()
|
| 27 |
+
if emotion in valid_emotions:
|
| 28 |
+
return emotion, True, None
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if re.search(r"['\"]emotion['\"]", model_output.lower()):
|
| 32 |
+
return None, False, "invalid_emotion_label"
|
| 33 |
+
elif any(word in model_output.lower() for word in valid_emotions):
|
| 34 |
+
return None, False, "emotion_found_but_not_extracted"
|
| 35 |
+
else:
|
| 36 |
+
return None, False, "no_emotion_pattern"
|
| 37 |
+
|
| 38 |
+
def evaluate_speech_emotion_recognition(result_file_path):
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 43 |
+
results = json.load(f)
|
| 44 |
+
|
| 45 |
+
predictions = []
|
| 46 |
+
ground_truths = []
|
| 47 |
+
detailed_results = []
|
| 48 |
+
extraction_errors = defaultdict(list)
|
| 49 |
+
prediction_errors = defaultdict(list)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
emotion_labels = ['neutral', 'calm', 'happy', 'sad', 'angry', 'fearful', 'surprised', 'disgust']
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
for item in results:
|
| 56 |
+
item_id = item['id']
|
| 57 |
+
model_output = item['model_output']
|
| 58 |
+
gt_label = item['ground_truth'].lower()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
pred_label, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
detailed_item = {
|
| 65 |
+
'id': item_id,
|
| 66 |
+
'model_output': model_output,
|
| 67 |
+
'extracted_prediction': pred_label,
|
| 68 |
+
'ground_truth': gt_label,
|
| 69 |
+
'correct': pred_label == gt_label if pred_label else False,
|
| 70 |
+
'valid': is_valid
|
| 71 |
+
}
|
| 72 |
+
detailed_results.append(detailed_item)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if not is_valid:
|
| 76 |
+
extraction_errors[error_type].append(item_id)
|
| 77 |
+
elif pred_label != gt_label:
|
| 78 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 79 |
+
prediction_errors[error_pattern].append(item_id)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if is_valid:
|
| 83 |
+
predictions.append(pred_label)
|
| 84 |
+
ground_truths.append(gt_label)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
if len(predictions) == 0:
|
| 88 |
+
return {
|
| 89 |
+
'error': 'No valid predictions found',
|
| 90 |
+
'total_samples': len(results),
|
| 91 |
+
'extraction_errors': dict(extraction_errors)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 96 |
+
weighted_f1 = f1_score(ground_truths, predictions, average='weighted')
|
| 97 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro')
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
cm = confusion_matrix(ground_truths, predictions, labels=emotion_labels)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class_report = classification_report(ground_truths, predictions,
|
| 104 |
+
target_names=emotion_labels,
|
| 105 |
+
output_dict=True,
|
| 106 |
+
zero_division=0)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
evaluation_result = {
|
| 110 |
+
'task_info': {
|
| 111 |
+
'task_name': 'speech.emotion.recognition',
|
| 112 |
+
'dataset': 'RAVDESS',
|
| 113 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 114 |
+
'total_samples': len(results),
|
| 115 |
+
'valid_predictions': len(predictions),
|
| 116 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 117 |
+
},
|
| 118 |
+
'metrics': {
|
| 119 |
+
'ACC': round(accuracy, 4),
|
| 120 |
+
'WAF': round(weighted_f1, 4),
|
| 121 |
+
'Macro_F1': round(macro_f1, 4)
|
| 122 |
+
},
|
| 123 |
+
'per_class_metrics': {
|
| 124 |
+
label: {
|
| 125 |
+
'precision': round(class_report[label]['precision'], 4),
|
| 126 |
+
'recall': round(class_report[label]['recall'], 4),
|
| 127 |
+
'f1_score': round(class_report[label]['f1-score'], 4),
|
| 128 |
+
'support': int(class_report[label]['support'])
|
| 129 |
+
} for label in emotion_labels if label in class_report
|
| 130 |
+
},
|
| 131 |
+
'confusion_matrix': {
|
| 132 |
+
'labels': emotion_labels,
|
| 133 |
+
'matrix': cm.tolist()
|
| 134 |
+
},
|
| 135 |
+
'error_analysis': {
|
| 136 |
+
'extraction_errors': {
|
| 137 |
+
error_type: {
|
| 138 |
+
'count': len(sample_ids),
|
| 139 |
+
'sample_ids': sample_ids
|
| 140 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 141 |
+
},
|
| 142 |
+
'prediction_errors': {
|
| 143 |
+
error_pattern: {
|
| 144 |
+
'count': len(sample_ids),
|
| 145 |
+
'sample_ids': sample_ids
|
| 146 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 147 |
+
}
|
| 148 |
+
},
|
| 149 |
+
'distribution': {
|
| 150 |
+
'ground_truth': dict(Counter(ground_truths)),
|
| 151 |
+
'predictions': dict(Counter(predictions))
|
| 152 |
+
}
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
base_name = result_file_path.replace('.json', '')
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 160 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 161 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 165 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 166 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
problem_samples = [item for item in detailed_results if not item['correct']]
|
| 170 |
+
if problem_samples:
|
| 171 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 172 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 173 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if problem_samples:
|
| 177 |
+
print(f"Problematic samples: {len(problem_samples)},see {problem_report_file}")
|
| 178 |
+
|
| 179 |
+
return evaluation_result
|
| 180 |
+
|
| 181 |
+
return evaluation_result
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
if __name__ == "__main__":
|
| 185 |
+
result_file = "model_result.json"
|
| 186 |
+
|
| 187 |
+
try:
|
| 188 |
+
evaluation_result = evaluate_speech_emotion_recognition(result_file)
|
| 189 |
+
|
| 190 |
+
except FileNotFoundError:
|
| 191 |
+
print(f"Error: File not found {result_file}")
|
| 192 |
+
except json.JSONDecodeError:
|
| 193 |
+
print(f"Error: {result_file} Invalid format")
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level2/evaluation_DPTM.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import f1_score, precision_score, recall_score, classification_report
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def extract_techniques_from_output(model_output):
|
| 10 |
+
|
| 11 |
+
if not model_output:
|
| 12 |
+
return [], False, "empty_output"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
valid_techniques = [
|
| 16 |
+
"Appeal to authority", "Appeal to fear/prejudice", "Black-and-white Fallacy/Dictatorship",
|
| 17 |
+
"Causal Oversimplification", "Doubt", "Exaggeration/Minimisation", "Flag-waving",
|
| 18 |
+
"Glittering generalities (Virtue)", "Loaded Language",
|
| 19 |
+
"Misrepresentation of Someone's Position (Straw Man)", "Name calling/Labeling",
|
| 20 |
+
"Obfuscation, Intentional vagueness, Confusion", "Presenting Irrelevant Data (Red Herring)",
|
| 21 |
+
"Reductio ad hitlerum", "Repetition", "Slogans", "Smears", "Thought-terminating cliché",
|
| 22 |
+
"Whataboutism", "Bandwagon", "Transfer", "Appeal to (Strong) Emotions"
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
|
| 27 |
+
if "{'techniques':" in model_output or '{"techniques":' in model_output:
|
| 28 |
+
|
| 29 |
+
cleaned_output = model_output.strip()
|
| 30 |
+
if not cleaned_output.startswith('{'):
|
| 31 |
+
|
| 32 |
+
json_match = re.search(r'\{[^}]*\}', cleaned_output)
|
| 33 |
+
if json_match:
|
| 34 |
+
cleaned_output = json_match.group()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
parsed = ast.literal_eval(cleaned_output)
|
| 39 |
+
except:
|
| 40 |
+
|
| 41 |
+
parsed = json.loads(cleaned_output)
|
| 42 |
+
|
| 43 |
+
if 'techniques' in parsed and isinstance(parsed['techniques'], list):
|
| 44 |
+
techniques = [tech.strip() for tech in parsed['techniques']]
|
| 45 |
+
|
| 46 |
+
valid_techniques_found = [tech for tech in techniques if tech in valid_techniques]
|
| 47 |
+
invalid_techniques = [tech for tech in techniques if tech not in valid_techniques]
|
| 48 |
+
|
| 49 |
+
if invalid_techniques:
|
| 50 |
+
return valid_techniques_found, False, "invalid_technique_labels"
|
| 51 |
+
return valid_techniques_found, True, None
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
found_techniques = []
|
| 55 |
+
for technique in valid_techniques:
|
| 56 |
+
if technique in model_output:
|
| 57 |
+
found_techniques.append(technique)
|
| 58 |
+
|
| 59 |
+
if found_techniques:
|
| 60 |
+
return found_techniques, False, "techniques_found_but_not_properly_formatted"
|
| 61 |
+
|
| 62 |
+
return [], False, "no_techniques_pattern"
|
| 63 |
+
|
| 64 |
+
except Exception as e:
|
| 65 |
+
return [], False, f"parsing_error_{str(e)}"
|
| 66 |
+
|
| 67 |
+
def calculate_multilabel_metrics(y_true_list, y_pred_list, all_labels):
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
y_true_binary = []
|
| 71 |
+
y_pred_binary = []
|
| 72 |
+
|
| 73 |
+
for y_true, y_pred in zip(y_true_list, y_pred_list):
|
| 74 |
+
true_vector = [1 if label in y_true else 0 for label in all_labels]
|
| 75 |
+
pred_vector = [1 if label in y_pred else 0 for label in all_labels]
|
| 76 |
+
y_true_binary.append(true_vector)
|
| 77 |
+
y_pred_binary.append(pred_vector)
|
| 78 |
+
|
| 79 |
+
y_true_binary = np.array(y_true_binary)
|
| 80 |
+
y_pred_binary = np.array(y_pred_binary)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
micro_f1 = f1_score(y_true_binary, y_pred_binary, average='micro')
|
| 84 |
+
macro_f1 = f1_score(y_true_binary, y_pred_binary, average='macro')
|
| 85 |
+
micro_precision = precision_score(y_true_binary, y_pred_binary, average='micro')
|
| 86 |
+
micro_recall = recall_score(y_true_binary, y_pred_binary, average='micro')
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
per_label_f1 = f1_score(y_true_binary, y_pred_binary, average=None)
|
| 90 |
+
per_label_precision = precision_score(y_true_binary, y_pred_binary, average=None)
|
| 91 |
+
per_label_recall = recall_score(y_true_binary, y_pred_binary, average=None)
|
| 92 |
+
|
| 93 |
+
return {
|
| 94 |
+
'micro_f1': micro_f1,
|
| 95 |
+
'macro_f1': macro_f1,
|
| 96 |
+
'micro_precision': micro_precision,
|
| 97 |
+
'micro_recall': micro_recall,
|
| 98 |
+
'per_label_metrics': {
|
| 99 |
+
all_labels[i]: {
|
| 100 |
+
'f1': per_label_f1[i],
|
| 101 |
+
'precision': per_label_precision[i],
|
| 102 |
+
'recall': per_label_recall[i]
|
| 103 |
+
} for i in range(len(all_labels))
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
def evaluate_persuasion_techniques_detection(result_file_path):
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 112 |
+
results = json.load(f)
|
| 113 |
+
|
| 114 |
+
predictions = []
|
| 115 |
+
ground_truths = []
|
| 116 |
+
detailed_results = []
|
| 117 |
+
extraction_errors = defaultdict(list)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
all_techniques = [
|
| 121 |
+
"Appeal to authority", "Appeal to fear/prejudice", "Black-and-white Fallacy/Dictatorship",
|
| 122 |
+
"Causal Oversimplification", "Doubt", "Exaggeration/Minimisation", "Flag-waving",
|
| 123 |
+
"Glittering generalities (Virtue)", "Loaded Language",
|
| 124 |
+
"Misrepresentation of Someone's Position (Straw Man)", "Name calling/Labeling",
|
| 125 |
+
"Obfuscation, Intentional vagueness, Confusion", "Presenting Irrelevant Data (Red Herring)",
|
| 126 |
+
"Reductio ad hitlerum", "Repetition", "Slogans", "Smears", "Thought-terminating cliché",
|
| 127 |
+
"Whataboutism", "Bandwagon", "Transfer", "Appeal to (Strong) Emotions"
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
for item in results:
|
| 132 |
+
item_id = item['id']
|
| 133 |
+
model_output = item['model_output']
|
| 134 |
+
gt_techniques = item['ground_truth']['techniques'] if isinstance(item['ground_truth'], dict) else item['ground_truth']
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
pred_techniques, is_valid, error_type = extract_techniques_from_output(model_output)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
detailed_item = {
|
| 141 |
+
'id': item_id,
|
| 142 |
+
'model_output': model_output,
|
| 143 |
+
'extracted_prediction': pred_techniques,
|
| 144 |
+
'ground_truth': gt_techniques,
|
| 145 |
+
'exact_match': set(pred_techniques) == set(gt_techniques) if is_valid else False,
|
| 146 |
+
'valid': is_valid
|
| 147 |
+
}
|
| 148 |
+
detailed_results.append(detailed_item)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if not is_valid:
|
| 152 |
+
extraction_errors[error_type].append(item_id)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
if is_valid:
|
| 156 |
+
predictions.append(pred_techniques)
|
| 157 |
+
ground_truths.append(gt_techniques)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
if len(predictions) == 0:
|
| 161 |
+
return {
|
| 162 |
+
'error': 'No valid predictions found',
|
| 163 |
+
'total_samples': len(results),
|
| 164 |
+
'extraction_errors': dict(extraction_errors)
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
metrics = calculate_multilabel_metrics(ground_truths, predictions, all_techniques)
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
exact_matches = sum(1 for item in detailed_results if item['exact_match'])
|
| 172 |
+
exact_match_accuracy = exact_matches / len([item for item in detailed_results if item['valid']])
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
all_true_labels = [label for labels in ground_truths for label in labels]
|
| 176 |
+
all_pred_labels = [label for labels in predictions for label in labels]
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
evaluation_result = {
|
| 180 |
+
'task_info': {
|
| 181 |
+
'task_name': 'detection.of.persuasion.techniques.in.memes',
|
| 182 |
+
'dataset': 'SemEval-2021 Task 6',
|
| 183 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 184 |
+
'total_samples': len(results),
|
| 185 |
+
'valid_predictions': len(predictions),
|
| 186 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 187 |
+
},
|
| 188 |
+
'metrics': {
|
| 189 |
+
'Micro_F1': round(metrics['micro_f1'], 4),
|
| 190 |
+
'Macro_F1': round(metrics['macro_f1'], 4),
|
| 191 |
+
'Micro_Precision': round(metrics['micro_precision'], 4),
|
| 192 |
+
'Micro_Recall': round(metrics['micro_recall'], 4),
|
| 193 |
+
'Exact_Match_Accuracy': round(exact_match_accuracy, 4)
|
| 194 |
+
},
|
| 195 |
+
'per_label_metrics': {
|
| 196 |
+
label: {
|
| 197 |
+
'f1': round(metrics['per_label_metrics'][label]['f1'], 4),
|
| 198 |
+
'precision': round(metrics['per_label_metrics'][label]['precision'], 4),
|
| 199 |
+
'recall': round(metrics['per_label_metrics'][label]['recall'], 4)
|
| 200 |
+
} for label in all_techniques
|
| 201 |
+
},
|
| 202 |
+
'error_analysis': {
|
| 203 |
+
'extraction_errors': {
|
| 204 |
+
error_type: {
|
| 205 |
+
'count': len(sample_ids),
|
| 206 |
+
'sample_ids': sample_ids
|
| 207 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 208 |
+
}
|
| 209 |
+
},
|
| 210 |
+
'label_statistics': {
|
| 211 |
+
'ground_truth_distribution': dict(Counter(all_true_labels)),
|
| 212 |
+
'prediction_distribution': dict(Counter(all_pred_labels)),
|
| 213 |
+
'avg_labels_per_sample': {
|
| 214 |
+
'ground_truth': round(np.mean([len(labels) for labels in ground_truths]), 2),
|
| 215 |
+
'predictions': round(np.mean([len(labels) for labels in predictions]), 2)
|
| 216 |
+
}
|
| 217 |
+
}
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
base_name = result_file_path.replace('.json', '')
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 225 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 226 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 230 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 231 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
problem_samples = [item for item in detailed_results if not item['exact_match']]
|
| 235 |
+
if problem_samples:
|
| 236 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 237 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 238 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 242 |
+
print(f"Key metrics: Micro F1={evaluation_result['metrics']['Micro_F1']}, Exact Match Acc={evaluation_result['metrics']['Exact_Match_Accuracy']}")
|
| 243 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 244 |
+
print(f"Results saved to: {eval_output_file}")
|
| 245 |
+
if problem_samples:
|
| 246 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 247 |
+
|
| 248 |
+
return evaluation_result
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
if __name__ == "__main__":
|
| 252 |
+
result_file = "model_result.json"
|
| 253 |
+
|
| 254 |
+
try:
|
| 255 |
+
evaluation_result = evaluate_persuasion_techniques_detection(result_file)
|
| 256 |
+
|
| 257 |
+
except FileNotFoundError:
|
| 258 |
+
print(f"Error: file not found {result_file}")
|
| 259 |
+
except json.JSONDecodeError:
|
| 260 |
+
print(f"Error: invalid format for {result_file}")
|
| 261 |
+
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
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def extract_emotion_intent_from_output(model_output):
|
| 10 |
+
|
| 11 |
+
if not model_output:
|
| 12 |
+
return None, None, False, "empty_output"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
valid_emotions = ['happy', 'surprise', 'sad', 'disgust', 'anger', 'fear', 'neutral']
|
| 16 |
+
valid_intents = ['questioning', 'agreeing', 'acknowledging', 'encouraging',
|
| 17 |
+
'consoling', 'suggesting', 'wishing', 'neutral']
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
|
| 21 |
+
if "{'emotion':" in model_output or '{"emotion":' in model_output:
|
| 22 |
+
|
| 23 |
+
cleaned_output = model_output.strip()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
cleaned_output = re.sub(r"'intent'(\s*,\s*)'", r"'intent':\1'", cleaned_output)
|
| 27 |
+
cleaned_output = re.sub(r'"intent"(\s*,\s*)"', r'"intent":\1"', cleaned_output)
|
| 28 |
+
|
| 29 |
+
if not cleaned_output.startswith('{'):
|
| 30 |
+
|
| 31 |
+
json_match = re.search(r'\{[^}]*\}', cleaned_output)
|
| 32 |
+
if json_match:
|
| 33 |
+
cleaned_output = json_match.group()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
try:
|
| 37 |
+
parsed = ast.literal_eval(cleaned_output)
|
| 38 |
+
except:
|
| 39 |
+
|
| 40 |
+
parsed = json.loads(cleaned_output)
|
| 41 |
+
|
| 42 |
+
if 'emotion' in parsed and 'intent' in parsed:
|
| 43 |
+
emotion = parsed['emotion'].lower().strip()
|
| 44 |
+
intent = parsed['intent'].lower().strip()
|
| 45 |
+
|
| 46 |
+
emotion_valid = emotion in valid_emotions
|
| 47 |
+
intent_valid = intent in valid_intents
|
| 48 |
+
|
| 49 |
+
if emotion_valid and intent_valid:
|
| 50 |
+
return emotion, intent, True, None
|
| 51 |
+
elif not emotion_valid and not intent_valid:
|
| 52 |
+
return emotion, intent, False, "invalid_emotion_and_intent"
|
| 53 |
+
elif not emotion_valid:
|
| 54 |
+
return emotion, intent, False, "invalid_emotion"
|
| 55 |
+
else:
|
| 56 |
+
return emotion, intent, False, "invalid_intent"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
emotion_found = None
|
| 60 |
+
intent_found = None
|
| 61 |
+
|
| 62 |
+
for emotion in valid_emotions:
|
| 63 |
+
if emotion in model_output.lower():
|
| 64 |
+
emotion_found = emotion
|
| 65 |
+
break
|
| 66 |
+
|
| 67 |
+
for intent in valid_intents:
|
| 68 |
+
if intent in model_output.lower():
|
| 69 |
+
intent_found = intent
|
| 70 |
+
break
|
| 71 |
+
|
| 72 |
+
if emotion_found and intent_found:
|
| 73 |
+
return emotion_found, intent_found, False, "labels_found_but_not_properly_formatted"
|
| 74 |
+
elif emotion_found:
|
| 75 |
+
return emotion_found, None, False, "only_emotion_found"
|
| 76 |
+
elif intent_found:
|
| 77 |
+
return None, intent_found, False, "only_intent_found"
|
| 78 |
+
|
| 79 |
+
return None, None, False, "no_labels_pattern"
|
| 80 |
+
|
| 81 |
+
except Exception as e:
|
| 82 |
+
return None, None, False, f"parsing_error_{str(e)}"
|
| 83 |
+
|
| 84 |
+
def parse_ground_truth(ground_truth):
|
| 85 |
+
|
| 86 |
+
if isinstance(ground_truth, dict):
|
| 87 |
+
return ground_truth.get('emotion', '').lower(), ground_truth.get('intent', '').lower()
|
| 88 |
+
elif isinstance(ground_truth, str):
|
| 89 |
+
|
| 90 |
+
cleaned_gt = ground_truth.strip()
|
| 91 |
+
cleaned_gt = re.sub(r"'intent'(\s*,\s*)'", r"'intent':\1'", cleaned_gt)
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
parsed = ast.literal_eval(cleaned_gt)
|
| 95 |
+
return parsed.get('emotion', '').lower(), parsed.get('intent', '').lower()
|
| 96 |
+
except:
|
| 97 |
+
return '', ''
|
| 98 |
+
else:
|
| 99 |
+
return '', ''
|
| 100 |
+
|
| 101 |
+
def evaluate_emotion_based_intent_analysis(result_file_path):
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 106 |
+
results = json.load(f)
|
| 107 |
+
|
| 108 |
+
emotion_predictions = []
|
| 109 |
+
emotion_ground_truths = []
|
| 110 |
+
intent_predictions = []
|
| 111 |
+
intent_ground_truths = []
|
| 112 |
+
detailed_results = []
|
| 113 |
+
extraction_errors = defaultdict(list)
|
| 114 |
+
prediction_errors = defaultdict(list)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
emotion_labels = ['happy', 'surprise', 'sad', 'disgust', 'anger', 'fear', 'neutral']
|
| 118 |
+
intent_labels = ['questioning', 'agreeing', 'acknowledging', 'encouraging',
|
| 119 |
+
'consoling', 'suggesting', 'wishing', 'neutral']
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
for item in results:
|
| 123 |
+
item_id = item['id']
|
| 124 |
+
model_output = item['model_output']
|
| 125 |
+
gt_emotion, gt_intent = parse_ground_truth(item['ground_truth'])
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
pred_emotion, pred_intent, is_valid, error_type = extract_emotion_intent_from_output(model_output)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
detailed_item = {
|
| 132 |
+
'id': item_id,
|
| 133 |
+
'model_output': model_output,
|
| 134 |
+
'extracted_prediction': {
|
| 135 |
+
'emotion': pred_emotion,
|
| 136 |
+
'intent': pred_intent
|
| 137 |
+
},
|
| 138 |
+
'ground_truth': {
|
| 139 |
+
'emotion': gt_emotion,
|
| 140 |
+
'intent': gt_intent
|
| 141 |
+
},
|
| 142 |
+
'emotion_correct': pred_emotion == gt_emotion if pred_emotion else False,
|
| 143 |
+
'intent_correct': pred_intent == gt_intent if pred_intent else False,
|
| 144 |
+
'both_correct': (pred_emotion == gt_emotion and pred_intent == gt_intent) if (pred_emotion and pred_intent) else False,
|
| 145 |
+
'valid': is_valid
|
| 146 |
+
}
|
| 147 |
+
detailed_results.append(detailed_item)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if not is_valid:
|
| 151 |
+
extraction_errors[error_type].append(item_id)
|
| 152 |
+
else:
|
| 153 |
+
if pred_emotion != gt_emotion:
|
| 154 |
+
error_pattern = f"emotion_{gt_emotion}_to_{pred_emotion}"
|
| 155 |
+
prediction_errors[error_pattern].append(item_id)
|
| 156 |
+
if pred_intent != gt_intent:
|
| 157 |
+
error_pattern = f"intent_{gt_intent}_to_{pred_intent}"
|
| 158 |
+
prediction_errors[error_pattern].append(item_id)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if is_valid:
|
| 162 |
+
emotion_predictions.append(pred_emotion)
|
| 163 |
+
emotion_ground_truths.append(gt_emotion)
|
| 164 |
+
intent_predictions.append(pred_intent)
|
| 165 |
+
intent_ground_truths.append(gt_intent)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
if len(emotion_predictions) == 0:
|
| 169 |
+
return {
|
| 170 |
+
'error': 'No valid predictions found',
|
| 171 |
+
'total_samples': len(results),
|
| 172 |
+
'extraction_errors': dict(extraction_errors)
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
emotion_accuracy = accuracy_score(emotion_ground_truths, emotion_predictions)
|
| 177 |
+
emotion_weighted_f1 = f1_score(emotion_ground_truths, emotion_predictions, average='weighted')
|
| 178 |
+
emotion_macro_f1 = f1_score(emotion_ground_truths, emotion_predictions, average='macro')
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
intent_accuracy = accuracy_score(intent_ground_truths, intent_predictions)
|
| 182 |
+
intent_weighted_f1 = f1_score(intent_ground_truths, intent_predictions, average='weighted')
|
| 183 |
+
intent_macro_f1 = f1_score(intent_ground_truths, intent_predictions, average='macro')
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
both_correct = sum(1 for item in detailed_results if item['both_correct'])
|
| 187 |
+
joint_accuracy = both_correct / len([item for item in detailed_results if item['valid']])
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
emotion_cm = confusion_matrix(emotion_ground_truths, emotion_predictions, labels=emotion_labels)
|
| 191 |
+
intent_cm = confusion_matrix(intent_ground_truths, intent_predictions, labels=intent_labels)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
emotion_class_report = classification_report(emotion_ground_truths, emotion_predictions,
|
| 195 |
+
target_names=emotion_labels,
|
| 196 |
+
output_dict=True, zero_division=0)
|
| 197 |
+
intent_class_report = classification_report(intent_ground_truths, intent_predictions,
|
| 198 |
+
target_names=intent_labels,
|
| 199 |
+
output_dict=True, zero_division=0)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
evaluation_result = {
|
| 203 |
+
'task_info': {
|
| 204 |
+
'task_name': 'emotion.based.intent.analysis',
|
| 205 |
+
'dataset': 'MC-EIU',
|
| 206 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 207 |
+
'total_samples': len(results),
|
| 208 |
+
'valid_predictions': len(emotion_predictions),
|
| 209 |
+
'extraction_success_rate': round(len(emotion_predictions) / len(results), 4)
|
| 210 |
+
},
|
| 211 |
+
'metrics': {
|
| 212 |
+
'emotion_metrics': {
|
| 213 |
+
'ACC': round(emotion_accuracy, 4),
|
| 214 |
+
'WAF': round(emotion_weighted_f1, 4),
|
| 215 |
+
'Macro_F1': round(emotion_macro_f1, 4)
|
| 216 |
+
},
|
| 217 |
+
'intent_metrics': {
|
| 218 |
+
'ACC': round(intent_accuracy, 4),
|
| 219 |
+
'WAF': round(intent_weighted_f1, 4),
|
| 220 |
+
'Macro_F1': round(intent_macro_f1, 4)
|
| 221 |
+
},
|
| 222 |
+
'joint_metrics': {
|
| 223 |
+
'Joint_ACC': round(joint_accuracy, 4)
|
| 224 |
+
}
|
| 225 |
+
},
|
| 226 |
+
'per_class_metrics': {
|
| 227 |
+
'emotion': {
|
| 228 |
+
label: {
|
| 229 |
+
'precision': round(emotion_class_report[label]['precision'], 4),
|
| 230 |
+
'recall': round(emotion_class_report[label]['recall'], 4),
|
| 231 |
+
'f1_score': round(emotion_class_report[label]['f1-score'], 4),
|
| 232 |
+
'support': int(emotion_class_report[label]['support'])
|
| 233 |
+
} for label in emotion_labels if label in emotion_class_report
|
| 234 |
+
},
|
| 235 |
+
'intent': {
|
| 236 |
+
label: {
|
| 237 |
+
'precision': round(intent_class_report[label]['precision'], 4),
|
| 238 |
+
'recall': round(intent_class_report[label]['recall'], 4),
|
| 239 |
+
'f1_score': round(intent_class_report[label]['f1-score'], 4),
|
| 240 |
+
'support': int(intent_class_report[label]['support'])
|
| 241 |
+
} for label in intent_labels if label in intent_class_report
|
| 242 |
+
}
|
| 243 |
+
},
|
| 244 |
+
'confusion_matrices': {
|
| 245 |
+
'emotion': {
|
| 246 |
+
'labels': emotion_labels,
|
| 247 |
+
'matrix': emotion_cm.tolist()
|
| 248 |
+
},
|
| 249 |
+
'intent': {
|
| 250 |
+
'labels': intent_labels,
|
| 251 |
+
'matrix': intent_cm.tolist()
|
| 252 |
+
}
|
| 253 |
+
},
|
| 254 |
+
'error_analysis': {
|
| 255 |
+
'extraction_errors': {
|
| 256 |
+
error_type: {
|
| 257 |
+
'count': len(sample_ids),
|
| 258 |
+
'sample_ids': sample_ids
|
| 259 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 260 |
+
},
|
| 261 |
+
'prediction_errors': {
|
| 262 |
+
error_pattern: {
|
| 263 |
+
'count': len(sample_ids),
|
| 264 |
+
'sample_ids': sample_ids
|
| 265 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 266 |
+
}
|
| 267 |
+
},
|
| 268 |
+
'distribution': {
|
| 269 |
+
'emotion': {
|
| 270 |
+
'ground_truth': dict(Counter(emotion_ground_truths)),
|
| 271 |
+
'predictions': dict(Counter(emotion_predictions))
|
| 272 |
+
},
|
| 273 |
+
'intent': {
|
| 274 |
+
'ground_truth': dict(Counter(intent_ground_truths)),
|
| 275 |
+
'predictions': dict(Counter(intent_predictions))
|
| 276 |
+
}
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
base_name = result_file_path.replace('.json', '')
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 285 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 286 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 290 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 291 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
problem_samples = [item for item in detailed_results if not item['both_correct']]
|
| 295 |
+
if problem_samples:
|
| 296 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 297 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 298 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 302 |
+
print(f"Emotion metrics: ACC={evaluation_result['metrics']['emotion_metrics']['ACC']}, WAF={evaluation_result['metrics']['emotion_metrics']['WAF']}")
|
| 303 |
+
print(f"Intent metrics: ACC={evaluation_result['metrics']['intent_metrics']['ACC']}, WAF={evaluation_result['metrics']['intent_metrics']['WAF']}")
|
| 304 |
+
print(f"Joint accuracy: {evaluation_result['metrics']['joint_metrics']['Joint_ACC']}")
|
| 305 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 306 |
+
print(f"Results saved to: {eval_output_file}")
|
| 307 |
+
if problem_samples:
|
| 308 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 309 |
+
|
| 310 |
+
return evaluation_result
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
if __name__ == "__main__":
|
| 314 |
+
result_file = "model_result.json"
|
| 315 |
+
|
| 316 |
+
try:
|
| 317 |
+
evaluation_result = evaluate_emotion_based_intent_analysis(result_file)
|
| 318 |
+
|
| 319 |
+
except FileNotFoundError:
|
| 320 |
+
print(f"Error: file not found {result_file}")
|
| 321 |
+
except json.JSONDecodeError:
|
| 322 |
+
print(f"Error: invalid format for {result_file}")
|
| 323 |
+
except Exception as e:
|
| 324 |
+
print(f"Evaluation failed: {str(e)}")
|
| 325 |
+
|
code/evaluation_code/level2/evaluation_HU.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def extract_humor_label_from_output(model_output):
|
| 9 |
+
|
| 10 |
+
if not model_output:
|
| 11 |
+
return None, False, "empty_output"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
valid_labels = ['true', 'false']
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
cleaned_output = model_output.strip().lower()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
patterns = [
|
| 21 |
+
r'^(true|false)$',
|
| 22 |
+
r'\b(true|false)\b',
|
| 23 |
+
r'answer[:\s]*(true|false)',
|
| 24 |
+
r'final[:\s]*(true|false)',
|
| 25 |
+
r'(true|false)\.?$',
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
for pattern in patterns:
|
| 29 |
+
match = re.search(pattern, cleaned_output)
|
| 30 |
+
if match:
|
| 31 |
+
label = match.group(1).lower()
|
| 32 |
+
if label in valid_labels:
|
| 33 |
+
return label, True, None
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if 'yes' in cleaned_output or 'humor' in cleaned_output:
|
| 37 |
+
if 'no' not in cleaned_output and 'not' not in cleaned_output:
|
| 38 |
+
return 'true', False, "inferred_from_yes_or_humor"
|
| 39 |
+
elif 'no' in cleaned_output or 'not humor' in cleaned_output:
|
| 40 |
+
return 'false', False, "inferred_from_no_or_not_humor"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if any(word in cleaned_output for word in ['true', 'false']):
|
| 44 |
+
return None, False, "label_found_but_not_extracted"
|
| 45 |
+
else:
|
| 46 |
+
return None, False, "no_label_pattern"
|
| 47 |
+
|
| 48 |
+
def evaluate_humor_understanding(result_file_path):
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 53 |
+
results = json.load(f)
|
| 54 |
+
|
| 55 |
+
predictions = []
|
| 56 |
+
ground_truths = []
|
| 57 |
+
detailed_results = []
|
| 58 |
+
extraction_errors = defaultdict(list)
|
| 59 |
+
prediction_errors = defaultdict(list)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
humor_labels = ['false', 'true']
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
for item in results:
|
| 66 |
+
item_id = item['id']
|
| 67 |
+
model_output = item['model_output']
|
| 68 |
+
gt_label = item['ground_truth'].lower().strip()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
pred_label, is_valid, error_type = extract_humor_label_from_output(model_output)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
detailed_item = {
|
| 75 |
+
'id': item_id,
|
| 76 |
+
'model_output': model_output,
|
| 77 |
+
'extracted_prediction': pred_label,
|
| 78 |
+
'ground_truth': gt_label,
|
| 79 |
+
'correct': pred_label == gt_label if pred_label else False,
|
| 80 |
+
'valid': is_valid
|
| 81 |
+
}
|
| 82 |
+
detailed_results.append(detailed_item)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if not is_valid:
|
| 86 |
+
extraction_errors[error_type].append(item_id)
|
| 87 |
+
elif pred_label != gt_label:
|
| 88 |
+
error_pattern = f"{gt_label}_to_{pred_label}"
|
| 89 |
+
prediction_errors[error_pattern].append(item_id)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if pred_label:
|
| 93 |
+
predictions.append(pred_label)
|
| 94 |
+
ground_truths.append(gt_label)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if len(predictions) == 0:
|
| 98 |
+
return {
|
| 99 |
+
'error': 'No valid predictions found',
|
| 100 |
+
'total_samples': len(results),
|
| 101 |
+
'extraction_errors': dict(extraction_errors)
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 106 |
+
weighted_f1 = f1_score(ground_truths, predictions, average='weighted')
|
| 107 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro')
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
cm = confusion_matrix(ground_truths, predictions, labels=humor_labels)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class_report = classification_report(ground_truths, predictions,
|
| 114 |
+
target_names=humor_labels,
|
| 115 |
+
output_dict=True,
|
| 116 |
+
zero_division=0)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
true_positives = cm[1, 1]
|
| 120 |
+
false_positives = cm[0, 1]
|
| 121 |
+
false_negatives = cm[1, 0]
|
| 122 |
+
true_negatives = cm[0, 0]
|
| 123 |
+
|
| 124 |
+
humor_precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
|
| 125 |
+
humor_recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) > 0 else 0
|
| 126 |
+
humor_f1 = 2 * humor_precision * humor_recall / (humor_precision + humor_recall) if (humor_precision + humor_recall) > 0 else 0
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
evaluation_result = {
|
| 130 |
+
'task_info': {
|
| 131 |
+
'task_name': 'humor.understanding',
|
| 132 |
+
'dataset': 'UR-FUNNY',
|
| 133 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 134 |
+
'total_samples': len(results),
|
| 135 |
+
'valid_predictions': len(predictions),
|
| 136 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 137 |
+
},
|
| 138 |
+
'metrics': {
|
| 139 |
+
'ACC': round(accuracy, 4),
|
| 140 |
+
'WAF': round(weighted_f1, 4),
|
| 141 |
+
'Macro_F1': round(macro_f1, 4),
|
| 142 |
+
'Humor_Precision': round(humor_precision, 4),
|
| 143 |
+
'Humor_Recall': round(humor_recall, 4),
|
| 144 |
+
'Humor_F1': round(humor_f1, 4)
|
| 145 |
+
},
|
| 146 |
+
'per_class_metrics': {
|
| 147 |
+
label: {
|
| 148 |
+
'precision': round(class_report[label]['precision'], 4),
|
| 149 |
+
'recall': round(class_report[label]['recall'], 4),
|
| 150 |
+
'f1_score': round(class_report[label]['f1-score'], 4),
|
| 151 |
+
'support': int(class_report[label]['support'])
|
| 152 |
+
} for label in humor_labels if label in class_report
|
| 153 |
+
},
|
| 154 |
+
'confusion_matrix': {
|
| 155 |
+
'labels': humor_labels,
|
| 156 |
+
'matrix': cm.tolist(),
|
| 157 |
+
'detailed': {
|
| 158 |
+
'true_positives': int(true_positives),
|
| 159 |
+
'false_positives': int(false_positives),
|
| 160 |
+
'false_negatives': int(false_negatives),
|
| 161 |
+
'true_negatives': int(true_negatives)
|
| 162 |
+
}
|
| 163 |
+
},
|
| 164 |
+
'error_analysis': {
|
| 165 |
+
'extraction_errors': {
|
| 166 |
+
error_type: {
|
| 167 |
+
'count': len(sample_ids),
|
| 168 |
+
'sample_ids': sample_ids
|
| 169 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 170 |
+
},
|
| 171 |
+
'prediction_errors': {
|
| 172 |
+
error_pattern: {
|
| 173 |
+
'count': len(sample_ids),
|
| 174 |
+
'sample_ids': sample_ids
|
| 175 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 176 |
+
}
|
| 177 |
+
},
|
| 178 |
+
'distribution': {
|
| 179 |
+
'ground_truth': dict(Counter(ground_truths)),
|
| 180 |
+
'predictions': dict(Counter(predictions))
|
| 181 |
+
}
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
base_name = result_file_path.replace('.json', '')
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 189 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 190 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 194 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 195 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
problem_samples = [item for item in detailed_results if not item['correct']]
|
| 199 |
+
if problem_samples:
|
| 200 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 201 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 202 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 206 |
+
print(f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, WAF={evaluation_result['metrics']['WAF']}")
|
| 207 |
+
print(f"Humor detection: Precision={evaluation_result['metrics']['Humor_Precision']}, Recall={evaluation_result['metrics']['Humor_Recall']}, F1={evaluation_result['metrics']['Humor_F1']}")
|
| 208 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 209 |
+
print(f"Results saved to: {eval_output_file}")
|
| 210 |
+
if problem_samples:
|
| 211 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 212 |
+
|
| 213 |
+
return evaluation_result
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
result_file = "model_result.json"
|
| 218 |
+
|
| 219 |
+
try:
|
| 220 |
+
evaluation_result = evaluate_humor_understanding(result_file)
|
| 221 |
+
|
| 222 |
+
except FileNotFoundError:
|
| 223 |
+
print(f"Error: file not found {result_file}")
|
| 224 |
+
except json.JSONDecodeError:
|
| 225 |
+
print(f"Error: invalid format for {result_file}")
|
| 226 |
+
except Exception as e:
|
| 227 |
+
print(f"Evaluation failed: {str(e)}")
|
| 228 |
+
|
code/evaluation_code/level2/evaluation_IAVE.py
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
ONTOLOGY = {
|
| 10 |
+
"Clothing": {
|
| 11 |
+
"Sleeve Style": ["3/4 Sleeve", "Long Sleeve", "Short Sleeve", "Sleeveless", "Strappy"],
|
| 12 |
+
"Neckline": ["Button Down", "Cowl Neck", "Crew Neck", "Halter", "Henley", "Polo", "Scoop Neck", "Square Neck", "Strapless", "Turtleneck", "V-Neck"],
|
| 13 |
+
"Length": ["Capri", "Long Dress/Gown", "Midi", "Mini/Short"],
|
| 14 |
+
"Shoulder Style": ["Cold Shoulder", "Off Shoulder", "One Shoulder"],
|
| 15 |
+
},
|
| 16 |
+
"Footwear": {
|
| 17 |
+
"Shaft Height": ["Ankle Boot", "Bootie", "Knee High", "Mid Calf", "Over The Knee"],
|
| 18 |
+
"Athletic Shoe Style": ["Basketball", "Climbing Shoe", "Cycling", "Golf", "Hiking Boot", "Running Shoe", "Skateboarding Shoe", "Soccer", "Tennis", "Training Shoe", "Volleyball", "Walking"],
|
| 19 |
+
"Boot Style": ["Chelsea", "Combat", "Western/Cowboy", "Motorcycle", "Rain Boots", "Snow Boots"],
|
| 20 |
+
"Heel Height": ["Flat", "High Heel", "Low Heel", "Mid Heel"],
|
| 21 |
+
"Toe Style": ["Pointed Toe", "Round Toe"],
|
| 22 |
+
}
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
def extract_attribute_type_from_prompt(prompt):
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
attribute_patterns = [
|
| 29 |
+
r"What is ([^?]+) of this product",
|
| 30 |
+
r"What ([^?]+) does this product have",
|
| 31 |
+
r"Identify the ([^?]+) of this product"
|
| 32 |
+
]
|
| 33 |
+
|
| 34 |
+
for pattern in attribute_patterns:
|
| 35 |
+
match = re.search(pattern, prompt, re.IGNORECASE)
|
| 36 |
+
if match:
|
| 37 |
+
attribute_type = match.group(1).strip()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
for category in ONTOLOGY.values():
|
| 41 |
+
if attribute_type in category:
|
| 42 |
+
return attribute_type, category[attribute_type]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
for category in ONTOLOGY.values():
|
| 46 |
+
for attr_name, values in category.items():
|
| 47 |
+
if attr_name.lower() in attribute_type.lower() or attribute_type.lower() in attr_name.lower():
|
| 48 |
+
return attr_name, values
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
choices_match = re.search(r"Answer with the option from the given choices directly:([^.]+)", prompt)
|
| 52 |
+
if choices_match:
|
| 53 |
+
choices_text = choices_match.group(1).strip()
|
| 54 |
+
choices = [choice.strip() for choice in choices_text.split(',')]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
for category in ONTOLOGY.values():
|
| 58 |
+
for attr_name, values in category.items():
|
| 59 |
+
if set(choices) == set(values) or len(set(choices) & set(values)) > len(choices) * 0.8:
|
| 60 |
+
return attr_name, values
|
| 61 |
+
|
| 62 |
+
return "Unknown", []
|
| 63 |
+
|
| 64 |
+
def extract_value_from_output(model_output, valid_values):
|
| 65 |
+
|
| 66 |
+
if not model_output:
|
| 67 |
+
return None, False, "empty_output"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
cleaned_output = model_output.strip()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
for value in valid_values:
|
| 74 |
+
if cleaned_output == value:
|
| 75 |
+
return value, True, None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
for value in valid_values:
|
| 79 |
+
if cleaned_output.lower() == value.lower():
|
| 80 |
+
return value, True, None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
for value in valid_values:
|
| 84 |
+
if value in cleaned_output or cleaned_output in value:
|
| 85 |
+
return value, True, None
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
cleaned_normalized = re.sub(r'[^\w\s]', '', cleaned_output.lower())
|
| 89 |
+
for value in valid_values:
|
| 90 |
+
value_normalized = re.sub(r'[^\w\s]', '', value.lower())
|
| 91 |
+
if cleaned_normalized == value_normalized:
|
| 92 |
+
return value, True, None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
for value in valid_values:
|
| 96 |
+
value_words = value.lower().split()
|
| 97 |
+
if all(word in cleaned_output.lower() for word in value_words):
|
| 98 |
+
return value, False, "keyword_match"
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
if any(word in cleaned_output.lower() for value in valid_values for word in value.lower().split()):
|
| 102 |
+
return None, False, "partial_match_failed"
|
| 103 |
+
else:
|
| 104 |
+
return None, False, "no_valid_value_found"
|
| 105 |
+
|
| 106 |
+
def evaluate_implicit_attribute_value_extraction(result_file_path):
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 111 |
+
results = json.load(f)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
attribute_results = defaultdict(lambda: {
|
| 115 |
+
'predictions': [],
|
| 116 |
+
'ground_truths': [],
|
| 117 |
+
'detailed_results': [],
|
| 118 |
+
'extraction_errors': defaultdict(list),
|
| 119 |
+
'prediction_errors': defaultdict(list)
|
| 120 |
+
})
|
| 121 |
+
|
| 122 |
+
overall_predictions = []
|
| 123 |
+
overall_ground_truths = []
|
| 124 |
+
overall_detailed_results = []
|
| 125 |
+
overall_extraction_errors = defaultdict(list)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
for item in results:
|
| 129 |
+
item_id = item['id']
|
| 130 |
+
prompt = item['prompt']
|
| 131 |
+
model_output = item['model_output']
|
| 132 |
+
gt_value = item['ground_truth'].strip()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
attribute_type, valid_values = extract_attribute_type_from_prompt(prompt)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
pred_value, is_valid, error_type = extract_value_from_output(model_output, valid_values)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
detailed_item = {
|
| 142 |
+
'id': item_id,
|
| 143 |
+
'attribute_type': attribute_type,
|
| 144 |
+
'valid_values': valid_values,
|
| 145 |
+
'model_output': model_output,
|
| 146 |
+
'extracted_prediction': pred_value,
|
| 147 |
+
'ground_truth': gt_value,
|
| 148 |
+
'correct': pred_value == gt_value if pred_value else False,
|
| 149 |
+
'valid': is_valid
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
attribute_results[attribute_type]['detailed_results'].append(detailed_item)
|
| 154 |
+
overall_detailed_results.append(detailed_item)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if not is_valid:
|
| 158 |
+
attribute_results[attribute_type]['extraction_errors'][error_type].append(item_id)
|
| 159 |
+
overall_extraction_errors[error_type].append(item_id)
|
| 160 |
+
elif pred_value != gt_value:
|
| 161 |
+
error_pattern = f"{gt_value}_to_{pred_value}"
|
| 162 |
+
attribute_results[attribute_type]['prediction_errors'][error_pattern].append(item_id)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if pred_value:
|
| 166 |
+
attribute_results[attribute_type]['predictions'].append(pred_value)
|
| 167 |
+
attribute_results[attribute_type]['ground_truths'].append(gt_value)
|
| 168 |
+
overall_predictions.append(pred_value)
|
| 169 |
+
overall_ground_truths.append(gt_value)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
if len(overall_predictions) == 0:
|
| 173 |
+
return {
|
| 174 |
+
'error': 'No valid predictions found',
|
| 175 |
+
'total_samples': len(results),
|
| 176 |
+
'extraction_errors': dict(overall_extraction_errors)
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
overall_accuracy = accuracy_score(overall_ground_truths, overall_predictions)
|
| 181 |
+
overall_weighted_f1 = f1_score(overall_ground_truths, overall_predictions, average='weighted')
|
| 182 |
+
overall_macro_f1 = f1_score(overall_ground_truths, overall_predictions, average='macro')
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
attribute_metrics = {}
|
| 186 |
+
for attr_type, attr_data in attribute_results.items():
|
| 187 |
+
if len(attr_data['predictions']) > 0:
|
| 188 |
+
attr_accuracy = accuracy_score(attr_data['ground_truths'], attr_data['predictions'])
|
| 189 |
+
attr_weighted_f1 = f1_score(attr_data['ground_truths'], attr_data['predictions'], average='weighted')
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
all_values = list(set(attr_data['ground_truths'] + attr_data['predictions']))
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
attr_cm = confusion_matrix(attr_data['ground_truths'], attr_data['predictions'], labels=all_values)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
attr_class_report = classification_report(attr_data['ground_truths'], attr_data['predictions'],
|
| 199 |
+
target_names=all_values,
|
| 200 |
+
output_dict=True, zero_division=0)
|
| 201 |
+
|
| 202 |
+
attribute_metrics[attr_type] = {
|
| 203 |
+
'ACC': round(attr_accuracy, 4),
|
| 204 |
+
'WAF': round(attr_weighted_f1, 4),
|
| 205 |
+
'total_samples': len(attr_data['detailed_results']),
|
| 206 |
+
'valid_predictions': len(attr_data['predictions']),
|
| 207 |
+
'per_class_metrics': {
|
| 208 |
+
label: {
|
| 209 |
+
'precision': round(attr_class_report[label]['precision'], 4),
|
| 210 |
+
'recall': round(attr_class_report[label]['recall'], 4),
|
| 211 |
+
'f1_score': round(attr_class_report[label]['f1-score'], 4),
|
| 212 |
+
'support': int(attr_class_report[label]['support'])
|
| 213 |
+
} for label in all_values if label in attr_class_report
|
| 214 |
+
},
|
| 215 |
+
'confusion_matrix': {
|
| 216 |
+
'labels': all_values,
|
| 217 |
+
'matrix': attr_cm.tolist()
|
| 218 |
+
},
|
| 219 |
+
'distribution': {
|
| 220 |
+
'ground_truth': dict(Counter(attr_data['ground_truths'])),
|
| 221 |
+
'predictions': dict(Counter(attr_data['predictions']))
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
evaluation_result = {
|
| 227 |
+
'task_info': {
|
| 228 |
+
'task_name': 'implicit.attribute.value.extraction',
|
| 229 |
+
'dataset': 'ImplicitAVE',
|
| 230 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 231 |
+
'total_samples': len(results),
|
| 232 |
+
'valid_predictions': len(overall_predictions),
|
| 233 |
+
'extraction_success_rate': round(len(overall_predictions) / len(results), 4),
|
| 234 |
+
'attribute_types_count': len(attribute_results)
|
| 235 |
+
},
|
| 236 |
+
'overall_metrics': {
|
| 237 |
+
'ACC': round(overall_accuracy, 4),
|
| 238 |
+
'WAF': round(overall_weighted_f1, 4),
|
| 239 |
+
'Macro_F1': round(overall_macro_f1, 4)
|
| 240 |
+
},
|
| 241 |
+
'attribute_metrics': attribute_metrics,
|
| 242 |
+
'error_analysis': {
|
| 243 |
+
'overall_extraction_errors': {
|
| 244 |
+
error_type: {
|
| 245 |
+
'count': len(sample_ids),
|
| 246 |
+
'sample_ids': sample_ids
|
| 247 |
+
} for error_type, sample_ids in overall_extraction_errors.items()
|
| 248 |
+
}
|
| 249 |
+
},
|
| 250 |
+
'overall_distribution': {
|
| 251 |
+
'ground_truth': dict(Counter(overall_ground_truths)),
|
| 252 |
+
'predictions': dict(Counter(overall_predictions))
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
base_name = result_file_path.replace('.json', '')
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 261 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 262 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 266 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 267 |
+
json.dump(overall_detailed_results, f, ensure_ascii=False, indent=2)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
attribute_detailed_file = f"{base_name}_attribute_detailed_results.json"
|
| 271 |
+
with open(attribute_detailed_file, 'w', encoding='utf-8') as f:
|
| 272 |
+
formatted_attr_results = {}
|
| 273 |
+
for attr_type, attr_data in attribute_results.items():
|
| 274 |
+
formatted_attr_results[attr_type] = {
|
| 275 |
+
'detailed_results': attr_data['detailed_results'],
|
| 276 |
+
'extraction_errors': dict(attr_data['extraction_errors']),
|
| 277 |
+
'prediction_errors': dict(attr_data['prediction_errors'])
|
| 278 |
+
}
|
| 279 |
+
json.dump(formatted_attr_results, f, ensure_ascii=False, indent=2)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
problem_samples = [item for item in overall_detailed_results if not item['correct']]
|
| 283 |
+
if problem_samples:
|
| 284 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 285 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 286 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 290 |
+
print(f"Overall metrics: ACC={evaluation_result['overall_metrics']['ACC']}, WAF={evaluation_result['overall_metrics']['WAF']}")
|
| 291 |
+
print(f"Number of attribute types: {evaluation_result['task_info']['attribute_types_count']}")
|
| 292 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 293 |
+
print(f"Results saved to: {eval_output_file}")
|
| 294 |
+
if problem_samples:
|
| 295 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
print("\nPerformance by attribute type:")
|
| 299 |
+
for attr_type, metrics in attribute_metrics.items():
|
| 300 |
+
print(f" {attr_type}: ACC={metrics['ACC']}, WAF={metrics['WAF']}, Samples={metrics['total_samples']}")
|
| 301 |
+
|
| 302 |
+
return evaluation_result
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
if __name__ == "__main__":
|
| 306 |
+
result_file = "model_result.json"
|
| 307 |
+
|
| 308 |
+
try:
|
| 309 |
+
evaluation_result = evaluate_implicit_attribute_value_extraction(result_file)
|
| 310 |
+
|
| 311 |
+
except FileNotFoundError:
|
| 312 |
+
print(f"Error: file not found {result_file}")
|
| 313 |
+
except json.JSONDecodeError:
|
| 314 |
+
print(f"Error: invalid format for {result_file}")
|
| 315 |
+
except Exception as e:
|
| 316 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level2/evaluation_MABSA.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import f1_score, precision_score, recall_score, classification_report
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def extract_targets_from_prompt(prompt):
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
targets_match = re.search(r"Targets:\s*([^\n]+)", prompt)
|
| 13 |
+
if targets_match:
|
| 14 |
+
targets_text = targets_match.group(1).strip()
|
| 15 |
+
|
| 16 |
+
targets = [target.strip() for target in re.split(r'[,;]', targets_text)]
|
| 17 |
+
return targets
|
| 18 |
+
return []
|
| 19 |
+
|
| 20 |
+
def extract_sentiment_dict_from_output(model_output):
|
| 21 |
+
|
| 22 |
+
if not model_output:
|
| 23 |
+
return {}, False, "empty_output"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
valid_sentiments = ['positive', 'neutral', 'negative']
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
|
| 30 |
+
if "{" in model_output and "}" in model_output:
|
| 31 |
+
|
| 32 |
+
cleaned_output = model_output.strip()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
json_match = re.search(r'\{[^}]*\}', cleaned_output)
|
| 36 |
+
if json_match:
|
| 37 |
+
cleaned_output = json_match.group()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
parsed = ast.literal_eval(cleaned_output)
|
| 42 |
+
except:
|
| 43 |
+
|
| 44 |
+
parsed = json.loads(cleaned_output)
|
| 45 |
+
|
| 46 |
+
if isinstance(parsed, dict):
|
| 47 |
+
|
| 48 |
+
sentiment_dict = {}
|
| 49 |
+
all_valid = True
|
| 50 |
+
|
| 51 |
+
for target, sentiment in parsed.items():
|
| 52 |
+
if isinstance(sentiment, str) and sentiment.lower() in valid_sentiments:
|
| 53 |
+
sentiment_dict[target] = sentiment.lower()
|
| 54 |
+
else:
|
| 55 |
+
all_valid = False
|
| 56 |
+
|
| 57 |
+
if all_valid and len(sentiment_dict) > 0:
|
| 58 |
+
return sentiment_dict, True, None
|
| 59 |
+
else:
|
| 60 |
+
return sentiment_dict, False, "invalid_sentiment_labels"
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
pairs = re.findall(r"([^:{},'\"]+):\s*['\"]?(positive|neutral|negative)['\"]?", model_output.lower())
|
| 65 |
+
if pairs:
|
| 66 |
+
sentiment_dict = {}
|
| 67 |
+
for target, sentiment in pairs:
|
| 68 |
+
target = target.strip(' \'"')
|
| 69 |
+
sentiment_dict[target] = sentiment
|
| 70 |
+
return sentiment_dict, False, "extracted_from_text_patterns"
|
| 71 |
+
|
| 72 |
+
return {}, False, "no_sentiment_pattern"
|
| 73 |
+
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return {}, False, f"parsing_error_{str(e)}"
|
| 76 |
+
|
| 77 |
+
def parse_ground_truth_dict(ground_truth):
|
| 78 |
+
|
| 79 |
+
if isinstance(ground_truth, dict):
|
| 80 |
+
return {k: v.lower() for k, v in ground_truth.items()}
|
| 81 |
+
elif isinstance(ground_truth, str):
|
| 82 |
+
try:
|
| 83 |
+
parsed = ast.literal_eval(ground_truth)
|
| 84 |
+
if isinstance(parsed, dict):
|
| 85 |
+
return {k: v.lower() for k, v in parsed.items()}
|
| 86 |
+
except:
|
| 87 |
+
pass
|
| 88 |
+
return {}
|
| 89 |
+
|
| 90 |
+
def calculate_multimodal_absa_metrics(predictions, ground_truths):
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
all_pred_sentiments = []
|
| 94 |
+
all_true_sentiments = []
|
| 95 |
+
|
| 96 |
+
for pred_pairs, true_pairs in zip(predictions, ground_truths):
|
| 97 |
+
pred_dict = dict(pred_pairs)
|
| 98 |
+
true_dict = dict(true_pairs)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
common_targets = set(pred_dict.keys()) & set(true_dict.keys())
|
| 102 |
+
|
| 103 |
+
for target in common_targets:
|
| 104 |
+
all_pred_sentiments.append(pred_dict[target])
|
| 105 |
+
all_true_sentiments.append(true_dict[target])
|
| 106 |
+
|
| 107 |
+
if len(all_pred_sentiments) == 0:
|
| 108 |
+
return {
|
| 109 |
+
'micro_f1': 0.0,
|
| 110 |
+
'macro_f1': 0.0,
|
| 111 |
+
'micro_precision': 0.0,
|
| 112 |
+
'micro_recall': 0.0,
|
| 113 |
+
'per_class_metrics': {},
|
| 114 |
+
'valid_pairs': 0
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
labels = ['positive', 'neutral', 'negative']
|
| 119 |
+
micro_f1 = f1_score(all_true_sentiments, all_pred_sentiments, average='micro')
|
| 120 |
+
macro_f1 = f1_score(all_true_sentiments, all_pred_sentiments, average='macro')
|
| 121 |
+
micro_precision = precision_score(all_true_sentiments, all_pred_sentiments, average='micro')
|
| 122 |
+
micro_recall = recall_score(all_true_sentiments, all_pred_sentiments, average='micro')
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class_report = classification_report(all_true_sentiments, all_pred_sentiments,
|
| 126 |
+
target_names=labels,
|
| 127 |
+
output_dict=True, zero_division=0)
|
| 128 |
+
|
| 129 |
+
per_class_metrics = {}
|
| 130 |
+
for label in labels:
|
| 131 |
+
if label in class_report:
|
| 132 |
+
per_class_metrics[label] = {
|
| 133 |
+
'precision': class_report[label]['precision'],
|
| 134 |
+
'recall': class_report[label]['recall'],
|
| 135 |
+
'f1_score': class_report[label]['f1-score'],
|
| 136 |
+
'support': int(class_report[label]['support'])
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
return {
|
| 140 |
+
'micro_f1': micro_f1,
|
| 141 |
+
'macro_f1': macro_f1,
|
| 142 |
+
'micro_precision': micro_precision,
|
| 143 |
+
'micro_recall': micro_recall,
|
| 144 |
+
'per_class_metrics': per_class_metrics,
|
| 145 |
+
'valid_pairs': len(all_pred_sentiments)
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
def evaluate_multimodal_aspect_based_sentiment_analysis(result_file_path):
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 153 |
+
results = json.load(f)
|
| 154 |
+
|
| 155 |
+
predictions = []
|
| 156 |
+
ground_truths = []
|
| 157 |
+
detailed_results = []
|
| 158 |
+
extraction_errors = defaultdict(list)
|
| 159 |
+
target_level_errors = defaultdict(list)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
for item in results:
|
| 163 |
+
item_id = item['id']
|
| 164 |
+
prompt = item['prompt']
|
| 165 |
+
model_output = item['model_output']
|
| 166 |
+
gt_dict = parse_ground_truth_dict(item['ground_truth'])
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
targets = extract_targets_from_prompt(prompt)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
pred_dict, is_valid, error_type = extract_sentiment_dict_from_output(model_output)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
pred_pairs = []
|
| 176 |
+
true_pairs = []
|
| 177 |
+
target_results = {}
|
| 178 |
+
|
| 179 |
+
for target in targets:
|
| 180 |
+
if target in gt_dict:
|
| 181 |
+
true_sentiment = gt_dict[target]
|
| 182 |
+
true_pairs.append((target, true_sentiment))
|
| 183 |
+
|
| 184 |
+
if target in pred_dict:
|
| 185 |
+
pred_sentiment = pred_dict[target]
|
| 186 |
+
pred_pairs.append((target, pred_sentiment))
|
| 187 |
+
target_results[target] = {
|
| 188 |
+
'predicted': pred_sentiment,
|
| 189 |
+
'ground_truth': true_sentiment,
|
| 190 |
+
'correct': pred_sentiment == true_sentiment
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
if pred_sentiment != true_sentiment:
|
| 195 |
+
error_pattern = f"{true_sentiment}_to_{pred_sentiment}"
|
| 196 |
+
target_level_errors[error_pattern].append(f"{item_id}_{target}")
|
| 197 |
+
else:
|
| 198 |
+
target_results[target] = {
|
| 199 |
+
'predicted': None,
|
| 200 |
+
'ground_truth': true_sentiment,
|
| 201 |
+
'correct': False
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
detailed_item = {
|
| 206 |
+
'id': item_id,
|
| 207 |
+
'targets': targets,
|
| 208 |
+
'model_output': model_output,
|
| 209 |
+
'extracted_prediction': pred_dict,
|
| 210 |
+
'ground_truth': gt_dict,
|
| 211 |
+
'target_results': target_results,
|
| 212 |
+
'all_targets_correct': all(result['correct'] for result in target_results.values()),
|
| 213 |
+
'valid': is_valid
|
| 214 |
+
}
|
| 215 |
+
detailed_results.append(detailed_item)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
if not is_valid:
|
| 219 |
+
extraction_errors[error_type].append(item_id)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
if len(pred_pairs) > 0:
|
| 223 |
+
predictions.append(pred_pairs)
|
| 224 |
+
ground_truths.append(true_pairs)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if len(predictions) == 0:
|
| 228 |
+
return {
|
| 229 |
+
'error': 'No valid predictions found',
|
| 230 |
+
'total_samples': len(results),
|
| 231 |
+
'extraction_errors': dict(extraction_errors)
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
metrics = calculate_multimodal_absa_metrics(predictions, ground_truths)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
all_correct_samples = sum(1 for item in detailed_results if item['all_targets_correct'])
|
| 239 |
+
sample_level_accuracy = all_correct_samples / len(detailed_results)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
all_true_sentiments = []
|
| 243 |
+
all_pred_sentiments = []
|
| 244 |
+
for item in detailed_results:
|
| 245 |
+
for target, result in item['target_results'].items():
|
| 246 |
+
if result['ground_truth']:
|
| 247 |
+
all_true_sentiments.append(result['ground_truth'])
|
| 248 |
+
if result['predicted']:
|
| 249 |
+
all_pred_sentiments.append(result['predicted'])
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
evaluation_result = {
|
| 253 |
+
'task_info': {
|
| 254 |
+
'task_name': 'multimodal.aspect.based.sentiment.analysis',
|
| 255 |
+
'dataset': 'Twitter2015/2017',
|
| 256 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 257 |
+
'total_samples': len(results),
|
| 258 |
+
'valid_samples': len(predictions),
|
| 259 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4),
|
| 260 |
+
'total_target_pairs': metrics['valid_pairs']
|
| 261 |
+
},
|
| 262 |
+
'metrics': {
|
| 263 |
+
'Micro_F1': round(metrics['micro_f1'], 4),
|
| 264 |
+
'Macro_F1': round(metrics['macro_f1'], 4),
|
| 265 |
+
'Micro_Precision': round(metrics['micro_precision'], 4),
|
| 266 |
+
'Micro_Recall': round(metrics['micro_recall'], 4),
|
| 267 |
+
'Sample_Level_Accuracy': round(sample_level_accuracy, 4)
|
| 268 |
+
},
|
| 269 |
+
'per_class_metrics': {
|
| 270 |
+
label: {
|
| 271 |
+
'precision': round(metrics['per_class_metrics'][label]['precision'], 4),
|
| 272 |
+
'recall': round(metrics['per_class_metrics'][label]['recall'], 4),
|
| 273 |
+
'f1_score': round(metrics['per_class_metrics'][label]['f1_score'], 4),
|
| 274 |
+
'support': metrics['per_class_metrics'][label]['support']
|
| 275 |
+
} for label in metrics['per_class_metrics']
|
| 276 |
+
},
|
| 277 |
+
'error_analysis': {
|
| 278 |
+
'extraction_errors': {
|
| 279 |
+
error_type: {
|
| 280 |
+
'count': len(sample_ids),
|
| 281 |
+
'sample_ids': sample_ids
|
| 282 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 283 |
+
},
|
| 284 |
+
'target_level_errors': {
|
| 285 |
+
error_pattern: {
|
| 286 |
+
'count': len(target_ids),
|
| 287 |
+
'target_ids': target_ids
|
| 288 |
+
} for error_pattern, target_ids in target_level_errors.items()
|
| 289 |
+
}
|
| 290 |
+
},
|
| 291 |
+
'distribution': {
|
| 292 |
+
'ground_truth_sentiments': dict(Counter(all_true_sentiments)),
|
| 293 |
+
'predicted_sentiments': dict(Counter(all_pred_sentiments))
|
| 294 |
+
}
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
base_name = result_file_path.replace('.json', '')
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 302 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 303 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 307 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 308 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
problem_samples = [item for item in detailed_results if not item['all_targets_correct']]
|
| 312 |
+
if problem_samples:
|
| 313 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 314 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 315 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 319 |
+
print(f"Key metrics: Micro F1={evaluation_result['metrics']['Micro_F1']}, Sample-level Accuracy={evaluation_result['metrics']['Sample_Level_Accuracy']}")
|
| 320 |
+
print(f"Number of target pairs: {evaluation_result['task_info']['total_target_pairs']}")
|
| 321 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 322 |
+
print(f"Results saved to: {eval_output_file}")
|
| 323 |
+
if problem_samples:
|
| 324 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 325 |
+
|
| 326 |
+
return evaluation_result
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
if __name__ == "__main__":
|
| 330 |
+
result_file = "model_result.json"
|
| 331 |
+
|
| 332 |
+
try:
|
| 333 |
+
evaluation_result = evaluate_multimodal_aspect_based_sentiment_analysis(result_file)
|
| 334 |
+
|
| 335 |
+
except FileNotFoundError:
|
| 336 |
+
print(f"Error: file not found {result_file}")
|
| 337 |
+
except json.JSONDecodeError:
|
| 338 |
+
print(f"Error: invalid format for {result_file}")
|
| 339 |
+
except Exception as e:
|
| 340 |
+
print(f"Evaluation failed: {str(e)}")
|
| 341 |
+
|
code/evaluation_code/level2/evaluation_MDER.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def extract_emotion_from_output(model_output):
|
| 10 |
+
|
| 11 |
+
if not model_output:
|
| 12 |
+
return None, False, "empty_output"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
valid_emotions = ['neutral', 'surprise', 'fear', 'sadness', 'joy', 'disgust', 'anger']
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
|
| 19 |
+
if "{'emotion':" in model_output or '{"emotion":' in model_output:
|
| 20 |
+
|
| 21 |
+
cleaned_output = model_output.strip()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
json_match = re.search(r'\{[^}]*\}', cleaned_output)
|
| 25 |
+
if json_match:
|
| 26 |
+
cleaned_output = json_match.group()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
parsed = ast.literal_eval(cleaned_output)
|
| 31 |
+
except:
|
| 32 |
+
|
| 33 |
+
parsed = json.loads(cleaned_output)
|
| 34 |
+
|
| 35 |
+
if 'emotion' in parsed and isinstance(parsed['emotion'], str):
|
| 36 |
+
emotion = parsed['emotion'].lower().strip()
|
| 37 |
+
if emotion in valid_emotions:
|
| 38 |
+
return emotion, True, None
|
| 39 |
+
else:
|
| 40 |
+
return emotion, False, "invalid_emotion_label"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
cleaned_output = model_output.lower().strip()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
for emotion in valid_emotions:
|
| 47 |
+
if cleaned_output == emotion:
|
| 48 |
+
return emotion, True, None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
for emotion in valid_emotions:
|
| 52 |
+
if emotion in cleaned_output:
|
| 53 |
+
return emotion, False, "emotion_found_but_not_properly_formatted"
|
| 54 |
+
|
| 55 |
+
return None, False, "no_valid_emotion_found"
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
return None, False, f"parsing_error_{str(e)}"
|
| 59 |
+
|
| 60 |
+
def evaluate_multiparty_dialogue_emotion_recognition(result_file_path):
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 65 |
+
results = json.load(f)
|
| 66 |
+
|
| 67 |
+
predictions = []
|
| 68 |
+
ground_truths = []
|
| 69 |
+
detailed_results = []
|
| 70 |
+
extraction_errors = defaultdict(list)
|
| 71 |
+
prediction_errors = defaultdict(list)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
emotion_labels = ['neutral', 'surprise', 'fear', 'sadness', 'joy', 'disgust', 'anger']
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
for item in results:
|
| 78 |
+
item_id = item['id']
|
| 79 |
+
model_output = item['model_output']
|
| 80 |
+
gt_emotion = item['ground_truth'].lower().strip()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
pred_emotion, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
detailed_item = {
|
| 87 |
+
'id': item_id,
|
| 88 |
+
'model_output': model_output,
|
| 89 |
+
'extracted_prediction': pred_emotion,
|
| 90 |
+
'ground_truth': gt_emotion,
|
| 91 |
+
'correct': pred_emotion == gt_emotion if pred_emotion else False,
|
| 92 |
+
'valid': is_valid
|
| 93 |
+
}
|
| 94 |
+
detailed_results.append(detailed_item)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
if not is_valid:
|
| 98 |
+
extraction_errors[error_type].append(item_id)
|
| 99 |
+
elif pred_emotion != gt_emotion:
|
| 100 |
+
error_pattern = f"{gt_emotion}_to_{pred_emotion}"
|
| 101 |
+
prediction_errors[error_pattern].append(item_id)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
if is_valid:
|
| 105 |
+
predictions.append(pred_emotion)
|
| 106 |
+
ground_truths.append(gt_emotion)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if len(predictions) == 0:
|
| 110 |
+
return {
|
| 111 |
+
'error': 'No valid predictions found',
|
| 112 |
+
'total_samples': len(results),
|
| 113 |
+
'extraction_errors': dict(extraction_errors)
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 118 |
+
weighted_f1 = f1_score(ground_truths, predictions, average='weighted')
|
| 119 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro')
|
| 120 |
+
micro_f1 = f1_score(ground_truths, predictions, average='micro')
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
cm = confusion_matrix(ground_truths, predictions, labels=emotion_labels)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class_report = classification_report(ground_truths, predictions,
|
| 127 |
+
target_names=emotion_labels,
|
| 128 |
+
output_dict=True,
|
| 129 |
+
zero_division=0)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
per_class_metrics = {}
|
| 133 |
+
for i, label in enumerate(emotion_labels):
|
| 134 |
+
if label in class_report:
|
| 135 |
+
true_positives = cm[i, i]
|
| 136 |
+
false_positives = np.sum(cm[:, i]) - true_positives
|
| 137 |
+
false_negatives = np.sum(cm[i, :]) - true_positives
|
| 138 |
+
|
| 139 |
+
per_class_metrics[label] = {
|
| 140 |
+
'precision': round(class_report[label]['precision'], 4),
|
| 141 |
+
'recall': round(class_report[label]['recall'], 4),
|
| 142 |
+
'f1_score': round(class_report[label]['f1-score'], 4),
|
| 143 |
+
'support': int(class_report[label]['support']),
|
| 144 |
+
'true_positives': int(true_positives),
|
| 145 |
+
'false_positives': int(false_positives),
|
| 146 |
+
'false_negatives': int(false_negatives)
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
evaluation_result = {
|
| 151 |
+
'task_info': {
|
| 152 |
+
'task_name': 'multiparty.dialogue.emotion.recognition',
|
| 153 |
+
'dataset': 'MELD',
|
| 154 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 155 |
+
'total_samples': len(results),
|
| 156 |
+
'valid_predictions': len(predictions),
|
| 157 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 158 |
+
},
|
| 159 |
+
'metrics': {
|
| 160 |
+
'ACC': round(accuracy, 4),
|
| 161 |
+
'WAF': round(weighted_f1, 4),
|
| 162 |
+
'Macro_F1': round(macro_f1, 4),
|
| 163 |
+
'Micro_F1': round(micro_f1, 4)
|
| 164 |
+
},
|
| 165 |
+
'per_class_metrics': per_class_metrics,
|
| 166 |
+
'confusion_matrix': {
|
| 167 |
+
'labels': emotion_labels,
|
| 168 |
+
'matrix': cm.tolist(),
|
| 169 |
+
'normalized': (cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]).round(4).tolist()
|
| 170 |
+
},
|
| 171 |
+
'error_analysis': {
|
| 172 |
+
'extraction_errors': {
|
| 173 |
+
error_type: {
|
| 174 |
+
'count': len(sample_ids),
|
| 175 |
+
'sample_ids': sample_ids
|
| 176 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 177 |
+
},
|
| 178 |
+
'prediction_errors': {
|
| 179 |
+
error_pattern: {
|
| 180 |
+
'count': len(sample_ids),
|
| 181 |
+
'sample_ids': sample_ids
|
| 182 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 183 |
+
}
|
| 184 |
+
},
|
| 185 |
+
'distribution': {
|
| 186 |
+
'ground_truth': dict(Counter(ground_truths)),
|
| 187 |
+
'predictions': dict(Counter(predictions))
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
confusion_pairs = []
|
| 193 |
+
for i, label1 in enumerate(emotion_labels):
|
| 194 |
+
for j, label2 in enumerate(emotion_labels):
|
| 195 |
+
if i != j and cm[i, j] > 0:
|
| 196 |
+
confusion_pairs.append({
|
| 197 |
+
'true_emotion': label1,
|
| 198 |
+
'predicted_emotion': label2,
|
| 199 |
+
'count': int(cm[i, j]),
|
| 200 |
+
'percentage': round(cm[i, j] / np.sum(cm[i, :]) * 100, 2)
|
| 201 |
+
})
|
| 202 |
+
|
| 203 |
+
confusion_pairs.sort(key=lambda x: x['count'], reverse=True)
|
| 204 |
+
evaluation_result['emotion_confusion_analysis'] = {
|
| 205 |
+
'most_confused_pairs': confusion_pairs[:10]
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
base_name = result_file_path.replace('.json', '')
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 213 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 214 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 218 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 219 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
problem_samples = [item for item in detailed_results if not item['correct']]
|
| 223 |
+
if problem_samples:
|
| 224 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 225 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 226 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 230 |
+
print(f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, WAF={evaluation_result['metrics']['WAF']}")
|
| 231 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 232 |
+
print(f"Results saved to: {eval_output_file}")
|
| 233 |
+
if problem_samples:
|
| 234 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
if confusion_pairs:
|
| 238 |
+
print("\nMost confusable emotion pairs:")
|
| 239 |
+
for pair in confusion_pairs[:5]:
|
| 240 |
+
print(f" {pair['true_emotion']} → {pair['predicted_emotion']}: {pair['count']} times ({pair['percentage']}%)")
|
| 241 |
+
|
| 242 |
+
return evaluation_result
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
result_file = "model_result.json"
|
| 247 |
+
|
| 248 |
+
try:
|
| 249 |
+
evaluation_result = evaluate_multiparty_dialogue_emotion_recognition(result_file)
|
| 250 |
+
|
| 251 |
+
except FileNotFoundError:
|
| 252 |
+
print(f"Error: file not found {result_file}")
|
| 253 |
+
except json.JSONDecodeError:
|
| 254 |
+
print(f"Error: invalid format for {result_file}")
|
| 255 |
+
except Exception as e:
|
| 256 |
+
print(f"Evaluation failed: {str(e)}")
|
| 257 |
+
|
code/evaluation_code/level2/evaluation_MQE.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import f1_score, precision_score, recall_score
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def parse_quintuple_list(output_text):
|
| 10 |
+
|
| 11 |
+
if not output_text:
|
| 12 |
+
return [], False, "empty_output"
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
|
| 16 |
+
cleaned_output = output_text.strip()
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
list_match = re.search(r'\[(.*)\]', cleaned_output, re.DOTALL)
|
| 20 |
+
if not list_match:
|
| 21 |
+
return [], False, "no_list_structure"
|
| 22 |
+
|
| 23 |
+
list_content = list_match.group(1).strip()
|
| 24 |
+
if not list_content:
|
| 25 |
+
return [], True, None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
try:
|
| 29 |
+
full_list = ast.literal_eval('[' + list_content + ']')
|
| 30 |
+
except:
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
fixed_content = list_content
|
| 34 |
+
|
| 35 |
+
fixed_content = re.sub(r'"([^"]*)"', r"'\1'", fixed_content)
|
| 36 |
+
|
| 37 |
+
try:
|
| 38 |
+
full_list = ast.literal_eval('[' + fixed_content + ']')
|
| 39 |
+
except:
|
| 40 |
+
|
| 41 |
+
return parse_tuples_manually(list_content)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
quintuples = []
|
| 45 |
+
for item in full_list:
|
| 46 |
+
if isinstance(item, (tuple, list)) and len(item) >= 5:
|
| 47 |
+
|
| 48 |
+
quintuple = tuple(str(element).strip() for element in item[:5])
|
| 49 |
+
quintuples.append(quintuple)
|
| 50 |
+
else:
|
| 51 |
+
return [], False, "invalid_tuple_structure"
|
| 52 |
+
|
| 53 |
+
return quintuples, True, None
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
return [], False, f"parsing_error_{str(e)}"
|
| 57 |
+
|
| 58 |
+
def parse_tuples_manually(list_content):
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
|
| 62 |
+
tuple_pattern = r'\(\s*([^)]+)\s*\)'
|
| 63 |
+
matches = re.findall(tuple_pattern, list_content)
|
| 64 |
+
|
| 65 |
+
quintuples = []
|
| 66 |
+
for match in matches:
|
| 67 |
+
|
| 68 |
+
elements = []
|
| 69 |
+
current_element = ""
|
| 70 |
+
in_quotes = False
|
| 71 |
+
quote_char = None
|
| 72 |
+
|
| 73 |
+
i = 0
|
| 74 |
+
while i < len(match):
|
| 75 |
+
char = match[i]
|
| 76 |
+
|
| 77 |
+
if char in ['"', "'"] and (i == 0 or match[i-1] != '\\'):
|
| 78 |
+
if not in_quotes:
|
| 79 |
+
in_quotes = True
|
| 80 |
+
quote_char = char
|
| 81 |
+
elif char == quote_char:
|
| 82 |
+
in_quotes = False
|
| 83 |
+
quote_char = None
|
| 84 |
+
elif char == ',' and not in_quotes:
|
| 85 |
+
elements.append(current_element.strip().strip('"\''))
|
| 86 |
+
current_element = ""
|
| 87 |
+
i += 1
|
| 88 |
+
continue
|
| 89 |
+
|
| 90 |
+
current_element += char
|
| 91 |
+
i += 1
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if current_element:
|
| 95 |
+
elements.append(current_element.strip().strip('"\''))
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if len(elements) >= 5:
|
| 99 |
+
quintuple = tuple(elements[:5])
|
| 100 |
+
quintuples.append(quintuple)
|
| 101 |
+
|
| 102 |
+
return quintuples, len(quintuples) > 0, "manual_parsing" if len(quintuples) > 0 else "manual_parsing_failed"
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
return [], False, f"manual_parsing_error_{str(e)}"
|
| 106 |
+
|
| 107 |
+
def normalize_quintuple(quintuple):
|
| 108 |
+
|
| 109 |
+
holder, target, aspect, opinion, sentiment = quintuple
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
sentiment_lower = sentiment.lower().strip()
|
| 113 |
+
if sentiment_lower in ['positive', 'pos']:
|
| 114 |
+
sentiment = 'positive'
|
| 115 |
+
elif sentiment_lower in ['negative', 'neg']:
|
| 116 |
+
sentiment = 'negative'
|
| 117 |
+
elif sentiment_lower in ['neutral', 'neu']:
|
| 118 |
+
sentiment = 'neutral'
|
| 119 |
+
else:
|
| 120 |
+
sentiment = sentiment_lower
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
holder = holder.strip()
|
| 124 |
+
target = target.strip()
|
| 125 |
+
aspect = aspect.strip()
|
| 126 |
+
opinion = opinion.strip()
|
| 127 |
+
|
| 128 |
+
return (holder, target, aspect, opinion, sentiment)
|
| 129 |
+
|
| 130 |
+
def calculate_quintuple_metrics(predictions, ground_truths):
|
| 131 |
+
|
| 132 |
+
total_pred = 0
|
| 133 |
+
total_true = 0
|
| 134 |
+
total_correct = 0
|
| 135 |
+
|
| 136 |
+
exact_matches = 0
|
| 137 |
+
partial_matches = {'holder': 0, 'target': 0, 'aspect': 0, 'opinion': 0, 'sentiment': 0}
|
| 138 |
+
|
| 139 |
+
for pred_list, true_list in zip(predictions, ground_truths):
|
| 140 |
+
|
| 141 |
+
pred_normalized = [normalize_quintuple(q) for q in pred_list]
|
| 142 |
+
true_normalized = [normalize_quintuple(q) for q in true_list]
|
| 143 |
+
|
| 144 |
+
total_pred += len(pred_normalized)
|
| 145 |
+
total_true += len(true_normalized)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
pred_set = set(pred_normalized)
|
| 149 |
+
true_set = set(true_normalized)
|
| 150 |
+
exact_matches += len(pred_set & true_set)
|
| 151 |
+
total_correct += len(pred_set & true_set)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
for pred_q in pred_normalized:
|
| 155 |
+
for true_q in true_normalized:
|
| 156 |
+
if pred_q == true_q:
|
| 157 |
+
continue
|
| 158 |
+
for i, (field_name, pred_field, true_field) in enumerate(
|
| 159 |
+
zip(['holder', 'target', 'aspect', 'opinion', 'sentiment'], pred_q, true_q)):
|
| 160 |
+
if pred_field.lower() == true_field.lower():
|
| 161 |
+
partial_matches[field_name] += 1
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
precision = total_correct / total_pred if total_pred > 0 else 0
|
| 165 |
+
recall = total_correct / total_true if total_true > 0 else 0
|
| 166 |
+
f1 = 2 * precision * recall / (precision + recall) if (precision + recall) > 0 else 0
|
| 167 |
+
|
| 168 |
+
return {
|
| 169 |
+
'micro_f1': f1,
|
| 170 |
+
'micro_precision': precision,
|
| 171 |
+
'micro_recall': recall,
|
| 172 |
+
'exact_matches': exact_matches,
|
| 173 |
+
'total_predicted': total_pred,
|
| 174 |
+
'total_ground_truth': total_true,
|
| 175 |
+
'partial_matches': partial_matches
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
def evaluate_multimodal_quintuple_extraction(result_file_path):
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 183 |
+
results = json.load(f)
|
| 184 |
+
|
| 185 |
+
predictions = []
|
| 186 |
+
ground_truths = []
|
| 187 |
+
detailed_results = []
|
| 188 |
+
extraction_errors = defaultdict(list)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
for item in results:
|
| 192 |
+
item_id = item['id']
|
| 193 |
+
model_output = item['model_output']
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
if isinstance(item['ground_truth'], str):
|
| 197 |
+
gt_quintuples, gt_valid, gt_error = parse_quintuple_list(item['ground_truth'])
|
| 198 |
+
elif isinstance(item['ground_truth'], list):
|
| 199 |
+
gt_quintuples = []
|
| 200 |
+
for gt_item in item['ground_truth']:
|
| 201 |
+
if isinstance(gt_item, (tuple, list)) and len(gt_item) >= 5:
|
| 202 |
+
gt_quintuples.append(tuple(str(element).strip() for element in gt_item[:5]))
|
| 203 |
+
gt_valid = True
|
| 204 |
+
gt_error = None
|
| 205 |
+
else:
|
| 206 |
+
gt_quintuples = []
|
| 207 |
+
gt_valid = False
|
| 208 |
+
gt_error = "invalid_ground_truth_format"
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
pred_quintuples, pred_valid, pred_error = parse_quintuple_list(model_output)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
detailed_item = {
|
| 215 |
+
'id': item_id,
|
| 216 |
+
'model_output': model_output,
|
| 217 |
+
'extracted_prediction': pred_quintuples,
|
| 218 |
+
'ground_truth': gt_quintuples,
|
| 219 |
+
'prediction_count': len(pred_quintuples),
|
| 220 |
+
'ground_truth_count': len(gt_quintuples),
|
| 221 |
+
'exact_matches': len(set(pred_quintuples) & set(gt_quintuples)) if pred_valid and gt_valid else 0,
|
| 222 |
+
'valid': pred_valid and gt_valid
|
| 223 |
+
}
|
| 224 |
+
detailed_results.append(detailed_item)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if not pred_valid:
|
| 228 |
+
extraction_errors[pred_error].append(item_id)
|
| 229 |
+
elif not gt_valid:
|
| 230 |
+
extraction_errors[f"gt_{gt_error}"].append(item_id)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
if pred_valid and gt_valid:
|
| 234 |
+
predictions.append(pred_quintuples)
|
| 235 |
+
ground_truths.append(gt_quintuples)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
if len(predictions) == 0:
|
| 239 |
+
return {
|
| 240 |
+
'error': 'No valid predictions found',
|
| 241 |
+
'total_samples': len(results),
|
| 242 |
+
'extraction_errors': dict(extraction_errors)
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
metrics = calculate_quintuple_metrics(predictions, ground_truths)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
sample_with_predictions = sum(1 for item in detailed_results if item['prediction_count'] > 0)
|
| 250 |
+
sample_with_correct_predictions = sum(1 for item in detailed_results if item['exact_matches'] > 0)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
all_pred_holders = []
|
| 254 |
+
all_pred_targets = []
|
| 255 |
+
all_pred_sentiments = []
|
| 256 |
+
all_true_holders = []
|
| 257 |
+
all_true_targets = []
|
| 258 |
+
all_true_sentiments = []
|
| 259 |
+
|
| 260 |
+
for pred_list, true_list in zip(predictions, ground_truths):
|
| 261 |
+
for quintuple in pred_list:
|
| 262 |
+
all_pred_holders.append(quintuple[0])
|
| 263 |
+
all_pred_targets.append(quintuple[1])
|
| 264 |
+
all_pred_sentiments.append(quintuple[4])
|
| 265 |
+
|
| 266 |
+
for quintuple in true_list:
|
| 267 |
+
all_true_holders.append(quintuple[0])
|
| 268 |
+
all_true_targets.append(quintuple[1])
|
| 269 |
+
all_true_sentiments.append(quintuple[4])
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
evaluation_result = {
|
| 273 |
+
'task_info': {
|
| 274 |
+
'task_name': 'multimodal.quintuple.extraction',
|
| 275 |
+
'dataset': 'PanoSent',
|
| 276 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 277 |
+
'total_samples': len(results),
|
| 278 |
+
'valid_samples': len(predictions),
|
| 279 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 280 |
+
},
|
| 281 |
+
'metrics': {
|
| 282 |
+
'Micro_F1': round(metrics['micro_f1'], 4),
|
| 283 |
+
'Micro_Precision': round(metrics['micro_precision'], 4),
|
| 284 |
+
'Micro_Recall': round(metrics['micro_recall'], 4),
|
| 285 |
+
'Exact_Matches': metrics['exact_matches'],
|
| 286 |
+
'Total_Predicted': metrics['total_predicted'],
|
| 287 |
+
'Total_Ground_Truth': metrics['total_ground_truth']
|
| 288 |
+
},
|
| 289 |
+
'sample_level_stats': {
|
| 290 |
+
'samples_with_predictions': sample_with_predictions,
|
| 291 |
+
'samples_with_correct_predictions': sample_with_correct_predictions,
|
| 292 |
+
'avg_predictions_per_sample': round(metrics['total_predicted'] / len(predictions), 2) if len(predictions) > 0 else 0,
|
| 293 |
+
'avg_ground_truth_per_sample': round(metrics['total_ground_truth'] / len(predictions), 2) if len(predictions) > 0 else 0
|
| 294 |
+
},
|
| 295 |
+
'partial_match_analysis': {
|
| 296 |
+
field: {
|
| 297 |
+
'matches': metrics['partial_matches'][field],
|
| 298 |
+
'rate': round(metrics['partial_matches'][field] / max(metrics['total_predicted'], 1), 4)
|
| 299 |
+
} for field in ['holder', 'target', 'aspect', 'opinion', 'sentiment']
|
| 300 |
+
},
|
| 301 |
+
'error_analysis': {
|
| 302 |
+
'extraction_errors': {
|
| 303 |
+
error_type: {
|
| 304 |
+
'count': len(sample_ids),
|
| 305 |
+
'sample_ids': sample_ids
|
| 306 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 307 |
+
}
|
| 308 |
+
},
|
| 309 |
+
'distribution': {
|
| 310 |
+
'holders': {
|
| 311 |
+
'ground_truth': dict(Counter(all_true_holders)),
|
| 312 |
+
'predictions': dict(Counter(all_pred_holders))
|
| 313 |
+
},
|
| 314 |
+
'targets': {
|
| 315 |
+
'ground_truth': dict(Counter(all_true_targets)),
|
| 316 |
+
'predictions': dict(Counter(all_pred_targets))
|
| 317 |
+
},
|
| 318 |
+
'sentiments': {
|
| 319 |
+
'ground_truth': dict(Counter(all_true_sentiments)),
|
| 320 |
+
'predictions': dict(Counter(all_pred_sentiments))
|
| 321 |
+
}
|
| 322 |
+
}
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
base_name = result_file_path.replace('.json', '')
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 330 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 331 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 335 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 336 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
problem_samples = [item for item in detailed_results if item['exact_matches'] == 0 and item['ground_truth_count'] > 0]
|
| 340 |
+
if problem_samples:
|
| 341 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 342 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 343 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 347 |
+
print(f"Key metric: Micro F1={evaluation_result['metrics']['Micro_F1']}")
|
| 348 |
+
print(f"Exact matches: {evaluation_result['metrics']['Exact_Matches']}/{evaluation_result['metrics']['Total_Ground_Truth']}")
|
| 349 |
+
print(f"Average predictions per sample: {evaluation_result['sample_level_stats']['avg_predictions_per_sample']}")
|
| 350 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 351 |
+
print(f"Results saved to: {eval_output_file}")
|
| 352 |
+
if problem_samples:
|
| 353 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 354 |
+
|
| 355 |
+
return evaluation_result
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
if __name__ == "__main__":
|
| 359 |
+
result_file = "model_result.json"
|
| 360 |
+
|
| 361 |
+
try:
|
| 362 |
+
evaluation_result = evaluate_multimodal_quintuple_extraction(result_file)
|
| 363 |
+
|
| 364 |
+
except FileNotFoundError:
|
| 365 |
+
print(f"Error: file not found {result_file}")
|
| 366 |
+
except json.JSONDecodeError:
|
| 367 |
+
print(f"Error: invalid format for {result_file}")
|
| 368 |
+
except Exception as e:
|
| 369 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level2/evaluation_MSD.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def extract_stance_from_output(model_output):
|
| 10 |
+
|
| 11 |
+
if not model_output:
|
| 12 |
+
return None, False, "empty_output"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
valid_stances = ['support', 'refute', 'comment', 'unrelated']
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
|
| 19 |
+
if "{'stance':" in model_output or '{"stance":' in model_output:
|
| 20 |
+
|
| 21 |
+
cleaned_output = model_output.strip()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
json_match = re.search(r'\{[^}]*\}', cleaned_output)
|
| 25 |
+
if json_match:
|
| 26 |
+
cleaned_output = json_match.group()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
parsed = ast.literal_eval(cleaned_output)
|
| 31 |
+
except:
|
| 32 |
+
|
| 33 |
+
parsed = json.loads(cleaned_output)
|
| 34 |
+
|
| 35 |
+
if 'stance' in parsed and isinstance(parsed['stance'], str):
|
| 36 |
+
stance = parsed['stance'].lower().strip()
|
| 37 |
+
if stance in valid_stances:
|
| 38 |
+
return stance, True, None
|
| 39 |
+
else:
|
| 40 |
+
return stance, False, "invalid_stance_label"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
cleaned_output = model_output.lower().strip()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
for stance in valid_stances:
|
| 47 |
+
if cleaned_output == stance:
|
| 48 |
+
return stance, True, None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
for stance in valid_stances:
|
| 52 |
+
if stance in cleaned_output:
|
| 53 |
+
return stance, False, "stance_found_in_text"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
if 'oppose' in cleaned_output or 'against' in cleaned_output or 'deny' in cleaned_output:
|
| 57 |
+
return 'refute', False, "inferred_from_synonyms"
|
| 58 |
+
elif 'agree' in cleaned_output or 'favor' in cleaned_output or 'endorse' in cleaned_output:
|
| 59 |
+
return 'support', False, "inferred_from_synonyms"
|
| 60 |
+
elif 'neutral' in cleaned_output or 'discuss' in cleaned_output or 'mention' in cleaned_output:
|
| 61 |
+
return 'comment', False, "inferred_from_synonyms"
|
| 62 |
+
elif 'irrelevant' in cleaned_output or 'unconnected' in cleaned_output or 'off-topic' in cleaned_output:
|
| 63 |
+
return 'unrelated', False, "inferred_from_synonyms"
|
| 64 |
+
|
| 65 |
+
return None, False, "no_stance_pattern"
|
| 66 |
+
|
| 67 |
+
except Exception as e:
|
| 68 |
+
return None, False, f"parsing_error_{str(e)}"
|
| 69 |
+
|
| 70 |
+
def parse_ground_truth_stance(ground_truth):
|
| 71 |
+
|
| 72 |
+
if isinstance(ground_truth, dict):
|
| 73 |
+
return ground_truth.get('stance', '').lower().strip()
|
| 74 |
+
elif isinstance(ground_truth, str):
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
parsed = ast.literal_eval(ground_truth)
|
| 78 |
+
if isinstance(parsed, dict) and 'stance' in parsed:
|
| 79 |
+
return parsed['stance'].lower().strip()
|
| 80 |
+
except:
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
return ground_truth.lower().strip()
|
| 84 |
+
else:
|
| 85 |
+
return ''
|
| 86 |
+
|
| 87 |
+
def evaluate_multimodal_stance_detection(result_file_path):
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 92 |
+
results = json.load(f)
|
| 93 |
+
|
| 94 |
+
predictions = []
|
| 95 |
+
ground_truths = []
|
| 96 |
+
detailed_results = []
|
| 97 |
+
extraction_errors = defaultdict(list)
|
| 98 |
+
prediction_errors = defaultdict(list)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
stance_labels = ['support', 'refute', 'comment', 'unrelated']
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
for item in results:
|
| 105 |
+
item_id = item['id']
|
| 106 |
+
model_output = item['model_output']
|
| 107 |
+
gt_stance = parse_ground_truth_stance(item['ground_truth'])
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
pred_stance, is_valid, error_type = extract_stance_from_output(model_output)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
detailed_item = {
|
| 114 |
+
'id': item_id,
|
| 115 |
+
'model_output': model_output,
|
| 116 |
+
'extracted_prediction': pred_stance,
|
| 117 |
+
'ground_truth': gt_stance,
|
| 118 |
+
'correct': pred_stance == gt_stance if pred_stance else False,
|
| 119 |
+
'valid': is_valid
|
| 120 |
+
}
|
| 121 |
+
detailed_results.append(detailed_item)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if not is_valid:
|
| 125 |
+
extraction_errors[error_type].append(item_id)
|
| 126 |
+
elif pred_stance != gt_stance:
|
| 127 |
+
error_pattern = f"{gt_stance}_to_{pred_stance}"
|
| 128 |
+
prediction_errors[error_pattern].append(item_id)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if pred_stance:
|
| 132 |
+
predictions.append(pred_stance)
|
| 133 |
+
ground_truths.append(gt_stance)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
if len(predictions) == 0:
|
| 137 |
+
return {
|
| 138 |
+
'error': 'No valid predictions found',
|
| 139 |
+
'total_samples': len(results),
|
| 140 |
+
'extraction_errors': dict(extraction_errors)
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 145 |
+
micro_f1 = f1_score(ground_truths, predictions, average='micro')
|
| 146 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro')
|
| 147 |
+
weighted_f1 = f1_score(ground_truths, predictions, average='weighted')
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
cm = confusion_matrix(ground_truths, predictions, labels=stance_labels)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class_report = classification_report(ground_truths, predictions,
|
| 154 |
+
target_names=stance_labels,
|
| 155 |
+
output_dict=True,
|
| 156 |
+
zero_division=0)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
per_class_metrics = {}
|
| 160 |
+
for i, label in enumerate(stance_labels):
|
| 161 |
+
if label in class_report:
|
| 162 |
+
true_positives = cm[i, i]
|
| 163 |
+
false_positives = np.sum(cm[:, i]) - true_positives
|
| 164 |
+
false_negatives = np.sum(cm[i, :]) - true_positives
|
| 165 |
+
|
| 166 |
+
per_class_metrics[label] = {
|
| 167 |
+
'precision': round(class_report[label]['precision'], 4),
|
| 168 |
+
'recall': round(class_report[label]['recall'], 4),
|
| 169 |
+
'f1_score': round(class_report[label]['f1-score'], 4),
|
| 170 |
+
'support': int(class_report[label]['support']),
|
| 171 |
+
'true_positives': int(true_positives),
|
| 172 |
+
'false_positives': int(false_positives),
|
| 173 |
+
'false_negatives': int(false_negatives)
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
support_refute_predictions = []
|
| 179 |
+
support_refute_ground_truths = []
|
| 180 |
+
for pred, true in zip(predictions, ground_truths):
|
| 181 |
+
if true in ['support', 'refute']:
|
| 182 |
+
support_refute_predictions.append(pred if pred in ['support', 'refute'] else 'other')
|
| 183 |
+
support_refute_ground_truths.append(true)
|
| 184 |
+
|
| 185 |
+
support_refute_accuracy = 0
|
| 186 |
+
if len(support_refute_ground_truths) > 0:
|
| 187 |
+
support_refute_accuracy = accuracy_score(support_refute_ground_truths, support_refute_predictions)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
evaluation_result = {
|
| 191 |
+
'task_info': {
|
| 192 |
+
'task_name': 'multimodal.stance.detection',
|
| 193 |
+
'dataset': 'MMWTWT',
|
| 194 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 195 |
+
'total_samples': len(results),
|
| 196 |
+
'valid_predictions': len(predictions),
|
| 197 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 198 |
+
},
|
| 199 |
+
'metrics': {
|
| 200 |
+
'ACC': round(accuracy, 4),
|
| 201 |
+
'Micro_F1': round(micro_f1, 4),
|
| 202 |
+
'Macro_F1': round(macro_f1, 4),
|
| 203 |
+
'Weighted_F1': round(weighted_f1, 4),
|
| 204 |
+
'Support_Refute_ACC': round(support_refute_accuracy, 4)
|
| 205 |
+
},
|
| 206 |
+
'per_class_metrics': per_class_metrics,
|
| 207 |
+
'confusion_matrix': {
|
| 208 |
+
'labels': stance_labels,
|
| 209 |
+
'matrix': cm.tolist(),
|
| 210 |
+
'normalized': (cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]).round(4).tolist()
|
| 211 |
+
},
|
| 212 |
+
'error_analysis': {
|
| 213 |
+
'extraction_errors': {
|
| 214 |
+
error_type: {
|
| 215 |
+
'count': len(sample_ids),
|
| 216 |
+
'sample_ids': sample_ids
|
| 217 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 218 |
+
},
|
| 219 |
+
'prediction_errors': {
|
| 220 |
+
error_pattern: {
|
| 221 |
+
'count': len(sample_ids),
|
| 222 |
+
'sample_ids': sample_ids
|
| 223 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 224 |
+
}
|
| 225 |
+
},
|
| 226 |
+
'distribution': {
|
| 227 |
+
'ground_truth': dict(Counter(ground_truths)),
|
| 228 |
+
'predictions': dict(Counter(predictions))
|
| 229 |
+
},
|
| 230 |
+
'stance_analysis': {
|
| 231 |
+
'support_vs_refute_samples': len(support_refute_ground_truths),
|
| 232 |
+
'comment_samples': ground_truths.count('comment'),
|
| 233 |
+
'unrelated_samples': ground_truths.count('unrelated'),
|
| 234 |
+
'most_confused_pairs': []
|
| 235 |
+
}
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
confusion_pairs = []
|
| 240 |
+
for i, label1 in enumerate(stance_labels):
|
| 241 |
+
for j, label2 in enumerate(stance_labels):
|
| 242 |
+
if i != j and cm[i, j] > 0:
|
| 243 |
+
confusion_pairs.append({
|
| 244 |
+
'true_stance': label1,
|
| 245 |
+
'predicted_stance': label2,
|
| 246 |
+
'count': int(cm[i, j]),
|
| 247 |
+
'percentage': round(cm[i, j] / np.sum(cm[i, :]) * 100, 2)
|
| 248 |
+
})
|
| 249 |
+
|
| 250 |
+
confusion_pairs.sort(key=lambda x: x['count'], reverse=True)
|
| 251 |
+
evaluation_result['stance_analysis']['most_confused_pairs'] = confusion_pairs[:5]
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
base_name = result_file_path.replace('.json', '')
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 258 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 259 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 263 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 264 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
problem_samples = [item for item in detailed_results if not item['correct']]
|
| 268 |
+
if problem_samples:
|
| 269 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 270 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 271 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 275 |
+
print(f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, Micro F1={evaluation_result['metrics']['Micro_F1']}")
|
| 276 |
+
print(f"Support/Refute accuracy: {evaluation_result['metrics']['Support_Refute_ACC']}")
|
| 277 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 278 |
+
print(f"Results saved to: {eval_output_file}")
|
| 279 |
+
if problem_samples:
|
| 280 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 281 |
+
|
| 282 |
+
if confusion_pairs:
|
| 283 |
+
print("\nMost confusable stance pairs:")
|
| 284 |
+
for pair in confusion_pairs[:3]:
|
| 285 |
+
print(f" {pair['true_stance']} → {pair['predicted_stance']}: {pair['count']} times ({pair['percentage']}%)")
|
| 286 |
+
|
| 287 |
+
return evaluation_result
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == "__main__":
|
| 291 |
+
result_file = "model_result.json"
|
| 292 |
+
|
| 293 |
+
try:
|
| 294 |
+
evaluation_result = evaluate_multimodal_stance_detection(result_file)
|
| 295 |
+
|
| 296 |
+
except FileNotFoundError:
|
| 297 |
+
print(f"Error: file not found {result_file}")
|
| 298 |
+
except json.JSONDecodeError:
|
| 299 |
+
print(f"Error: invalid format for {result_file}")
|
| 300 |
+
except Exception as e:
|
| 301 |
+
print(f"Evaluation failed: {str(e)}")
|
code/evaluation_code/level3/evaluation_EER.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import accuracy_score, f1_score, classification_report, confusion_matrix
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def extract_emotion_from_output(model_output):
|
| 10 |
+
|
| 11 |
+
if not model_output:
|
| 12 |
+
return None, False, "empty_output"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
valid_emotions = ['Amusement', 'Anger', 'Disgust', 'Fear', 'Neutral', 'Sadness', 'Tenderness']
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
|
| 19 |
+
if "{'emotion':" in model_output or '{"emotion":' in model_output:
|
| 20 |
+
|
| 21 |
+
cleaned_output = model_output.strip()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
json_match = re.search(r'\{[^}]*\}', cleaned_output)
|
| 25 |
+
if json_match:
|
| 26 |
+
cleaned_output = json_match.group()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
try:
|
| 30 |
+
parsed = ast.literal_eval(cleaned_output)
|
| 31 |
+
except:
|
| 32 |
+
|
| 33 |
+
parsed = json.loads(cleaned_output)
|
| 34 |
+
|
| 35 |
+
if 'emotion' in parsed and isinstance(parsed['emotion'], str):
|
| 36 |
+
emotion = parsed['emotion'].strip()
|
| 37 |
+
if emotion in valid_emotions:
|
| 38 |
+
return emotion, True, None
|
| 39 |
+
else:
|
| 40 |
+
return emotion, False, "invalid_emotion_label"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
cleaned_output = model_output.strip()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
for emotion in valid_emotions:
|
| 47 |
+
if cleaned_output == emotion:
|
| 48 |
+
return emotion, True, None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
for emotion in valid_emotions:
|
| 52 |
+
if cleaned_output.lower() == emotion.lower():
|
| 53 |
+
return emotion, True, None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
for emotion in valid_emotions:
|
| 57 |
+
if emotion.lower() in cleaned_output.lower():
|
| 58 |
+
return emotion, False, "emotion_found_but_not_properly_formatted"
|
| 59 |
+
|
| 60 |
+
return None, False, "no_valid_emotion_found"
|
| 61 |
+
|
| 62 |
+
except Exception as e:
|
| 63 |
+
return None, False, f"parsing_error_{str(e)}"
|
| 64 |
+
|
| 65 |
+
def evaluate_emotion_elicitation_reasoning(result_file_path):
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 70 |
+
results = json.load(f)
|
| 71 |
+
|
| 72 |
+
predictions = []
|
| 73 |
+
ground_truths = []
|
| 74 |
+
detailed_results = []
|
| 75 |
+
extraction_errors = defaultdict(list)
|
| 76 |
+
prediction_errors = defaultdict(list)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
emotion_labels = ['Amusement', 'Anger', 'Disgust', 'Fear', 'Neutral', 'Sadness', 'Tenderness']
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
for item in results:
|
| 83 |
+
item_id = item['id']
|
| 84 |
+
model_output = item['model_output']
|
| 85 |
+
gt_emotion = item['ground_truth'].strip()
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
pred_emotion, is_valid, error_type = extract_emotion_from_output(model_output)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
detailed_item = {
|
| 92 |
+
'id': item_id,
|
| 93 |
+
'model_output': model_output,
|
| 94 |
+
'extracted_prediction': pred_emotion,
|
| 95 |
+
'ground_truth': gt_emotion,
|
| 96 |
+
'correct': pred_emotion == gt_emotion if pred_emotion else False,
|
| 97 |
+
'valid': is_valid
|
| 98 |
+
}
|
| 99 |
+
detailed_results.append(detailed_item)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if not is_valid:
|
| 103 |
+
extraction_errors[error_type].append(item_id)
|
| 104 |
+
elif pred_emotion != gt_emotion:
|
| 105 |
+
error_pattern = f"{gt_emotion}_to_{pred_emotion}"
|
| 106 |
+
prediction_errors[error_pattern].append(item_id)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if is_valid:
|
| 110 |
+
predictions.append(pred_emotion)
|
| 111 |
+
ground_truths.append(gt_emotion)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if len(predictions) == 0:
|
| 115 |
+
return {
|
| 116 |
+
'error': 'No valid predictions found',
|
| 117 |
+
'total_samples': len(results),
|
| 118 |
+
'extraction_errors': dict(extraction_errors)
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 123 |
+
weighted_f1 = f1_score(ground_truths, predictions, average='weighted')
|
| 124 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro')
|
| 125 |
+
micro_f1 = f1_score(ground_truths, predictions, average='micro')
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
cm = confusion_matrix(ground_truths, predictions, labels=emotion_labels)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class_report = classification_report(ground_truths, predictions,
|
| 132 |
+
target_names=emotion_labels,
|
| 133 |
+
output_dict=True,
|
| 134 |
+
zero_division=0)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
per_class_metrics = {}
|
| 138 |
+
for i, label in enumerate(emotion_labels):
|
| 139 |
+
if label in class_report:
|
| 140 |
+
true_positives = cm[i, i]
|
| 141 |
+
false_positives = np.sum(cm[:, i]) - true_positives
|
| 142 |
+
false_negatives = np.sum(cm[i, :]) - true_positives
|
| 143 |
+
|
| 144 |
+
per_class_metrics[label] = {
|
| 145 |
+
'precision': round(class_report[label]['precision'], 4),
|
| 146 |
+
'recall': round(class_report[label]['recall'], 4),
|
| 147 |
+
'f1_score': round(class_report[label]['f1-score'], 4),
|
| 148 |
+
'support': int(class_report[label]['support']),
|
| 149 |
+
'true_positives': int(true_positives),
|
| 150 |
+
'false_positives': int(false_positives),
|
| 151 |
+
'false_negatives': int(false_negatives)
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
evaluation_result = {
|
| 156 |
+
'task_info': {
|
| 157 |
+
'task_name': 'emotion.elicitation.reasoning',
|
| 158 |
+
'dataset': 'FilmStim',
|
| 159 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 160 |
+
'total_samples': len(results),
|
| 161 |
+
'valid_predictions': len(predictions),
|
| 162 |
+
'extraction_success_rate': round(len(predictions) / len(results), 4)
|
| 163 |
+
},
|
| 164 |
+
'metrics': {
|
| 165 |
+
'ACC': round(accuracy, 4),
|
| 166 |
+
'WAF': round(weighted_f1, 4),
|
| 167 |
+
'Macro_F1': round(macro_f1, 4),
|
| 168 |
+
'Micro_F1': round(micro_f1, 4)
|
| 169 |
+
},
|
| 170 |
+
'per_class_metrics': per_class_metrics,
|
| 171 |
+
'confusion_matrix': {
|
| 172 |
+
'labels': emotion_labels,
|
| 173 |
+
'matrix': cm.tolist(),
|
| 174 |
+
'normalized': (cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]).round(4).tolist()
|
| 175 |
+
},
|
| 176 |
+
'error_analysis': {
|
| 177 |
+
'extraction_errors': {
|
| 178 |
+
error_type: {
|
| 179 |
+
'count': len(sample_ids),
|
| 180 |
+
'sample_ids': sample_ids
|
| 181 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 182 |
+
},
|
| 183 |
+
'prediction_errors': {
|
| 184 |
+
error_pattern: {
|
| 185 |
+
'count': len(sample_ids),
|
| 186 |
+
'sample_ids': sample_ids
|
| 187 |
+
} for error_pattern, sample_ids in prediction_errors.items()
|
| 188 |
+
}
|
| 189 |
+
},
|
| 190 |
+
'distribution': {
|
| 191 |
+
'ground_truth': dict(Counter(ground_truths)),
|
| 192 |
+
'predictions': dict(Counter(predictions))
|
| 193 |
+
}
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
confusion_pairs = []
|
| 198 |
+
for i, label1 in enumerate(emotion_labels):
|
| 199 |
+
for j, label2 in enumerate(emotion_labels):
|
| 200 |
+
if i != j and cm[i, j] > 0:
|
| 201 |
+
confusion_pairs.append({
|
| 202 |
+
'true_emotion': label1,
|
| 203 |
+
'predicted_emotion': label2,
|
| 204 |
+
'count': int(cm[i, j]),
|
| 205 |
+
'percentage': round(cm[i, j] / np.sum(cm[i, :]) * 100, 2) if np.sum(cm[i, :]) > 0 else 0
|
| 206 |
+
})
|
| 207 |
+
|
| 208 |
+
confusion_pairs.sort(key=lambda x: x['count'], reverse=True)
|
| 209 |
+
evaluation_result['emotion_confusion_analysis'] = {
|
| 210 |
+
'most_confused_pairs': confusion_pairs[:10]
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
base_name = result_file_path.replace('.json', '')
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 218 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 219 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 223 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 224 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
problem_samples = [item for item in detailed_results if not item['correct']]
|
| 228 |
+
if problem_samples:
|
| 229 |
+
problem_report_file = f"{base_name}_problem_samples.json"
|
| 230 |
+
with open(problem_report_file, 'w', encoding='utf-8') as f:
|
| 231 |
+
json.dump(problem_samples, f, ensure_ascii=False, indent=2)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 235 |
+
print(f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, WAF={evaluation_result['metrics']['WAF']}")
|
| 236 |
+
print(f"Extraction success rate: {evaluation_result['task_info']['extraction_success_rate']}")
|
| 237 |
+
print(f"Results saved to: {eval_output_file}")
|
| 238 |
+
if problem_samples:
|
| 239 |
+
print(f"Problematic samples: {len(problem_samples)}; see {problem_report_file} for details")
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if confusion_pairs:
|
| 243 |
+
print("\nMost confusable emotion pairs:")
|
| 244 |
+
for pair in confusion_pairs[:5]:
|
| 245 |
+
print(f" {pair['true_emotion']} → {pair['predicted_emotion']}: {pair['count']} times ({pair['percentage']}%)")
|
| 246 |
+
|
| 247 |
+
return evaluation_result
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
if __name__ == "__main__":
|
| 251 |
+
result_file = "model_result.json"
|
| 252 |
+
|
| 253 |
+
try:
|
| 254 |
+
evaluation_result = evaluate_emotion_elicitation_reasoning(result_file)
|
| 255 |
+
|
| 256 |
+
except FileNotFoundError:
|
| 257 |
+
print(f"Error: file not found {result_file}")
|
| 258 |
+
except json.JSONDecodeError:
|
| 259 |
+
print(f"Error: invalid format for {result_file}")
|
| 260 |
+
except Exception as e:
|
| 261 |
+
print(f"Evaluation failed: {str(e)}")
|
| 262 |
+
|
code/evaluation_code/level3/evaluation_EI.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import openai
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
def extract_numbered_list(text):
|
| 9 |
+
|
| 10 |
+
if not text:
|
| 11 |
+
return []
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
patterns = [
|
| 15 |
+
r'^\s*(\d+)\.\s*(.+)$',
|
| 16 |
+
r'^\s*(\d+)\)\s*(.+)$',
|
| 17 |
+
r'^\s*\((\d+)\)\s*(.+)$',
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
items = []
|
| 21 |
+
lines = text.strip().split('\n')
|
| 22 |
+
|
| 23 |
+
for line in lines:
|
| 24 |
+
line = line.strip()
|
| 25 |
+
if not line:
|
| 26 |
+
continue
|
| 27 |
+
|
| 28 |
+
matched = False
|
| 29 |
+
for pattern in patterns:
|
| 30 |
+
match = re.match(pattern, line)
|
| 31 |
+
if match:
|
| 32 |
+
number = int(match.group(1))
|
| 33 |
+
content = match.group(2).strip()
|
| 34 |
+
items.append(content)
|
| 35 |
+
matched = True
|
| 36 |
+
break
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if not matched and len(line) > 5:
|
| 40 |
+
items.append(line)
|
| 41 |
+
|
| 42 |
+
return items
|
| 43 |
+
|
| 44 |
+
def evaluate_with_gpt4(prediction_text, ground_truth_text, emotion, client):
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
prompt = f"""You are evaluating emotion interpretation explanations.
|
| 48 |
+
|
| 49 |
+
Task: Compare the predicted explanation with the reference explanation for the emotion "{emotion}".
|
| 50 |
+
|
| 51 |
+
Reference explanation:
|
| 52 |
+
{ground_truth_text}
|
| 53 |
+
|
| 54 |
+
Predicted explanation:
|
| 55 |
+
{prediction_text}
|
| 56 |
+
|
| 57 |
+
Evaluate if the predicted explanation is reasonable and accurate compared to the reference.
|
| 58 |
+
|
| 59 |
+
Respond with only "CORRECT" or "INCORRECT" based on whether the predicted explanation is of acceptable quality compared to the reference."""
|
| 60 |
+
|
| 61 |
+
response = client.chat.completions.create(
|
| 62 |
+
model="gpt-4o",
|
| 63 |
+
messages=[{"role": "user", "content": prompt}],
|
| 64 |
+
temperature=0.1,
|
| 65 |
+
max_tokens=10
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
result = response.choices[0].message.content.strip().upper()
|
| 69 |
+
is_correct = result == "CORRECT"
|
| 70 |
+
|
| 71 |
+
return {
|
| 72 |
+
"is_correct": is_correct,
|
| 73 |
+
"llm_response": result
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
except Exception as e:
|
| 77 |
+
return {
|
| 78 |
+
"is_correct": False,
|
| 79 |
+
"llm_response": f"Error: {str(e)}"
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
def extract_emotion_from_prompt(prompt):
|
| 83 |
+
|
| 84 |
+
emotion_match = re.search(r"Emotion to explain:\s*(\w+)", prompt)
|
| 85 |
+
if emotion_match:
|
| 86 |
+
return emotion_match.group(1)
|
| 87 |
+
return "Unknown"
|
| 88 |
+
|
| 89 |
+
def evaluate_emotion_interpretation(result_file_path, api_key):
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
client = openai.OpenAI(api_key=api_key)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 97 |
+
results = json.load(f)
|
| 98 |
+
|
| 99 |
+
detailed_results = []
|
| 100 |
+
extraction_errors = defaultdict(list)
|
| 101 |
+
|
| 102 |
+
correct_count = 0
|
| 103 |
+
total_valid = 0
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
for i, item in enumerate(results):
|
| 107 |
+
item_id = item['id']
|
| 108 |
+
prompt = item['prompt']
|
| 109 |
+
model_output = item['model_output']
|
| 110 |
+
ground_truth = item['ground_truth']
|
| 111 |
+
|
| 112 |
+
print(f"Processing sample {i+1}/{len(results)}: {item_id}")
|
| 113 |
+
|
| 114 |
+
emotion = extract_emotion_from_prompt(prompt)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
pred_items = extract_numbered_list(model_output)
|
| 118 |
+
gt_items = extract_numbered_list(ground_truth)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
has_valid_format = len(pred_items) > 0
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
detailed_item = {
|
| 125 |
+
'id': item_id,
|
| 126 |
+
'emotion': emotion,
|
| 127 |
+
'model_output': model_output,
|
| 128 |
+
'ground_truth': ground_truth,
|
| 129 |
+
'extracted_prediction': pred_items,
|
| 130 |
+
'extracted_ground_truth': gt_items,
|
| 131 |
+
'prediction_count': len(pred_items),
|
| 132 |
+
'ground_truth_count': len(gt_items),
|
| 133 |
+
'has_valid_format': has_valid_format,
|
| 134 |
+
'llm_evaluation': None,
|
| 135 |
+
'is_correct': False
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
if has_valid_format:
|
| 140 |
+
llm_eval = evaluate_with_gpt4(model_output, ground_truth, emotion, client)
|
| 141 |
+
detailed_item['llm_evaluation'] = llm_eval
|
| 142 |
+
detailed_item['is_correct'] = llm_eval['is_correct']
|
| 143 |
+
|
| 144 |
+
if llm_eval['is_correct']:
|
| 145 |
+
correct_count += 1
|
| 146 |
+
total_valid += 1
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
time.sleep(0.5)
|
| 150 |
+
else:
|
| 151 |
+
extraction_errors['invalid_format'].append(item_id)
|
| 152 |
+
|
| 153 |
+
detailed_results.append(detailed_item)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
format_success_rate = total_valid / len(results) if len(results) > 0 else 0
|
| 157 |
+
accuracy = correct_count / total_valid if total_valid > 0 else 0
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
emotion_distribution = Counter([item['emotion'] for item in detailed_results])
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
pred_lengths = [item['prediction_count'] for item in detailed_results if item['has_valid_format']]
|
| 164 |
+
gt_lengths = [item['ground_truth_count'] for item in detailed_results]
|
| 165 |
+
|
| 166 |
+
avg_pred_length = sum(pred_lengths) / len(pred_lengths) if pred_lengths else 0
|
| 167 |
+
avg_gt_length = sum(gt_lengths) / len(gt_lengths) if gt_lengths else 0
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
evaluation_result = {
|
| 171 |
+
'task_info': {
|
| 172 |
+
'task_name': 'emotion.interpretation',
|
| 173 |
+
'dataset': 'EIBench',
|
| 174 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 175 |
+
'total_samples': len(results),
|
| 176 |
+
'valid_samples': total_valid,
|
| 177 |
+
'format_success_rate': round(format_success_rate, 4)
|
| 178 |
+
},
|
| 179 |
+
'metrics': {
|
| 180 |
+
'LLM_ACC': round(accuracy, 4),
|
| 181 |
+
'Correct_Count': correct_count,
|
| 182 |
+
'Total_Valid': total_valid
|
| 183 |
+
},
|
| 184 |
+
'content_analysis': {
|
| 185 |
+
'avg_prediction_length': round(avg_pred_length, 2),
|
| 186 |
+
'avg_ground_truth_length': round(avg_gt_length, 2),
|
| 187 |
+
'emotion_distribution': dict(emotion_distribution)
|
| 188 |
+
},
|
| 189 |
+
'error_analysis': {
|
| 190 |
+
'extraction_errors': {
|
| 191 |
+
error_type: {
|
| 192 |
+
'count': len(sample_ids),
|
| 193 |
+
'sample_ids': sample_ids
|
| 194 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 195 |
+
}
|
| 196 |
+
}
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
emotion_analysis = {}
|
| 201 |
+
for emotion in emotion_distribution.keys():
|
| 202 |
+
emotion_samples = [item for item in detailed_results if item['emotion'] == emotion and item['has_valid_format']]
|
| 203 |
+
if emotion_samples:
|
| 204 |
+
emotion_correct = sum(1 for item in emotion_samples if item['is_correct'])
|
| 205 |
+
emotion_total = len(emotion_samples)
|
| 206 |
+
emotion_acc = emotion_correct / emotion_total if emotion_total > 0 else 0
|
| 207 |
+
|
| 208 |
+
emotion_analysis[emotion] = {
|
| 209 |
+
'sample_count': emotion_total,
|
| 210 |
+
'correct_count': emotion_correct,
|
| 211 |
+
'accuracy': round(emotion_acc, 4),
|
| 212 |
+
'avg_prediction_length': round(sum([item['prediction_count'] for item in emotion_samples]) / len(emotion_samples), 2)
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
evaluation_result['emotion_analysis'] = emotion_analysis
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
base_name = result_file_path.replace('.json', '')
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 222 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 223 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 227 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 228 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
incorrect_samples = [item for item in detailed_results if item['has_valid_format'] and not item['is_correct']]
|
| 232 |
+
if incorrect_samples:
|
| 233 |
+
incorrect_report_file = f"{base_name}_incorrect_samples.json"
|
| 234 |
+
with open(incorrect_report_file, 'w', encoding='utf-8') as f:
|
| 235 |
+
json.dump(incorrect_samples, f, ensure_ascii=False, indent=2)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
print(f"\nEvaluation complete: {len(results)} samples")
|
| 239 |
+
print(f"Key metric: LLM_ACC={evaluation_result['metrics']['LLM_ACC']}")
|
| 240 |
+
print(f"Correct count: {evaluation_result['metrics']['Correct_Count']}/{evaluation_result['metrics']['Total_Valid']}")
|
| 241 |
+
print(f"Format success rate: {evaluation_result['task_info']['format_success_rate']}")
|
| 242 |
+
print(f"Average prediction length: {evaluation_result['content_analysis']['avg_prediction_length']}")
|
| 243 |
+
print(f"Results saved to: {eval_output_file}")
|
| 244 |
+
if incorrect_samples:
|
| 245 |
+
print(f"Incorrect samples: {len(incorrect_samples)}; see {incorrect_report_file} for details")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
if emotion_analysis:
|
| 249 |
+
print("\nPerformance by emotion type:")
|
| 250 |
+
for emotion, analysis in emotion_analysis.items():
|
| 251 |
+
print(f" {emotion}: ACC={analysis['accuracy']}, Samples={analysis['sample_count']}")
|
| 252 |
+
|
| 253 |
+
return evaluation_result
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
result_file = "model_result.json"
|
| 258 |
+
api_key = "xxx"
|
| 259 |
+
|
| 260 |
+
try:
|
| 261 |
+
evaluation_result = evaluate_emotion_interpretation(result_file, api_key)
|
| 262 |
+
|
| 263 |
+
except FileNotFoundError:
|
| 264 |
+
print(f"Error: file not found {result_file}")
|
| 265 |
+
except json.JSONDecodeError:
|
| 266 |
+
print(f"Error: invalid format for {result_file}")
|
| 267 |
+
except Exception as e:
|
| 268 |
+
print(f"Evaluation failed: {str(e)}")
|
| 269 |
+
|
code/evaluation_code/level3/evaluation_LR.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ai
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import time
|
| 7 |
+
|
| 8 |
+
def check_required_format(text):
|
| 9 |
+
|
| 10 |
+
if not text:
|
| 11 |
+
return False, ""
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
pattern = r'^The audience laughed because\s+'
|
| 15 |
+
match = re.search(pattern, text, re.IGNORECASE)
|
| 16 |
+
|
| 17 |
+
if match:
|
| 18 |
+
|
| 19 |
+
content = text[match.end():].strip()
|
| 20 |
+
return True, content
|
| 21 |
+
else:
|
| 22 |
+
return False, text.strip()
|
| 23 |
+
|
| 24 |
+
def evaluate_with_gpt4(prediction_text, ground_truth_text, client):
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
prompt = f"""Compare the predicted explanation with the reference explanation for why the audience laughed.
|
| 28 |
+
|
| 29 |
+
Reference explanation:
|
| 30 |
+
{ground_truth_text}
|
| 31 |
+
|
| 32 |
+
Predicted explanation:
|
| 33 |
+
{prediction_text}
|
| 34 |
+
|
| 35 |
+
Does the predicted explanation correctly identify the reason for laughter? The prediction doesn't need to be identical to the reference, but should accurately capture why the audience laughed.
|
| 36 |
+
|
| 37 |
+
Respond with only "CORRECT" or "INCORRECT"."""
|
| 38 |
+
|
| 39 |
+
response = client.chat.completions.create(
|
| 40 |
+
model="gpt-4",
|
| 41 |
+
messages=[{"role": "user", "content": prompt}],
|
| 42 |
+
temperature=0.1,
|
| 43 |
+
max_tokens=10
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
result = response.choices[0].message.content.strip().upper()
|
| 47 |
+
is_correct = result == "CORRECT"
|
| 48 |
+
|
| 49 |
+
return {
|
| 50 |
+
"is_correct": is_correct,
|
| 51 |
+
"llm_response": result
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
except Exception as e:
|
| 55 |
+
return {
|
| 56 |
+
"is_correct": False,
|
| 57 |
+
"llm_response": f"Error: {str(e)}"
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
def evaluate_laughter_reasoning(result_file_path, api_key):
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
client = openai.OpenAI(api_key=api_key)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 68 |
+
results = json.load(f)
|
| 69 |
+
|
| 70 |
+
detailed_results = []
|
| 71 |
+
format_errors = defaultdict(list)
|
| 72 |
+
|
| 73 |
+
correct_count = 0
|
| 74 |
+
total_valid = 0
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
for i, item in enumerate(results):
|
| 78 |
+
item_id = item['id']
|
| 79 |
+
model_output = item['model_output']
|
| 80 |
+
ground_truth = item['ground_truth']
|
| 81 |
+
|
| 82 |
+
print(f"Processing sample {i+1}/{len(results)}: {item_id}")
|
| 83 |
+
|
| 84 |
+
has_correct_format, cleaned_content = check_required_format(model_output)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
detailed_item = {
|
| 88 |
+
'id': item_id,
|
| 89 |
+
'model_output': model_output,
|
| 90 |
+
'ground_truth': ground_truth,
|
| 91 |
+
'has_correct_format': has_correct_format,
|
| 92 |
+
'cleaned_content': cleaned_content,
|
| 93 |
+
'llm_evaluation': None,
|
| 94 |
+
'is_correct': False
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
if has_correct_format and cleaned_content:
|
| 99 |
+
|
| 100 |
+
_, gt_cleaned = check_required_format(ground_truth)
|
| 101 |
+
if not gt_cleaned:
|
| 102 |
+
gt_cleaned = ground_truth
|
| 103 |
+
|
| 104 |
+
llm_eval = evaluate_with_gpt4(cleaned_content, gt_cleaned, client)
|
| 105 |
+
detailed_item['llm_evaluation'] = llm_eval
|
| 106 |
+
detailed_item['is_correct'] = llm_eval['is_correct']
|
| 107 |
+
|
| 108 |
+
if llm_eval['is_correct']:
|
| 109 |
+
correct_count += 1
|
| 110 |
+
total_valid += 1
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
time.sleep(0.5)
|
| 114 |
+
else:
|
| 115 |
+
if not has_correct_format:
|
| 116 |
+
format_errors['incorrect_format'].append(item_id)
|
| 117 |
+
else:
|
| 118 |
+
format_errors['empty_content'].append(item_id)
|
| 119 |
+
|
| 120 |
+
detailed_results.append(detailed_item)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
format_success_rate = total_valid / len(results) if len(results) > 0 else 0
|
| 124 |
+
accuracy = correct_count / total_valid if total_valid > 0 else 0
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
valid_contents = [item['cleaned_content'] for item in detailed_results if item['has_correct_format'] and item['cleaned_content']]
|
| 128 |
+
avg_content_length = sum(len(content.split()) for content in valid_contents) / len(valid_contents) if valid_contents else 0
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
correct_samples = [item for item in detailed_results if item['has_correct_format'] and item['is_correct']]
|
| 132 |
+
incorrect_samples = [item for item in detailed_results if item['has_correct_format'] and not item['is_correct']]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
evaluation_result = {
|
| 136 |
+
'task_info': {
|
| 137 |
+
'task_name': 'laughter.reasoning',
|
| 138 |
+
'dataset': 'SMILE',
|
| 139 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 140 |
+
'total_samples': len(results),
|
| 141 |
+
'valid_samples': total_valid,
|
| 142 |
+
'format_success_rate': round(format_success_rate, 4)
|
| 143 |
+
},
|
| 144 |
+
'metrics': {
|
| 145 |
+
'LLM_ACC': round(accuracy, 4),
|
| 146 |
+
'Correct_Count': correct_count,
|
| 147 |
+
'Total_Valid': total_valid
|
| 148 |
+
},
|
| 149 |
+
'content_analysis': {
|
| 150 |
+
'avg_content_length_words': round(avg_content_length, 2)
|
| 151 |
+
},
|
| 152 |
+
'error_analysis': {
|
| 153 |
+
'format_errors': {
|
| 154 |
+
error_type: {
|
| 155 |
+
'count': len(sample_ids),
|
| 156 |
+
'sample_ids': sample_ids
|
| 157 |
+
} for error_type, sample_ids in format_errors.items()
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if correct_samples:
|
| 164 |
+
correct_avg_length = sum(len(item['cleaned_content'].split()) for item in correct_samples) / len(correct_samples)
|
| 165 |
+
evaluation_result['content_analysis']['correct_samples_avg_length'] = round(correct_avg_length, 2)
|
| 166 |
+
|
| 167 |
+
if incorrect_samples:
|
| 168 |
+
incorrect_avg_length = sum(len(item['cleaned_content'].split()) for item in incorrect_samples) / len(incorrect_samples)
|
| 169 |
+
evaluation_result['content_analysis']['incorrect_samples_avg_length'] = round(incorrect_avg_length, 2)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
base_name = result_file_path.replace('.json', '')
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 176 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 177 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 181 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 182 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
if incorrect_samples:
|
| 186 |
+
incorrect_report_file = f"{base_name}_incorrect_samples.json"
|
| 187 |
+
with open(incorrect_report_file, 'w', encoding='utf-8') as f:
|
| 188 |
+
json.dump(incorrect_samples, f, ensure_ascii=False, indent=2)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
format_error_samples = [item for item in detailed_results if not item['has_correct_format']]
|
| 192 |
+
if format_error_samples:
|
| 193 |
+
format_error_report_file = f"{base_name}_format_error_samples.json"
|
| 194 |
+
with open(format_error_report_file, 'w', encoding='utf-8') as f:
|
| 195 |
+
json.dump(format_error_samples, f, ensure_ascii=False, indent=2)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
print(f"\nEvaluation complete: {len(results)} samples")
|
| 199 |
+
print(f"Key metric: LLM_ACC={evaluation_result['metrics']['LLM_ACC']}")
|
| 200 |
+
print(f"Correct count: {evaluation_result['metrics']['Correct_Count']}/{evaluation_result['metrics']['Total_Valid']}")
|
| 201 |
+
print(f"Format success rate: {evaluation_result['task_info']['format_success_rate']}")
|
| 202 |
+
print(f"Average content length: {evaluation_result['content_analysis']['avg_content_length_words']} words")
|
| 203 |
+
print(f"Results saved to: {eval_output_file}")
|
| 204 |
+
|
| 205 |
+
if incorrect_samples:
|
| 206 |
+
print(f"Incorrect samples: {len(incorrect_samples)}; see {incorrect_report_file} for details")
|
| 207 |
+
if format_error_samples:
|
| 208 |
+
print(f"Format-error samples: {len(format_error_samples)}; see {format_error_report_file} for details")
|
| 209 |
+
|
| 210 |
+
return evaluation_result
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
result_file = "model_result.json"
|
| 215 |
+
api_key = "xxx"
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
evaluation_result = evaluate_laughter_reasoning(result_file, api_key)
|
| 219 |
+
|
| 220 |
+
except FileNotFoundError:
|
| 221 |
+
print(f"Error: file not found {result_file}")
|
| 222 |
+
except json.JSONDecodeError:
|
| 223 |
+
print(f"Error: invalid format for {result_file}")
|
| 224 |
+
except Exception as e:
|
| 225 |
+
print(f"Evaluation failed: {str(e)}")
|
| 226 |
+
|
code/evaluation_code/level3/evaluation_MECPE.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
from sklearn.metrics import f1_score, precision_score, recall_score
|
| 9 |
+
|
| 10 |
+
def parse_emotion_cause_pairs(output_text):
|
| 11 |
+
|
| 12 |
+
if not output_text:
|
| 13 |
+
return {}, False, "empty_output"
|
| 14 |
+
|
| 15 |
+
valid_emotions = ['joy', 'sadness', 'anger', 'disgust', 'fear', 'surprise', 'neutral']
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
cleaned_output = output_text.strip()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
json_match = re.search(r'\{.*\}', cleaned_output, re.DOTALL)
|
| 22 |
+
if not json_match:
|
| 23 |
+
return {}, False, "no_json_structure"
|
| 24 |
+
|
| 25 |
+
json_content = json_match.group()
|
| 26 |
+
|
| 27 |
+
parsed = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
try:
|
| 31 |
+
|
| 32 |
+
parsed = ast.literal_eval(json_content)
|
| 33 |
+
except (ValueError, SyntaxError) as e:
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if "EOF" in str(e) or "end of string" in str(e):
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
last_comma_index = json_content.rfind(',')
|
| 40 |
+
if last_comma_index != -1:
|
| 41 |
+
|
| 42 |
+
content_after_comma = json_content[last_comma_index+1:].strip()
|
| 43 |
+
if content_after_comma and content_after_comma != '}':
|
| 44 |
+
truncated_content = json_content[:last_comma_index] + '}'
|
| 45 |
+
try:
|
| 46 |
+
|
| 47 |
+
parsed = ast.literal_eval(truncated_content)
|
| 48 |
+
|
| 49 |
+
except (ValueError, SyntaxError):
|
| 50 |
+
|
| 51 |
+
pass
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if parsed is None:
|
| 55 |
+
try:
|
| 56 |
+
|
| 57 |
+
json_content_fixed = json_content.replace("'", '"')
|
| 58 |
+
parsed = json.loads(json_content_fixed)
|
| 59 |
+
except json.JSONDecodeError:
|
| 60 |
+
|
| 61 |
+
raise e
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if not isinstance(parsed, dict):
|
| 65 |
+
return {}, False, "not_dictionary"
|
| 66 |
+
|
| 67 |
+
validated_pairs = {}
|
| 68 |
+
for utterance_id, pair_data in parsed.items():
|
| 69 |
+
|
| 70 |
+
if not isinstance(pair_data, dict) or 'emotion' not in pair_data or 'cause_utterance_id' not in pair_data:
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
emotion = str(pair_data['emotion']).lower().strip()
|
| 74 |
+
cause_id = str(pair_data['cause_utterance_id']).strip()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if emotion not in valid_emotions:
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
int(utterance_id)
|
| 83 |
+
int(cause_id)
|
| 84 |
+
except (ValueError, TypeError):
|
| 85 |
+
continue
|
| 86 |
+
|
| 87 |
+
validated_pairs[str(utterance_id)] = {
|
| 88 |
+
'emotion': emotion,
|
| 89 |
+
'cause_utterance_id': cause_id
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
return validated_pairs, len(validated_pairs) > 0, None
|
| 93 |
+
|
| 94 |
+
except Exception as e:
|
| 95 |
+
|
| 96 |
+
return {}, False, f"parsing_error_{type(e).__name__}"
|
| 97 |
+
|
| 98 |
+
def calculate_pair_extraction_metrics(predictions, ground_truths):
|
| 99 |
+
|
| 100 |
+
total_tp = 0
|
| 101 |
+
total_fp = 0
|
| 102 |
+
total_fn = 0
|
| 103 |
+
|
| 104 |
+
emotion_correct_on_common = 0
|
| 105 |
+
cause_correct_on_common = 0
|
| 106 |
+
total_common_utterances = 0
|
| 107 |
+
|
| 108 |
+
all_true_emotions = []
|
| 109 |
+
all_pred_emotions = []
|
| 110 |
+
|
| 111 |
+
for pred_dict, true_dict in zip(predictions, ground_truths):
|
| 112 |
+
|
| 113 |
+
pred_pairs = {(str(uid), data['emotion'], str(data['cause_utterance_id'])) for uid, data in pred_dict.items()}
|
| 114 |
+
true_pairs = {(str(uid), data['emotion'], str(data['cause_utterance_id'])) for uid, data in true_dict.items()}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
all_pred_emotions.extend([data['emotion'] for data in pred_dict.values()])
|
| 118 |
+
all_true_emotions.extend([data['emotion'] for data in true_dict.values()])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
total_tp += len(pred_pairs.intersection(true_pairs))
|
| 122 |
+
total_fp += len(pred_pairs.difference(true_pairs))
|
| 123 |
+
total_fn += len(true_pairs.difference(pred_pairs))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
common_ids = set(pred_dict.keys()) & set(true_dict.keys())
|
| 127 |
+
total_common_utterances += len(common_ids)
|
| 128 |
+
for uid in common_ids:
|
| 129 |
+
if pred_dict[uid]['emotion'] == true_dict[uid]['emotion']:
|
| 130 |
+
emotion_correct_on_common += 1
|
| 131 |
+
if pred_dict[uid]['cause_utterance_id'] == true_dict[uid]['cause_utterance_id']:
|
| 132 |
+
cause_correct_on_common += 1
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
micro_precision = total_tp / (total_tp + total_fp) if (total_tp + total_fp) > 0 else 0
|
| 136 |
+
micro_recall = total_tp / (total_tp + total_fn) if (total_tp + total_fn) > 0 else 0
|
| 137 |
+
micro_f1 = 2 * micro_precision * micro_recall / (micro_precision + micro_recall) if (micro_precision + micro_recall) > 0 else 0
|
| 138 |
+
|
| 139 |
+
emotion_accuracy_common = emotion_correct_on_common / total_common_utterances if total_common_utterances > 0 else 0
|
| 140 |
+
cause_accuracy_common = cause_correct_on_common / total_common_utterances if total_common_utterances > 0 else 0
|
| 141 |
+
|
| 142 |
+
return {
|
| 143 |
+
'micro_f1': micro_f1,
|
| 144 |
+
'micro_precision': micro_precision,
|
| 145 |
+
'micro_recall': micro_recall,
|
| 146 |
+
'emotion_accuracy_on_common_ids': emotion_accuracy_common,
|
| 147 |
+
'cause_accuracy_on_common_ids': cause_accuracy_common,
|
| 148 |
+
'total_predicted_pairs': total_tp + total_fp,
|
| 149 |
+
'total_ground_truth_pairs': total_tp + total_fn,
|
| 150 |
+
'exact_matches': total_tp,
|
| 151 |
+
'emotion_distribution': dict(Counter(all_true_emotions)),
|
| 152 |
+
'predicted_emotion_distribution': dict(Counter(all_pred_emotions))
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
def evaluate_multimodal_emotion_cause_pair_extraction(result_file_path):
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 159 |
+
results = json.load(f)
|
| 160 |
+
|
| 161 |
+
predictions = []
|
| 162 |
+
ground_truths = []
|
| 163 |
+
detailed_results = []
|
| 164 |
+
extraction_errors = defaultdict(list)
|
| 165 |
+
|
| 166 |
+
for item in results:
|
| 167 |
+
item_id = item.get('id', 'unknown')
|
| 168 |
+
model_output = item.get('model_output', '')
|
| 169 |
+
ground_truth = item.get('ground_truth', {})
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
pred_pairs, pred_valid, pred_error = parse_emotion_cause_pairs(model_output)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if isinstance(ground_truth, str):
|
| 176 |
+
gt_pairs, gt_valid, gt_error = parse_emotion_cause_pairs(ground_truth)
|
| 177 |
+
else:
|
| 178 |
+
gt_pairs, gt_valid, gt_error = parse_emotion_cause_pairs(json.dumps(ground_truth))
|
| 179 |
+
|
| 180 |
+
detailed_item = {
|
| 181 |
+
'id': item_id,
|
| 182 |
+
'model_output': model_output,
|
| 183 |
+
'ground_truth': ground_truth,
|
| 184 |
+
'extracted_prediction': pred_pairs,
|
| 185 |
+
'extracted_ground_truth': gt_pairs,
|
| 186 |
+
'prediction_valid': pred_valid,
|
| 187 |
+
'ground_truth_valid': gt_valid,
|
| 188 |
+
'predicted_pairs_count': len(pred_pairs),
|
| 189 |
+
'ground_truth_pairs_count': len(gt_pairs)
|
| 190 |
+
}
|
| 191 |
+
detailed_results.append(detailed_item)
|
| 192 |
+
|
| 193 |
+
if not pred_valid:
|
| 194 |
+
extraction_errors[pred_error].append(item_id)
|
| 195 |
+
if not gt_valid:
|
| 196 |
+
|
| 197 |
+
extraction_errors[f"gt_{gt_error}"].append(item_id)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
if pred_valid and gt_valid:
|
| 201 |
+
predictions.append(pred_pairs)
|
| 202 |
+
ground_truths.append(gt_pairs)
|
| 203 |
+
|
| 204 |
+
if not predictions:
|
| 205 |
+
print("Error: No valid prediction–ground truth pairs were found for evaluation.")
|
| 206 |
+
print(f"Total samples: {len(results)}")
|
| 207 |
+
print("Parsing error stats:", json.dumps(dict(extraction_errors), indent=2))
|
| 208 |
+
return {
|
| 209 |
+
'error': 'No valid prediction and ground_truth pairs found for evaluation',
|
| 210 |
+
'total_samples': len(results),
|
| 211 |
+
'extraction_errors': dict(extraction_errors)
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
metrics = calculate_pair_extraction_metrics(predictions, ground_truths)
|
| 216 |
+
|
| 217 |
+
evaluation_result = {
|
| 218 |
+
'task_info': {
|
| 219 |
+
'task_name': 'multimodal.emotion.cause.pair.extraction',
|
| 220 |
+
'dataset': 'ECF',
|
| 221 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 222 |
+
'total_samples': len(results),
|
| 223 |
+
'valid_samples_for_eval': len(predictions),
|
| 224 |
+
'extraction_success_rate': round(len(predictions) / len(results) if results else 0, 4)
|
| 225 |
+
},
|
| 226 |
+
'metrics': {
|
| 227 |
+
'Micro_F1': round(metrics['micro_f1'], 4),
|
| 228 |
+
'Micro_Precision': round(metrics['micro_precision'], 4),
|
| 229 |
+
'Micro_Recall': round(metrics['micro_recall'], 4),
|
| 230 |
+
'Emotion_ACC_on_Common_IDs': round(metrics['emotion_accuracy_on_common_ids'], 4),
|
| 231 |
+
'Cause_ACC_on_Common_IDs': round(metrics['cause_accuracy_on_common_ids'], 4),
|
| 232 |
+
'Total_Predicted_Pairs': metrics['total_predicted_pairs'],
|
| 233 |
+
'Total_Ground_Truth_Pairs': metrics['total_ground_truth_pairs'],
|
| 234 |
+
'Exact_Matches': metrics['exact_matches']
|
| 235 |
+
},
|
| 236 |
+
'distribution_analysis': {
|
| 237 |
+
'emotion_distribution': metrics['emotion_distribution'],
|
| 238 |
+
'predicted_emotion_distribution': metrics['predicted_emotion_distribution']
|
| 239 |
+
},
|
| 240 |
+
'error_analysis': {
|
| 241 |
+
'extraction_errors': {
|
| 242 |
+
error_type: {
|
| 243 |
+
'count': len(sample_ids),
|
| 244 |
+
'sample_ids': sample_ids[:10]
|
| 245 |
+
} for error_type, sample_ids in extraction_errors.items()
|
| 246 |
+
}
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
base_name = result_file_path.rsplit('.', 1)[0]
|
| 252 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 253 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 254 |
+
|
| 255 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 256 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 257 |
+
|
| 258 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 259 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
print("\n" + "="*50)
|
| 263 |
+
print("Evaluation Report")
|
| 264 |
+
print("="*50)
|
| 265 |
+
print(f"Evaluation complete: {len(results)} total samples")
|
| 266 |
+
print(f"Valid evaluation samples (both prediction and label parsed successfully): {len(predictions)} / {len(results)} (extraction success rate: {evaluation_result['task_info']['extraction_success_rate']:.2%})")
|
| 267 |
+
print("\n--- Primary Metrics ---")
|
| 268 |
+
print(f"Micro F1: {evaluation_result['metrics']['Micro_F1']:.4f}")
|
| 269 |
+
print(f"Micro Precision: {evaluation_result['metrics']['Micro_Precision']:.4f}")
|
| 270 |
+
print(f"Micro Recall: {evaluation_result['metrics']['Micro_Recall']:.4f}")
|
| 271 |
+
print("\n--- Auxiliary Metrics ---")
|
| 272 |
+
print(f"Emotion accuracy on common IDs (Emotion ACC): {evaluation_result['metrics']['Emotion_ACC_on_Common_IDs']:.4f}")
|
| 273 |
+
print(f"Cause accuracy on common IDs (Cause ACC): {evaluation_result['metrics']['Cause_ACC_on_Common_IDs']:.4f}")
|
| 274 |
+
print(f"Total predicted pairs: {evaluation_result['metrics']['Total_Predicted_Pairs']}")
|
| 275 |
+
print(f"Total ground-truth pairs: {evaluation_result['metrics']['Total_Ground_Truth_Pairs']}")
|
| 276 |
+
print(f"Exact matches: {evaluation_result['metrics']['Exact_Matches']}")
|
| 277 |
+
|
| 278 |
+
if extraction_errors:
|
| 279 |
+
print("\n--- Parsing Error Analysis ---")
|
| 280 |
+
for error_type, info in evaluation_result['error_analysis']['extraction_errors'].items():
|
| 281 |
+
print(f"- Type: {error_type}, Count: {info['count']}")
|
| 282 |
+
|
| 283 |
+
print(f"Detailed evaluation results saved to: {eval_output_file}")
|
| 284 |
+
print(f"Per-sample parsing details saved to: {detailed_output_file}")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
return evaluation_result
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
if __name__ == "__main__":
|
| 293 |
+
|
| 294 |
+
result_file = "model_result.json"
|
| 295 |
+
|
| 296 |
+
try:
|
| 297 |
+
evaluation_result = evaluate_multimodal_emotion_cause_pair_extraction(result_file)
|
| 298 |
+
|
| 299 |
+
except FileNotFoundError:
|
| 300 |
+
print(f"Error: File '{result_file}' not found. Please check that the path is correct.")
|
| 301 |
+
except json.JSONDecodeError:
|
| 302 |
+
print(f"Error: File '{result_file}' is not valid JSON. Ensure the file is a JSON list (starts with '[' and ends with ']').")
|
| 303 |
+
except Exception as e:
|
| 304 |
+
print(f"An unknown error occurred during evaluation: {e}")
|
code/evaluation_code/level3/evaluation_SD.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, confusion_matrix, classification_report
|
| 4 |
+
from collections import Counter, defaultdict
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
def parse_classification_output(output_text):
|
| 9 |
+
|
| 10 |
+
if not output_text:
|
| 11 |
+
return None, False, "empty_output"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
cleaned_output = output_text.strip().lower()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
if re.search(r'\btrue\b', cleaned_output):
|
| 18 |
+
return "true", True, None
|
| 19 |
+
elif re.search(r'\bfalse\b', cleaned_output):
|
| 20 |
+
return "false", True, None
|
| 21 |
+
else:
|
| 22 |
+
return None, False, "no_valid_label"
|
| 23 |
+
|
| 24 |
+
def calculate_weighted_average_f1(y_true, y_pred, labels):
|
| 25 |
+
|
| 26 |
+
return f1_score(y_true, y_pred, labels=labels, average='weighted')
|
| 27 |
+
|
| 28 |
+
def evaluate_sarcasm_detection(result_file_path):
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 32 |
+
results = json.load(f)
|
| 33 |
+
|
| 34 |
+
predictions = []
|
| 35 |
+
ground_truths = []
|
| 36 |
+
detailed_results = []
|
| 37 |
+
parsing_errors = defaultdict(list)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
for item in results:
|
| 41 |
+
item_id = item['id']
|
| 42 |
+
model_output = item['model_output']
|
| 43 |
+
ground_truth = item['ground_truth']
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
pred_label, pred_valid, pred_error = parse_classification_output(model_output)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
gt_label = ground_truth.strip().lower() if isinstance(ground_truth, str) else str(ground_truth).strip().lower()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
detailed_item = {
|
| 53 |
+
'id': item_id,
|
| 54 |
+
'model_output': model_output,
|
| 55 |
+
'ground_truth': ground_truth,
|
| 56 |
+
'extracted_prediction': pred_label,
|
| 57 |
+
'standardized_ground_truth': gt_label,
|
| 58 |
+
'prediction_valid': pred_valid,
|
| 59 |
+
'prediction_error': pred_error
|
| 60 |
+
}
|
| 61 |
+
detailed_results.append(detailed_item)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if not pred_valid:
|
| 65 |
+
parsing_errors[pred_error].append(item_id)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
if pred_valid and gt_label in ['true', 'false']:
|
| 69 |
+
predictions.append(pred_label)
|
| 70 |
+
ground_truths.append(gt_label)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
if len(predictions) == 0:
|
| 74 |
+
return {
|
| 75 |
+
'error': 'No valid predictions found',
|
| 76 |
+
'total_samples': len(results),
|
| 77 |
+
'parsing_errors': dict(parsing_errors)
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
labels = ['true', 'false']
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
accuracy = accuracy_score(ground_truths, predictions)
|
| 85 |
+
weighted_f1 = calculate_weighted_average_f1(ground_truths, predictions, labels)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
precision_scores = precision_score(ground_truths, predictions, labels=labels, average=None, zero_division=0)
|
| 89 |
+
recall_scores = recall_score(ground_truths, predictions, labels=labels, average=None, zero_division=0)
|
| 90 |
+
f1_scores = f1_score(ground_truths, predictions, labels=labels, average=None, zero_division=0)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
macro_precision = precision_score(ground_truths, predictions, average='macro', zero_division=0)
|
| 94 |
+
macro_recall = recall_score(ground_truths, predictions, average='macro', zero_division=0)
|
| 95 |
+
macro_f1 = f1_score(ground_truths, predictions, average='macro', zero_division=0)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
cm = confusion_matrix(ground_truths, predictions, labels=labels)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
true_distribution = Counter(ground_truths)
|
| 102 |
+
pred_distribution = Counter(predictions)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class_metrics = {}
|
| 106 |
+
for i, label in enumerate(labels):
|
| 107 |
+
class_metrics[label] = {
|
| 108 |
+
'precision': round(precision_scores[i], 4),
|
| 109 |
+
'recall': round(recall_scores[i], 4),
|
| 110 |
+
'f1_score': round(f1_scores[i], 4),
|
| 111 |
+
'support': true_distribution.get(label, 0)
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
evaluation_result = {
|
| 116 |
+
'task_info': {
|
| 117 |
+
'task_name': 'sarcasm.detection',
|
| 118 |
+
'dataset': 'MUStARD',
|
| 119 |
+
'task_type': '2-CLS',
|
| 120 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 121 |
+
'total_samples': len(results),
|
| 122 |
+
'valid_samples': len(predictions),
|
| 123 |
+
'parsing_success_rate': round(len(predictions) / len(results), 4)
|
| 124 |
+
},
|
| 125 |
+
'metrics': {
|
| 126 |
+
'ACC': round(accuracy, 4),
|
| 127 |
+
'WAF': round(weighted_f1, 4),
|
| 128 |
+
'Macro_Precision': round(macro_precision, 4),
|
| 129 |
+
'Macro_Recall': round(macro_recall, 4),
|
| 130 |
+
'Macro_F1': round(macro_f1, 4)
|
| 131 |
+
},
|
| 132 |
+
'class_metrics': class_metrics,
|
| 133 |
+
'confusion_matrix': {
|
| 134 |
+
'matrix': cm.tolist(),
|
| 135 |
+
'labels': labels
|
| 136 |
+
},
|
| 137 |
+
'distribution_analysis': {
|
| 138 |
+
'ground_truth_distribution': dict(true_distribution),
|
| 139 |
+
'prediction_distribution': dict(pred_distribution)
|
| 140 |
+
},
|
| 141 |
+
'error_analysis': {
|
| 142 |
+
'parsing_errors': {
|
| 143 |
+
error_type: {
|
| 144 |
+
'count': len(sample_ids),
|
| 145 |
+
'sample_ids': sample_ids
|
| 146 |
+
} for error_type, sample_ids in parsing_errors.items()
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
if len(labels) == 2:
|
| 153 |
+
|
| 154 |
+
tn, fp, fn, tp = cm.ravel() if cm.size == 4 else [0, 0, 0, 0]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
specificity = tn / (tn + fp) if (tn + fp) > 0 else 0
|
| 158 |
+
sensitivity = tp / (tp + fn) if (tp + fn) > 0 else 0
|
| 159 |
+
|
| 160 |
+
evaluation_result['binary_metrics'] = {
|
| 161 |
+
'true_positives': int(tp),
|
| 162 |
+
'true_negatives': int(tn),
|
| 163 |
+
'false_positives': int(fp),
|
| 164 |
+
'false_negatives': int(fn),
|
| 165 |
+
'sensitivity_recall': round(sensitivity, 4),
|
| 166 |
+
'specificity': round(specificity, 4)
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
error_samples = []
|
| 171 |
+
correct_samples = []
|
| 172 |
+
|
| 173 |
+
for i, (pred, true, item) in enumerate(zip(predictions, ground_truths,
|
| 174 |
+
[d for d in detailed_results if d['prediction_valid']])):
|
| 175 |
+
if pred != true:
|
| 176 |
+
error_samples.append({
|
| 177 |
+
'id': item['id'],
|
| 178 |
+
'predicted': pred,
|
| 179 |
+
'ground_truth': true,
|
| 180 |
+
'model_output': item['model_output']
|
| 181 |
+
})
|
| 182 |
+
else:
|
| 183 |
+
correct_samples.append(item['id'])
|
| 184 |
+
|
| 185 |
+
evaluation_result['sample_analysis'] = {
|
| 186 |
+
'correct_samples_count': len(correct_samples),
|
| 187 |
+
'error_samples_count': len(error_samples),
|
| 188 |
+
'error_rate': round(len(error_samples) / len(predictions), 4) if predictions else 0
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
base_name = result_file_path.replace('.json', '')
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 196 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 197 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 201 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 202 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
if error_samples:
|
| 206 |
+
error_report_file = f"{base_name}_error_samples.json"
|
| 207 |
+
with open(error_report_file, 'w', encoding='utf-8') as f:
|
| 208 |
+
json.dump(error_samples, f, ensure_ascii=False, indent=2)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
parsing_error_samples = [item for item in detailed_results if not item['prediction_valid']]
|
| 212 |
+
if parsing_error_samples:
|
| 213 |
+
parsing_error_report_file = f"{base_name}_parsing_error_samples.json"
|
| 214 |
+
with open(parsing_error_report_file, 'w', encoding='utf-8') as f:
|
| 215 |
+
json.dump(parsing_error_samples, f, ensure_ascii=False, indent=2)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 219 |
+
print(f"Key metrics: ACC={evaluation_result['metrics']['ACC']}, WAF={evaluation_result['metrics']['WAF']}")
|
| 220 |
+
print(f"Macro-averaged metrics: Precision={evaluation_result['metrics']['Macro_Precision']}, Recall={evaluation_result['metrics']['Macro_Recall']}, F1={evaluation_result['metrics']['Macro_F1']}")
|
| 221 |
+
print(f"Parsing success rate: {evaluation_result['task_info']['parsing_success_rate']}")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
print("\nPer-class metrics:")
|
| 225 |
+
for label, metrics in evaluation_result['class_metrics'].items():
|
| 226 |
+
print(f" {label.upper()}: P={metrics['precision']}, R={metrics['recall']}, F1={metrics['f1_score']}, Support={metrics['support']}")
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
print(f"\nConfusion matrix:")
|
| 230 |
+
print(f" Predicted")
|
| 231 |
+
print(f"Actual false true")
|
| 232 |
+
for i, true_label in enumerate(labels):
|
| 233 |
+
row_str = f"{true_label:>5} "
|
| 234 |
+
for j, pred_label in enumerate(labels):
|
| 235 |
+
row_str += f"{cm[i][j]:>5} "
|
| 236 |
+
print(row_str)
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
print(f"\nLabel distribution:")
|
| 240 |
+
print(f"True labels: {dict(true_distribution)}")
|
| 241 |
+
print(f"Predicted labels: {dict(pred_distribution)}")
|
| 242 |
+
|
| 243 |
+
print(f"\nResults saved to: {eval_output_file}")
|
| 244 |
+
if error_samples:
|
| 245 |
+
print(f"Error samples: {len(error_samples)}; see {error_report_file} for details")
|
| 246 |
+
if parsing_error_samples:
|
| 247 |
+
print(f"Parsing-error samples: {len(parsing_error_samples)}; see {parsing_error_report_file} for details")
|
| 248 |
+
|
| 249 |
+
return evaluation_result
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
result_file = "model_result.json"
|
| 254 |
+
|
| 255 |
+
try:
|
| 256 |
+
evaluation_result = evaluate_sarcasm_detection(result_file)
|
| 257 |
+
|
| 258 |
+
except FileNotFoundError:
|
| 259 |
+
print(f"Error: file not found {result_file}")
|
| 260 |
+
except json.JSONDecodeError:
|
| 261 |
+
print(f"Error: invalid format for {result_file}")
|
| 262 |
+
except Exception as e:
|
| 263 |
+
print(f"Evaluation failed: {str(e)}")
|
| 264 |
+
|
code/evaluation_code/level3/evaluation_SFA.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
import ast
|
| 4 |
+
from sklearn.metrics import f1_score, precision_score, recall_score
|
| 5 |
+
from collections import Counter, defaultdict
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
def parse_sentiment_flip_output(output_text):
|
| 10 |
+
|
| 11 |
+
if not output_text:
|
| 12 |
+
return [], False, "empty_output"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
valid_sentiments = ['positive', 'negative', 'neutral']
|
| 16 |
+
valid_trigger_types = [
|
| 17 |
+
'Introduction of New Information',
|
| 18 |
+
'Logical Argumentation',
|
| 19 |
+
'Participant Feedback and Interaction',
|
| 20 |
+
'Personal Experience and Self-reflection'
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
|
| 25 |
+
cleaned_output = output_text.strip()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
list_match = re.search(r'\[.*\]', cleaned_output, re.DOTALL)
|
| 29 |
+
if not list_match:
|
| 30 |
+
return [], False, "no_list_structure"
|
| 31 |
+
|
| 32 |
+
list_content = list_match.group()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
parsed = ast.literal_eval(list_content)
|
| 37 |
+
except:
|
| 38 |
+
|
| 39 |
+
list_content = re.sub(r"'", '"', list_content)
|
| 40 |
+
parsed = json.loads(list_content)
|
| 41 |
+
|
| 42 |
+
if not isinstance(parsed, list):
|
| 43 |
+
return [], False, "not_list"
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
validated_flips = []
|
| 47 |
+
for item in parsed:
|
| 48 |
+
if not isinstance(item, dict):
|
| 49 |
+
continue
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
required_fields = ['holder', 'initial_sentiment', 'flipped_sentiment', 'trigger_type']
|
| 53 |
+
if not all(field in item for field in required_fields):
|
| 54 |
+
continue
|
| 55 |
+
|
| 56 |
+
holder = str(item['holder']).strip()
|
| 57 |
+
initial_sentiment = str(item['initial_sentiment']).lower().strip()
|
| 58 |
+
flipped_sentiment = str(item['flipped_sentiment']).lower().strip()
|
| 59 |
+
trigger_type = str(item['trigger_type']).strip()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
if initial_sentiment not in valid_sentiments or flipped_sentiment not in valid_sentiments:
|
| 63 |
+
continue
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
trigger_valid = False
|
| 67 |
+
for valid_trigger in valid_trigger_types:
|
| 68 |
+
if trigger_type.lower() in valid_trigger.lower() or valid_trigger.lower() in trigger_type.lower():
|
| 69 |
+
trigger_type = valid_trigger
|
| 70 |
+
trigger_valid = True
|
| 71 |
+
break
|
| 72 |
+
|
| 73 |
+
if not trigger_valid:
|
| 74 |
+
continue
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if not holder:
|
| 78 |
+
continue
|
| 79 |
+
|
| 80 |
+
validated_flips.append({
|
| 81 |
+
'holder': holder,
|
| 82 |
+
'initial_sentiment': initial_sentiment,
|
| 83 |
+
'flipped_sentiment': flipped_sentiment,
|
| 84 |
+
'trigger_type': trigger_type
|
| 85 |
+
})
|
| 86 |
+
|
| 87 |
+
return validated_flips, len(validated_flips) >= 0, None
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
return [], False, f"parsing_error_{str(e)}"
|
| 91 |
+
|
| 92 |
+
def normalize_flip_for_comparison(flip):
|
| 93 |
+
|
| 94 |
+
return {
|
| 95 |
+
'holder': flip['holder'].lower().strip(),
|
| 96 |
+
'initial_sentiment': flip['initial_sentiment'].lower().strip(),
|
| 97 |
+
'flipped_sentiment': flip['flipped_sentiment'].lower().strip(),
|
| 98 |
+
'trigger_type': flip['trigger_type'].strip()
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
def calculate_exact_match_f1(predictions, ground_truths):
|
| 102 |
+
|
| 103 |
+
total_pred_flips = 0
|
| 104 |
+
total_true_flips = 0
|
| 105 |
+
exact_matches = 0
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
all_metrics = []
|
| 109 |
+
|
| 110 |
+
for pred_flips, true_flips in zip(predictions, ground_truths):
|
| 111 |
+
|
| 112 |
+
norm_pred_flips = [normalize_flip_for_comparison(flip) for flip in pred_flips]
|
| 113 |
+
norm_true_flips = [normalize_flip_for_comparison(flip) for flip in true_flips]
|
| 114 |
+
|
| 115 |
+
total_pred_flips += len(pred_flips)
|
| 116 |
+
total_true_flips += len(true_flips)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
sample_matches = 0
|
| 120 |
+
for true_flip in norm_true_flips:
|
| 121 |
+
if true_flip in norm_pred_flips:
|
| 122 |
+
sample_matches += 1
|
| 123 |
+
exact_matches += 1
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
sample_precision = sample_matches / len(pred_flips) if len(pred_flips) > 0 else 0
|
| 127 |
+
sample_recall = sample_matches / len(true_flips) if len(true_flips) > 0 else (1 if len(pred_flips) == 0 else 0)
|
| 128 |
+
sample_f1 = 2 * sample_precision * sample_recall / (sample_precision + sample_recall) if (sample_precision + sample_recall) > 0 else 0
|
| 129 |
+
|
| 130 |
+
all_metrics.append({
|
| 131 |
+
'precision': sample_precision,
|
| 132 |
+
'recall': sample_recall,
|
| 133 |
+
'f1': sample_f1,
|
| 134 |
+
'matches': sample_matches,
|
| 135 |
+
'pred_count': len(pred_flips),
|
| 136 |
+
'true_count': len(true_flips)
|
| 137 |
+
})
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
micro_precision = exact_matches / total_pred_flips if total_pred_flips > 0 else 0
|
| 141 |
+
micro_recall = exact_matches / total_true_flips if total_true_flips > 0 else 0
|
| 142 |
+
micro_f1 = 2 * micro_precision * micro_recall / (micro_precision + micro_recall) if (micro_precision + micro_recall) > 0 else 0
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
macro_precision = np.mean([m['precision'] for m in all_metrics]) if all_metrics else 0
|
| 146 |
+
macro_recall = np.mean([m['recall'] for m in all_metrics]) if all_metrics else 0
|
| 147 |
+
macro_f1 = np.mean([m['f1'] for m in all_metrics]) if all_metrics else 0
|
| 148 |
+
|
| 149 |
+
return {
|
| 150 |
+
'exact_match_f1': micro_f1,
|
| 151 |
+
'micro_precision': micro_precision,
|
| 152 |
+
'micro_recall': micro_recall,
|
| 153 |
+
'macro_precision': macro_precision,
|
| 154 |
+
'macro_recall': macro_recall,
|
| 155 |
+
'macro_f1': macro_f1,
|
| 156 |
+
'total_predicted_flips': total_pred_flips,
|
| 157 |
+
'total_ground_truth_flips': total_true_flips,
|
| 158 |
+
'exact_matches': exact_matches,
|
| 159 |
+
'sample_metrics': all_metrics
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
def analyze_flip_patterns(predictions, ground_truths):
|
| 163 |
+
|
| 164 |
+
all_pred_sentiments = []
|
| 165 |
+
all_true_sentiments = []
|
| 166 |
+
all_pred_triggers = []
|
| 167 |
+
all_true_triggers = []
|
| 168 |
+
all_pred_holders = []
|
| 169 |
+
all_true_holders = []
|
| 170 |
+
|
| 171 |
+
for pred_flips, true_flips in zip(predictions, ground_truths):
|
| 172 |
+
for flip in pred_flips:
|
| 173 |
+
all_pred_sentiments.append(f"{flip['initial_sentiment']}->{flip['flipped_sentiment']}")
|
| 174 |
+
all_pred_triggers.append(flip['trigger_type'])
|
| 175 |
+
all_pred_holders.append(flip['holder'])
|
| 176 |
+
|
| 177 |
+
for flip in true_flips:
|
| 178 |
+
all_true_sentiments.append(f"{flip['initial_sentiment']}->{flip['flipped_sentiment']}")
|
| 179 |
+
all_true_triggers.append(flip['trigger_type'])
|
| 180 |
+
all_true_holders.append(flip['holder'])
|
| 181 |
+
|
| 182 |
+
return {
|
| 183 |
+
'sentiment_flip_patterns': {
|
| 184 |
+
'predicted': dict(Counter(all_pred_sentiments)),
|
| 185 |
+
'ground_truth': dict(Counter(all_true_sentiments))
|
| 186 |
+
},
|
| 187 |
+
'trigger_type_distribution': {
|
| 188 |
+
'predicted': dict(Counter(all_pred_triggers)),
|
| 189 |
+
'ground_truth': dict(Counter(all_true_triggers))
|
| 190 |
+
},
|
| 191 |
+
'holder_distribution': {
|
| 192 |
+
'predicted': dict(Counter(all_pred_holders)),
|
| 193 |
+
'ground_truth': dict(Counter(all_true_holders))
|
| 194 |
+
}
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
def evaluate_sentiment_flip_analysis(result_file_path):
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
with open(result_file_path, 'r', encoding='utf-8') as f:
|
| 202 |
+
results = json.load(f)
|
| 203 |
+
|
| 204 |
+
predictions = []
|
| 205 |
+
ground_truths = []
|
| 206 |
+
detailed_results = []
|
| 207 |
+
parsing_errors = defaultdict(list)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
for item in results:
|
| 211 |
+
item_id = item['id']
|
| 212 |
+
model_output = item['model_output']
|
| 213 |
+
ground_truth = item['ground_truth']
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
pred_flips, pred_valid, pred_error = parse_sentiment_flip_output(model_output)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
if isinstance(ground_truth, str):
|
| 220 |
+
gt_flips, gt_valid, gt_error = parse_sentiment_flip_output(ground_truth)
|
| 221 |
+
elif isinstance(ground_truth, list):
|
| 222 |
+
gt_flips = ground_truth
|
| 223 |
+
gt_valid = True
|
| 224 |
+
gt_error = None
|
| 225 |
+
else:
|
| 226 |
+
gt_flips = []
|
| 227 |
+
gt_valid = False
|
| 228 |
+
gt_error = "invalid_ground_truth_format"
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
detailed_item = {
|
| 232 |
+
'id': item_id,
|
| 233 |
+
'model_output': model_output,
|
| 234 |
+
'ground_truth': ground_truth,
|
| 235 |
+
'extracted_prediction': pred_flips,
|
| 236 |
+
'extracted_ground_truth': gt_flips,
|
| 237 |
+
'prediction_valid': pred_valid,
|
| 238 |
+
'ground_truth_valid': gt_valid,
|
| 239 |
+
'predicted_flips_count': len(pred_flips),
|
| 240 |
+
'ground_truth_flips_count': len(gt_flips)
|
| 241 |
+
}
|
| 242 |
+
detailed_results.append(detailed_item)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if not pred_valid:
|
| 246 |
+
parsing_errors[pred_error].append(item_id)
|
| 247 |
+
elif not gt_valid:
|
| 248 |
+
parsing_errors[f"gt_{gt_error}"].append(item_id)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
if pred_valid and gt_valid:
|
| 252 |
+
predictions.append(pred_flips)
|
| 253 |
+
ground_truths.append(gt_flips)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
if len(predictions) == 0:
|
| 257 |
+
return {
|
| 258 |
+
'error': 'No valid predictions found',
|
| 259 |
+
'total_samples': len(results),
|
| 260 |
+
'parsing_errors': dict(parsing_errors)
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
metrics = calculate_exact_match_f1(predictions, ground_truths)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
pattern_analysis = analyze_flip_patterns(predictions, ground_truths)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
pred_flip_counts = [len(flips) for flips in predictions]
|
| 271 |
+
true_flip_counts = [len(flips) for flips in ground_truths]
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
evaluation_result = {
|
| 275 |
+
'task_info': {
|
| 276 |
+
'task_name': 'sentiment.flip.analysis',
|
| 277 |
+
'dataset': 'PanoSent',
|
| 278 |
+
'task_type': 'GEN',
|
| 279 |
+
'evaluation_time': datetime.now().isoformat(),
|
| 280 |
+
'total_samples': len(results),
|
| 281 |
+
'valid_samples': len(predictions),
|
| 282 |
+
'parsing_success_rate': round(len(predictions) / len(results), 4)
|
| 283 |
+
},
|
| 284 |
+
'metrics': {
|
| 285 |
+
'Exact_Match_F1': round(metrics['exact_match_f1'], 4),
|
| 286 |
+
'Micro_Precision': round(metrics['micro_precision'], 4),
|
| 287 |
+
'Micro_Recall': round(metrics['micro_recall'], 4),
|
| 288 |
+
'Macro_Precision': round(metrics['macro_precision'], 4),
|
| 289 |
+
'Macro_Recall': round(metrics['macro_recall'], 4),
|
| 290 |
+
'Macro_F1': round(metrics['macro_f1'], 4),
|
| 291 |
+
'Total_Predicted_Flips': metrics['total_predicted_flips'],
|
| 292 |
+
'Total_Ground_Truth_Flips': metrics['total_ground_truth_flips'],
|
| 293 |
+
'Exact_Matches': metrics['exact_matches']
|
| 294 |
+
},
|
| 295 |
+
'flip_count_analysis': {
|
| 296 |
+
'avg_predicted_flips_per_sample': round(np.mean(pred_flip_counts), 2),
|
| 297 |
+
'avg_ground_truth_flips_per_sample': round(np.mean(true_flip_counts), 2),
|
| 298 |
+
'predicted_flip_count_distribution': dict(Counter(pred_flip_counts)),
|
| 299 |
+
'ground_truth_flip_count_distribution': dict(Counter(true_flip_counts))
|
| 300 |
+
},
|
| 301 |
+
'pattern_analysis': pattern_analysis,
|
| 302 |
+
'error_analysis': {
|
| 303 |
+
'parsing_errors': {
|
| 304 |
+
error_type: {
|
| 305 |
+
'count': len(sample_ids),
|
| 306 |
+
'sample_ids': sample_ids
|
| 307 |
+
} for error_type, sample_ids in parsing_errors.items()
|
| 308 |
+
}
|
| 309 |
+
}
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
zero_pred_samples = sum(1 for count in pred_flip_counts if count == 0)
|
| 314 |
+
zero_true_samples = sum(1 for count in true_flip_counts if count == 0)
|
| 315 |
+
|
| 316 |
+
evaluation_result['zero_flip_analysis'] = {
|
| 317 |
+
'predicted_zero_flips': zero_pred_samples,
|
| 318 |
+
'ground_truth_zero_flips': zero_true_samples,
|
| 319 |
+
'zero_flip_accuracy': sum(1 for p, t in zip(pred_flip_counts, true_flip_counts) if p == 0 and t == 0) / len(predictions)
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
base_name = result_file_path.replace('.json', '')
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
eval_output_file = f"{base_name}_evaluation.json"
|
| 327 |
+
with open(eval_output_file, 'w', encoding='utf-8') as f:
|
| 328 |
+
json.dump(evaluation_result, f, ensure_ascii=False, indent=2)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
detailed_output_file = f"{base_name}_detailed_results.json"
|
| 332 |
+
with open(detailed_output_file, 'w', encoding='utf-8') as f:
|
| 333 |
+
json.dump(detailed_results, f, ensure_ascii=False, indent=2)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
low_score_samples = []
|
| 337 |
+
for i, sample_metric in enumerate(metrics['sample_metrics']):
|
| 338 |
+
if sample_metric['f1'] < 0.5:
|
| 339 |
+
low_score_samples.append({
|
| 340 |
+
'id': detailed_results[i]['id'],
|
| 341 |
+
'f1_score': sample_metric['f1'],
|
| 342 |
+
'precision': sample_metric['precision'],
|
| 343 |
+
'recall': sample_metric['recall'],
|
| 344 |
+
'predicted_flips': detailed_results[i]['extracted_prediction'],
|
| 345 |
+
'ground_truth_flips': detailed_results[i]['extracted_ground_truth']
|
| 346 |
+
})
|
| 347 |
+
|
| 348 |
+
if low_score_samples:
|
| 349 |
+
low_score_report_file = f"{base_name}_low_score_samples.json"
|
| 350 |
+
with open(low_score_report_file, 'w', encoding='utf-8') as f:
|
| 351 |
+
json.dump(low_score_samples, f, ensure_ascii=False, indent=2)
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
parsing_error_samples = [item for item in detailed_results if not item['prediction_valid']]
|
| 355 |
+
if parsing_error_samples:
|
| 356 |
+
parsing_error_report_file = f"{base_name}_parsing_error_samples.json"
|
| 357 |
+
with open(parsing_error_report_file, 'w', encoding='utf-8') as f:
|
| 358 |
+
json.dump(parsing_error_samples, f, ensure_ascii=False, indent=2)
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
print(f"Evaluation complete: {len(results)} samples")
|
| 362 |
+
print(f"Key metric: Exact Match F1={evaluation_result['metrics']['Exact_Match_F1']}")
|
| 363 |
+
print(f"Micro-averaged metrics: Precision={evaluation_result['metrics']['Micro_Precision']}, Recall={evaluation_result['metrics']['Micro_Recall']}")
|
| 364 |
+
print(f"Macro-averaged metrics: Precision={evaluation_result['metrics']['Macro_Precision']}, Recall={evaluation_result['metrics']['Macro_Recall']}, F1={evaluation_result['metrics']['Macro_F1']}")
|
| 365 |
+
print(f"Parsing success rate: {evaluation_result['task_info']['parsing_success_rate']}")
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
print(f"\nFlip statistics:")
|
| 369 |
+
print(f"Average predicted flips per sample: {evaluation_result['flip_count_analysis']['avg_predicted_flips_per_sample']}")
|
| 370 |
+
print(f"Average ground-truth flips per sample: {evaluation_result['flip_count_analysis']['avg_ground_truth_flips_per_sample']}")
|
| 371 |
+
print(f"Zero-flip accuracy: {evaluation_result['zero_flip_analysis']['zero_flip_accuracy']:.4f}")
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
print(f"\nSentiment flip patterns:")
|
| 375 |
+
gt_patterns = evaluation_result['pattern_analysis']['sentiment_flip_patterns']['ground_truth']
|
| 376 |
+
pred_patterns = evaluation_result['pattern_analysis']['sentiment_flip_patterns']['predicted']
|
| 377 |
+
for pattern in sorted(set(list(gt_patterns.keys()) + list(pred_patterns.keys()))):
|
| 378 |
+
gt_count = gt_patterns.get(pattern, 0)
|
| 379 |
+
pred_count = pred_patterns.get(pattern, 0)
|
| 380 |
+
print(f" {pattern}: GT={gt_count}, Pred={pred_count}")
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
print(f"\nTrigger type distribution:")
|
| 384 |
+
gt_triggers = evaluation_result['pattern_analysis']['trigger_type_distribution']['ground_truth']
|
| 385 |
+
pred_triggers = evaluation_result['pattern_analysis']['trigger_type_distribution']['predicted']
|
| 386 |
+
for trigger in sorted(set(list(gt_triggers.keys()) + list(pred_triggers.keys()))):
|
| 387 |
+
gt_count = gt_triggers.get(trigger, 0)
|
| 388 |
+
pred_count = pred_triggers.get(trigger, 0)
|
| 389 |
+
print(f" {trigger}: GT={gt_count}, Pred={pred_count}")
|
| 390 |
+
|
| 391 |
+
print(f"\nResults saved to: {eval_output_file}")
|
| 392 |
+
if low_score_samples:
|
| 393 |
+
print(f"Low-scoring samples: {len(low_score_samples)}; see {low_score_report_file} for details")
|
| 394 |
+
if parsing_error_samples:
|
| 395 |
+
print(f"Parsing-error samples: {len(parsing_error_samples)}; see {parsing_error_report_file} for details")
|
| 396 |
+
|
| 397 |
+
return evaluation_result
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
if __name__ == "__main__":
|
| 401 |
+
result_file = "model_result.json"
|
| 402 |
+
|
| 403 |
+
try:
|
| 404 |
+
evaluation_result = evaluate_sentiment_flip_analysis(result_file)
|
| 405 |
+
|
| 406 |
+
except FileNotFoundError:
|
| 407 |
+
print(f"Error: file not found {result_file}")
|
| 408 |
+
except json.JSONDecodeError:
|
| 409 |
+
print(f"Error: invalid format for {result_file}")
|
| 410 |
+
except Exception as e:
|
| 411 |
+
print(f"Evaluation failed: {str(e)}")
|
code/test_code/test_affectgpt.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import time
|
| 5 |
+
import sys
|
| 6 |
+
from typing import Dict, Any
|
| 7 |
+
from tqdm import tqdm
|
| 8 |
+
import torch
|
| 9 |
+
import cv2
|
| 10 |
+
import tempfile
|
| 11 |
+
import torch.backends.cudnn as cudnn
|
| 12 |
+
import decord
|
| 13 |
+
decord.bridge.set_bridge('torch')
|
| 14 |
+
import torch.multiprocessing as mp
|
| 15 |
+
|
| 16 |
+
# --- Worker Initialization for Multiprocessing Pool ---
|
| 17 |
+
worker_chat = None
|
| 18 |
+
worker_cfg = None
|
| 19 |
+
|
| 20 |
+
def init_worker():
|
| 21 |
+
global worker_chat, worker_cfg
|
| 22 |
+
setup_seeds(42)
|
| 23 |
+
worker_chat, worker_cfg = load_affectgpt_model()
|
| 24 |
+
print(f"[Worker PID: {os.getpid()}] Model loaded successfully.")
|
| 25 |
+
|
| 26 |
+
sys.path.append('AffectGPT')
|
| 27 |
+
|
| 28 |
+
from my_affectgpt.common.config import Config
|
| 29 |
+
from my_affectgpt.common.registry import registry
|
| 30 |
+
from my_affectgpt.conversation.conversation_video import Chat
|
| 31 |
+
|
| 32 |
+
# --- Configuration ---
|
| 33 |
+
LEVEL_DIRS = ["level1", "level2", "level3"]
|
| 34 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 35 |
+
|
| 36 |
+
def get_media_type(file_path: str) -> str:
|
| 37 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 38 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 39 |
+
return 'video'
|
| 40 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 41 |
+
return 'image'
|
| 42 |
+
else:
|
| 43 |
+
raise ValueError(f"Unsupported file format: {ext}")
|
| 44 |
+
|
| 45 |
+
def setup_seeds(seed=42):
|
| 46 |
+
import random
|
| 47 |
+
random.seed(seed)
|
| 48 |
+
torch.manual_seed(seed)
|
| 49 |
+
if torch.cuda.is_available():
|
| 50 |
+
torch.cuda.manual_seed(seed)
|
| 51 |
+
torch.cuda.manual_seed_all(seed)
|
| 52 |
+
cudnn.benchmark = False
|
| 53 |
+
cudnn.deterministic = True
|
| 54 |
+
|
| 55 |
+
def load_affectgpt_model():
|
| 56 |
+
print("Loading AffectGPT model...")
|
| 57 |
+
import config
|
| 58 |
+
config.PATH_TO_LLM['Qwen25'] = 'Qwen25'
|
| 59 |
+
config.PATH_TO_VISUAL['CLIP_VIT_LARGE'] = 'CLIP_VIT_LARGE'
|
| 60 |
+
config.PATH_TO_AUDIO['HUBERT_LARGE'] = 'HUBRT_LARGE'
|
| 61 |
+
cfg_path = "CFG_PATH"
|
| 62 |
+
class Args:
|
| 63 |
+
def __init__(self):
|
| 64 |
+
self.cfg_path = cfg_path
|
| 65 |
+
self.options = ["inference.test_epoch=60"]
|
| 66 |
+
args = Args()
|
| 67 |
+
cfg = Config(args)
|
| 68 |
+
model_cfg = cfg.model_cfg
|
| 69 |
+
device = 'cuda:7'
|
| 70 |
+
ckpt_path = "CKPT_PATH"
|
| 71 |
+
model_cfg.ckpt_3 = ckpt_path
|
| 72 |
+
model_cls = registry.get_model_class(model_cfg.arch)
|
| 73 |
+
model = model_cls.from_config(model_cfg)
|
| 74 |
+
model = model.to(device).eval()
|
| 75 |
+
chat = Chat(model, model_cfg, device=device)
|
| 76 |
+
print("AffectGPT model loaded!")
|
| 77 |
+
return chat, cfg
|
| 78 |
+
|
| 79 |
+
def create_complete_dataset(cfg):
|
| 80 |
+
from my_affectgpt.processors import BaseProcessor
|
| 81 |
+
class CompleteDataset:
|
| 82 |
+
def __init__(self, cfg):
|
| 83 |
+
self.vis_processor = BaseProcessor()
|
| 84 |
+
self.img_processor = BaseProcessor()
|
| 85 |
+
self.n_frms = 8
|
| 86 |
+
inference_cfg = cfg.inference_cfg
|
| 87 |
+
vis_processor_cfg = inference_cfg.get("vis_processor")
|
| 88 |
+
img_processor_cfg = inference_cfg.get("img_processor")
|
| 89 |
+
if vis_processor_cfg is not None:
|
| 90 |
+
self.vis_processor = registry.get_processor_class(vis_processor_cfg.train.name).from_config(vis_processor_cfg.train)
|
| 91 |
+
if img_processor_cfg is not None:
|
| 92 |
+
self.img_processor = registry.get_processor_class(img_processor_cfg.train.name).from_config(img_processor_cfg.train)
|
| 93 |
+
self.n_frms = cfg.model_cfg.vis_processor.train.n_frms
|
| 94 |
+
|
| 95 |
+
def read_frame_face_audio_text(self, video_path, face_npy, audio_path, image_path):
|
| 96 |
+
sample_data = {}
|
| 97 |
+
frame, raw_frame = None, None
|
| 98 |
+
if video_path is not None:
|
| 99 |
+
from my_affectgpt.processors.video_processor import load_video
|
| 100 |
+
raw_frame, msg = load_video(video_path=video_path, n_frms=self.n_frms, height=224, width=224, sampling="uniform", return_msg=True)
|
| 101 |
+
frame = self.vis_processor.transform(raw_frame)
|
| 102 |
+
sample_data['frame'] = frame
|
| 103 |
+
sample_data['raw_frame'] = raw_frame
|
| 104 |
+
sample_data['face'] = None
|
| 105 |
+
sample_data['raw_face'] = None
|
| 106 |
+
audio, raw_audio = None, None
|
| 107 |
+
if audio_path is not None and os.path.exists(audio_path):
|
| 108 |
+
from my_affectgpt.models.ImageBind.data import load_audio, transform_audio
|
| 109 |
+
raw_audio = load_audio([audio_path], "cpu", clips_per_video=8)[0]
|
| 110 |
+
audio = transform_audio(raw_audio, "cpu")
|
| 111 |
+
sample_data['audio'] = audio
|
| 112 |
+
sample_data['raw_audio'] = raw_audio
|
| 113 |
+
image, raw_image = None, None
|
| 114 |
+
if image_path is not None and os.path.exists(image_path):
|
| 115 |
+
from PIL import Image as PILImage
|
| 116 |
+
raw_image = PILImage.open(image_path).convert('RGB')
|
| 117 |
+
image = self.img_processor(raw_image)
|
| 118 |
+
sample_data['image'] = image
|
| 119 |
+
sample_data['raw_image'] = raw_image
|
| 120 |
+
return sample_data
|
| 121 |
+
def get_prompt_for_multimodal(self, face_or_frame, subtitle, user_message):
|
| 122 |
+
prompt = f"<FrameHere>{user_message}"
|
| 123 |
+
if subtitle:
|
| 124 |
+
prompt = f"Context: {subtitle}\n{prompt}"
|
| 125 |
+
return prompt
|
| 126 |
+
return CompleteDataset(cfg)
|
| 127 |
+
|
| 128 |
+
def process_single_sample(chat, cfg, media_full_path, prompt_text):
|
| 129 |
+
try:
|
| 130 |
+
media_type = get_media_type(media_full_path)
|
| 131 |
+
if media_type == 'image':
|
| 132 |
+
temp_video = tempfile.mktemp(suffix='.mp4')
|
| 133 |
+
img = cv2.imread(media_full_path)
|
| 134 |
+
height, width, layers = img.shape
|
| 135 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 136 |
+
video_writer = cv2.VideoWriter(temp_video, fourcc, 1.0, (width, height))
|
| 137 |
+
for _ in range(30):
|
| 138 |
+
video_writer.write(img)
|
| 139 |
+
video_writer.release()
|
| 140 |
+
video_path, audio_path, image_path = temp_video, None, None
|
| 141 |
+
else:
|
| 142 |
+
video_path, audio_path, image_path = media_full_path, None, None
|
| 143 |
+
|
| 144 |
+
dataset_cls = create_complete_dataset(cfg)
|
| 145 |
+
sample_data = dataset_cls.read_frame_face_audio_text(video_path, None, audio_path, image_path)
|
| 146 |
+
_, audio_llms = chat.postprocess_audio(sample_data)
|
| 147 |
+
_, frame_llms = chat.postprocess_frame(sample_data)
|
| 148 |
+
_, face_llms = chat.postprocess_face(sample_data)
|
| 149 |
+
_, image_llms = chat.postprocess_image(sample_data)
|
| 150 |
+
|
| 151 |
+
img_list = {'audio': audio_llms, 'frame': frame_llms, 'face': face_llms, 'image': image_llms, 'multi': None}
|
| 152 |
+
|
| 153 |
+
user_message = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 154 |
+
prompt = dataset_cls.get_prompt_for_multimodal('frame', "", user_message)
|
| 155 |
+
|
| 156 |
+
response = chat.answer_sample(prompt=prompt, img_list=img_list, num_beams=1, temperature=0.1, do_sample=False, top_p=0.9, max_new_tokens=512, max_length=2000)
|
| 157 |
+
|
| 158 |
+
if media_type == 'image' and os.path.exists(temp_video):
|
| 159 |
+
os.remove(temp_video)
|
| 160 |
+
return response
|
| 161 |
+
except Exception as e:
|
| 162 |
+
import traceback
|
| 163 |
+
traceback.print_exc()
|
| 164 |
+
return f"ERROR: {str(e)}"
|
| 165 |
+
|
| 166 |
+
def text_only_fallback_logic(chat, cfg, prompt_text: str) -> str:
|
| 167 |
+
print("Executing text-only fallback in worker...")
|
| 168 |
+
try:
|
| 169 |
+
dataset_cls = create_complete_dataset(cfg)
|
| 170 |
+
user_message = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 171 |
+
prompt = dataset_cls.get_prompt_for_multimodal('frame', "", user_message)
|
| 172 |
+
img_list = {'audio': None, 'frame': None, 'face': None, 'image': None, 'multi': None}
|
| 173 |
+
response = chat.answer_sample(prompt=prompt, img_list=img_list, num_beams=1, temperature=0.1, do_sample=False, top_p=0.9, max_new_tokens=512, max_length=2000)
|
| 174 |
+
return response
|
| 175 |
+
except Exception as e:
|
| 176 |
+
return f"ERROR in text-only fallback: {str(e)}"
|
| 177 |
+
|
| 178 |
+
# --- Worker Task Functions ---
|
| 179 |
+
def run_inference_task(media_full_path, prompt_text):
|
| 180 |
+
global worker_chat, worker_cfg
|
| 181 |
+
if worker_chat is None or worker_cfg is None: return "ERROR: Worker model not initialized."
|
| 182 |
+
return process_single_sample(worker_chat, worker_cfg, media_full_path, prompt_text)
|
| 183 |
+
|
| 184 |
+
def run_fallback_task(prompt_text):
|
| 185 |
+
global worker_chat, worker_cfg
|
| 186 |
+
if worker_chat is None or worker_cfg is None: return "ERROR: Worker model not initialized."
|
| 187 |
+
return text_only_fallback_logic(worker_chat, worker_cfg, prompt_text)
|
| 188 |
+
|
| 189 |
+
def process_task(task_path: str, result_suffix: str, pool_ref: list):
|
| 190 |
+
source_json_files = [f for f in os.listdir(task_path) if f.endswith('.json') and GENERIC_RESULT_PATTERN not in f]
|
| 191 |
+
if not source_json_files:
|
| 192 |
+
print(f" No source JSON files found in {task_path}.")
|
| 193 |
+
return
|
| 194 |
+
|
| 195 |
+
for json_filename in source_json_files:
|
| 196 |
+
dataset_json_path = os.path.join(task_path, json_filename)
|
| 197 |
+
result_json_path = os.path.join(task_path, f"{os.path.splitext(json_filename)[0]}{result_suffix}")
|
| 198 |
+
if os.path.exists(result_json_path):
|
| 199 |
+
print(f" [INFO] Result file '{os.path.basename(result_json_path)}' already exists, skipping.")
|
| 200 |
+
continue
|
| 201 |
+
|
| 202 |
+
print(f"Reading and processing dataset: {json_filename}")
|
| 203 |
+
try:
|
| 204 |
+
with open(dataset_json_path, 'r', encoding='utf-8') as f: data = json.load(f)
|
| 205 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 206 |
+
print(f" Could not read or parse JSON file {dataset_json_path}: {e}")
|
| 207 |
+
continue
|
| 208 |
+
|
| 209 |
+
all_results = []
|
| 210 |
+
for item in tqdm(data, desc=f" Processing {json_filename}"):
|
| 211 |
+
start_time = time.time()
|
| 212 |
+
model_output, prompt, ground_truth = "", "", ""
|
| 213 |
+
try:
|
| 214 |
+
prompt = item['conversations'][0]['value']
|
| 215 |
+
ground_truth = item['conversations'][1]['value']
|
| 216 |
+
media_relative_path = item.get('image') or item.get('video')
|
| 217 |
+
if not media_relative_path and 'conversations' in item and isinstance(item.get('conversations')[0], dict):
|
| 218 |
+
media_relative_path = item['conversations'][0].get('image') or item['conversations'][0].get('video')
|
| 219 |
+
|
| 220 |
+
if not media_relative_path:
|
| 221 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 222 |
+
else:
|
| 223 |
+
media_full_path = os.path.join(task_path, media_relative_path)
|
| 224 |
+
if not os.path.exists(media_full_path):
|
| 225 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 226 |
+
else:
|
| 227 |
+
async_result = pool_ref[0].apply_async(run_inference_task, args=(media_full_path, prompt))
|
| 228 |
+
try:
|
| 229 |
+
result = async_result.get(timeout=60)
|
| 230 |
+
if isinstance(result, str) and result.startswith("ERROR:"):
|
| 231 |
+
pool_ref[0].terminate()
|
| 232 |
+
pool_ref[0].join()
|
| 233 |
+
pool_ref[0] = mp.Pool(processes=1, initializer=init_worker)
|
| 234 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 235 |
+
else:
|
| 236 |
+
model_output = result
|
| 237 |
+
except mp.TimeoutError:
|
| 238 |
+
pool_ref[0].terminate()
|
| 239 |
+
pool_ref[0].join()
|
| 240 |
+
pool_ref[0] = mp.Pool(processes=1, initializer=init_worker)
|
| 241 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 242 |
+
except Exception as e:
|
| 243 |
+
model_output = f"ERROR: Main loop error: {e}"
|
| 244 |
+
print(f"\n {model_output}")
|
| 245 |
+
|
| 246 |
+
end_time = time.time()
|
| 247 |
+
all_results.append({
|
| 248 |
+
"id": item.get('id', 'N/A'), "prompt": prompt, "model_output": model_output,
|
| 249 |
+
"ground_truth": ground_truth, "processing_time_seconds": round(end_time - start_time, 2)
|
| 250 |
+
})
|
| 251 |
+
|
| 252 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 253 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 254 |
+
print(f" Task complete. Results saved to: {result_json_path}")
|
| 255 |
+
|
| 256 |
+
def main():
|
| 257 |
+
try:
|
| 258 |
+
mp.set_start_method('spawn', force=True)
|
| 259 |
+
print("Multiprocessing start method set to 'spawn'.")
|
| 260 |
+
except RuntimeError:
|
| 261 |
+
pass
|
| 262 |
+
|
| 263 |
+
parser = argparse.ArgumentParser(description="Test emotion.hallucination with AffectGPT.")
|
| 264 |
+
parser.add_argument("--result-suffix", default="_affectgpt_result.json", help="Result file suffix")
|
| 265 |
+
args = parser.parse_args()
|
| 266 |
+
|
| 267 |
+
pool = mp.Pool(processes=1, initializer=init_worker)
|
| 268 |
+
pool_ref = [pool]
|
| 269 |
+
|
| 270 |
+
try:
|
| 271 |
+
dataset_dir = "emotion_task"
|
| 272 |
+
os.chdir(dataset_dir)
|
| 273 |
+
for level_dir in LEVEL_DIRS:
|
| 274 |
+
level_path = os.path.join(dataset_dir, level_dir)
|
| 275 |
+
if not os.path.isdir(level_path): continue
|
| 276 |
+
|
| 277 |
+
task_dirs = sorted([d.path for d in os.scandir(level_path) if d.is_dir()])
|
| 278 |
+
for task_path in task_dirs:
|
| 279 |
+
process_task(task_path, args.result_suffix, pool_ref)
|
| 280 |
+
finally:
|
| 281 |
+
pool_ref[0].close()
|
| 282 |
+
pool_ref[0].join()
|
| 283 |
+
|
| 284 |
+
if __name__ == "__main__":
|
| 285 |
+
main()
|
code/test_code/test_emotionllama.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
os.environ.setdefault("CUDA_VISIBLE_DEVICES", "0")
|
| 3 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import json
|
| 7 |
+
import argparse
|
| 8 |
+
import time
|
| 9 |
+
import sys
|
| 10 |
+
from typing import List, Dict, Any
|
| 11 |
+
|
| 12 |
+
from tqdm import tqdm
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import torch
|
| 15 |
+
import torch.backends.cudnn as cudnn
|
| 16 |
+
import numpy as np
|
| 17 |
+
import signal
|
| 18 |
+
import contextlib
|
| 19 |
+
|
| 20 |
+
@contextlib.contextmanager
|
| 21 |
+
def timeout(seconds: int, error_message: str = 'Function call timed out'):
|
| 22 |
+
def _handle_timeout(signum, frame):
|
| 23 |
+
raise TimeoutError(error_message)
|
| 24 |
+
signal.signal(signal.SIGALRM, _handle_timeout)
|
| 25 |
+
signal.alarm(seconds)
|
| 26 |
+
try:
|
| 27 |
+
yield
|
| 28 |
+
finally:
|
| 29 |
+
signal.alarm(0)
|
| 30 |
+
|
| 31 |
+
class TimeoutError(Exception):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
EMOTION_LLAMA_PATH = "PATH_TO_EMOTION_LLAMA_PROJECT"
|
| 36 |
+
if EMOTION_LLAMA_PATH not in sys.path:
|
| 37 |
+
sys.path.append(EMOTION_LLAMA_PATH)
|
| 38 |
+
|
| 39 |
+
from minigpt4.common.config import Config
|
| 40 |
+
from minigpt4.common.registry import registry
|
| 41 |
+
from minigpt4.conversation.conversation import Conversation, Chat, SeparatorStyle
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
from minigpt4.datasets.builders import * # noqa
|
| 45 |
+
from minigpt4.models import * # noqa
|
| 46 |
+
from minigpt4.processors import * # noqa
|
| 47 |
+
from minigpt4.runners import * # noqa
|
| 48 |
+
from minigpt4.tasks import * # noqa
|
| 49 |
+
|
| 50 |
+
# --- Configuration ---
|
| 51 |
+
LEVEL_DIRS = ["level1", "level2", "level3"]
|
| 52 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 53 |
+
RESULT_SUFFIX = "_emotionllama_result.json"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
_TAGS = [
|
| 57 |
+
r"<s>\s*[INST]\s*", r"[/INST]",
|
| 58 |
+
r"<image>.*?</image>", r"<img>.*?</img>",
|
| 59 |
+
r"<video>.*?</video>", r"<feature>.*?</feature>",
|
| 60 |
+
r"<VideoHere>", r"<FeatureHere>",
|
| 61 |
+
r"<image>", r"</image>", r"<video>", r"</video>", r"<feature>", r"</feature>",
|
| 62 |
+
]
|
| 63 |
+
_TAGS_RE = re.compile("|".join(_TAGS), flags=re.IGNORECASE | re.DOTALL)
|
| 64 |
+
|
| 65 |
+
def clean_prompt_text(s: str) -> str:
|
| 66 |
+
s = _TAGS_RE.sub("", s).strip()
|
| 67 |
+
tail = '\nRespond ONLY with: {"emotion":"neutral|negative|positive"}'
|
| 68 |
+
if "Respond ONLY with" not in s:
|
| 69 |
+
s += tail
|
| 70 |
+
return s
|
| 71 |
+
|
| 72 |
+
_JSON_RE = re.compile(r'\{\s*"emotion"\s*:\s*"(neutral|negative|positive)"\s*\}', re.IGNORECASE)
|
| 73 |
+
def extract_emotion_json(text: str) -> str:
|
| 74 |
+
m = _JSON_RE.search(text)
|
| 75 |
+
if m:
|
| 76 |
+
return json.dumps({"emotion": m.group(1).lower()}, ensure_ascii=False)
|
| 77 |
+
low = text.lower()
|
| 78 |
+
if "negative" in low:
|
| 79 |
+
return json.dumps({"emotion": "negative"}, ensure_ascii=False)
|
| 80 |
+
if "positive" in low:
|
| 81 |
+
return json.dumps({"emotion": "positive"}, ensure_ascii=False)
|
| 82 |
+
return json.dumps({"emotion": "neutral"}, ensure_ascii=False)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
IMG_EXTS = {".jpg", ".jpeg", ".png", ".bmp", ".webp", ".gif"}
|
| 86 |
+
VID_EXTS = {".mp4", ".avi", ".mov", ".mkv", ".webm"}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def get_first_frame_pil(video_path: str):
|
| 90 |
+
import cv2
|
| 91 |
+
from PIL import Image
|
| 92 |
+
cap = cv2.VideoCapture(video_path)
|
| 93 |
+
if not cap.isOpened():
|
| 94 |
+
raise IOError(f"Cannot open video file: {video_path}")
|
| 95 |
+
ret, frame = cap.read()
|
| 96 |
+
cap.release()
|
| 97 |
+
if not ret:
|
| 98 |
+
raise IOError(f"Cannot read frame from video file: {video_path}")
|
| 99 |
+
return Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
| 100 |
+
|
| 101 |
+
def get_media_type(file_path: str) -> str:
|
| 102 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 103 |
+
if ext in VID_EXTS:
|
| 104 |
+
return 'video'
|
| 105 |
+
elif ext in IMG_EXTS:
|
| 106 |
+
return 'image'
|
| 107 |
+
else:
|
| 108 |
+
return 'unknown'
|
| 109 |
+
|
| 110 |
+
@torch.inference_mode()
|
| 111 |
+
def process_single_sample(chat: Chat, media_full_path: str, prompt_text: str) -> str:
|
| 112 |
+
try:
|
| 113 |
+
chat_state = Conversation(
|
| 114 |
+
system="",
|
| 115 |
+
roles=("<s>[INST] ", " [/INST]"),
|
| 116 |
+
messages=[],
|
| 117 |
+
offset=2,
|
| 118 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 119 |
+
sep=""
|
| 120 |
+
)
|
| 121 |
+
img_list = []
|
| 122 |
+
media_type = get_media_type(media_full_path)
|
| 123 |
+
if media_type == 'unknown':
|
| 124 |
+
raise ValueError(f"Unsupported media type: {media_full_path}")
|
| 125 |
+
|
| 126 |
+
if media_type == 'video':
|
| 127 |
+
pil_image = get_first_frame_pil(media_full_path)
|
| 128 |
+
else: # image
|
| 129 |
+
from PIL import Image
|
| 130 |
+
pil_image = Image.open(media_full_path).convert("RGB")
|
| 131 |
+
|
| 132 |
+
chat.upload_img(pil_image, chat_state, img_list)
|
| 133 |
+
|
| 134 |
+
if len(img_list) > 0:
|
| 135 |
+
chat.encode_img(img_list)
|
| 136 |
+
|
| 137 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 138 |
+
chat.ask(clean_prompt, chat_state)
|
| 139 |
+
|
| 140 |
+
model_output = chat.answer(conv=chat_state, img_list=img_list, temperature=0.1, max_new_tokens=500, max_length=2000)[0]
|
| 141 |
+
return model_output
|
| 142 |
+
except Exception as e:
|
| 143 |
+
return f"ERROR: {str(e)}"
|
| 144 |
+
|
| 145 |
+
def text_only_fallback(chat: Chat, prompt_text: str) -> str:
|
| 146 |
+
|
| 147 |
+
print(" [INFO] Executing text-only fallback...")
|
| 148 |
+
try:
|
| 149 |
+
img_list = [Image.new('RGB', (1, 1), 'black')]
|
| 150 |
+
|
| 151 |
+
chat_state = Conversation(
|
| 152 |
+
system="",
|
| 153 |
+
roles=("<s>[INST] ", " [/INST]"),
|
| 154 |
+
messages=[],
|
| 155 |
+
offset=2,
|
| 156 |
+
sep_style=SeparatorStyle.SINGLE,
|
| 157 |
+
sep=""
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
chat.encode_img(img_list)
|
| 161 |
+
|
| 162 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 163 |
+
chat.ask(clean_prompt, chat_state)
|
| 164 |
+
|
| 165 |
+
model_output = chat.answer(conv=chat_state, img_list=[], temperature=0.1, max_new_tokens=500, max_length=2000)[0]
|
| 166 |
+
return model_output
|
| 167 |
+
except Exception as e:
|
| 168 |
+
import traceback
|
| 169 |
+
traceback.print_exc()
|
| 170 |
+
return f"ERROR in text-only fallback: {str(e)}"
|
| 171 |
+
|
| 172 |
+
def process_task(task_path: str, chat: Chat):
|
| 173 |
+
print(f"\n--- Processing Task: {os.path.basename(task_path)} ---")
|
| 174 |
+
|
| 175 |
+
source_json_files = [
|
| 176 |
+
f for f in os.listdir(task_path)
|
| 177 |
+
if f.endswith(".json") and GENERIC_RESULT_PATTERN not in f and not f.endswith(RESULT_SUFFIX)
|
| 178 |
+
]
|
| 179 |
+
if not source_json_files:
|
| 180 |
+
print(f" No source JSON files found in {task_path}.")
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
for json_filename in source_json_files:
|
| 184 |
+
dataset_json_path = os.path.join(task_path, json_filename)
|
| 185 |
+
result_json_path = os.path.join(task_path, f"{os.path.splitext(json_filename)[0]}{RESULT_SUFFIX}")
|
| 186 |
+
|
| 187 |
+
if os.path.exists(result_json_path):
|
| 188 |
+
print(f" Result file already exists, skipping: {os.path.basename(result_json_path)}")
|
| 189 |
+
continue
|
| 190 |
+
|
| 191 |
+
print(f" Reading and processing dataset: {json_filename}")
|
| 192 |
+
try:
|
| 193 |
+
with open(dataset_json_path, "r", encoding="utf-8") as f:
|
| 194 |
+
data = json.load(f)
|
| 195 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 196 |
+
print(f" Could not read or parse JSON file {dataset_json_path}: {e}")
|
| 197 |
+
continue
|
| 198 |
+
|
| 199 |
+
all_results: List[Dict[str, Any]] = []
|
| 200 |
+
for item in tqdm(data, desc=f" Processing {json_filename}"):
|
| 201 |
+
start_time = time.time()
|
| 202 |
+
model_output = ""
|
| 203 |
+
prompt = ""
|
| 204 |
+
ground_truth = ""
|
| 205 |
+
try:
|
| 206 |
+
prompt = item["conversations"][0]["value"]
|
| 207 |
+
ground_truth = item["conversations"][1]["value"]
|
| 208 |
+
|
| 209 |
+
media_relative_path = None
|
| 210 |
+
|
| 211 |
+
if 'image' in item:
|
| 212 |
+
media_relative_path = item.get('image')
|
| 213 |
+
elif 'video' in item:
|
| 214 |
+
media_relative_path = item.get('video')
|
| 215 |
+
|
| 216 |
+
elif 'conversations' in item and item['conversations'] and isinstance(item['conversations'][0], dict):
|
| 217 |
+
conv0 = item['conversations'][0]
|
| 218 |
+
if 'image' in conv0:
|
| 219 |
+
media_relative_path = conv0.get('image')
|
| 220 |
+
elif 'video' in conv0:
|
| 221 |
+
media_relative_path = conv0.get('video')
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
if not media_relative_path:
|
| 225 |
+
print(f"\n Could not find media key for item {item.get('id', 'N/A')}. Falling back to text-only.")
|
| 226 |
+
model_output = text_only_fallback(chat=chat, prompt_text=prompt)
|
| 227 |
+
else:
|
| 228 |
+
media_full_path = os.path.join(task_path, media_relative_path)
|
| 229 |
+
if not os.path.exists(media_full_path):
|
| 230 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 231 |
+
|
| 232 |
+
try:
|
| 233 |
+
with timeout(seconds=300):
|
| 234 |
+
model_output = process_single_sample(
|
| 235 |
+
chat=chat,
|
| 236 |
+
media_full_path=media_full_path,
|
| 237 |
+
prompt_text=prompt,
|
| 238 |
+
)
|
| 239 |
+
except TimeoutError:
|
| 240 |
+
print(f"\n Processing timed out for item {item.get('id', 'N/A')}. Falling back to text-only.")
|
| 241 |
+
model_output = text_only_fallback(
|
| 242 |
+
chat=chat,
|
| 243 |
+
prompt_text=prompt
|
| 244 |
+
)
|
| 245 |
+
except Exception as e:
|
| 246 |
+
model_output = f"ERROR: {str(e)}"
|
| 247 |
+
|
| 248 |
+
end_time = time.time()
|
| 249 |
+
all_results.append({
|
| 250 |
+
"id": item.get("id", "N/A"),
|
| 251 |
+
"prompt": prompt,
|
| 252 |
+
"model_output": model_output,
|
| 253 |
+
"ground_truth": ground_truth,
|
| 254 |
+
"processing_time_seconds": round(end_time - start_time, 2),
|
| 255 |
+
})
|
| 256 |
+
|
| 257 |
+
with open(result_json_path, "w", encoding="utf-8") as f:
|
| 258 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 259 |
+
print(f"Task complete. Results saved to: {result_json_path}")
|
| 260 |
+
|
| 261 |
+
def init_model(cfg_path: str, device: str):
|
| 262 |
+
|
| 263 |
+
if not torch.cuda.is_available():
|
| 264 |
+
print("CUDA is not available.")
|
| 265 |
+
sys.exit(1)
|
| 266 |
+
|
| 267 |
+
args = argparse.Namespace(cfg_path=cfg_path, options=None)
|
| 268 |
+
cfg = Config(args)
|
| 269 |
+
model_config = cfg.model_cfg
|
| 270 |
+
|
| 271 |
+
model_config.low_resource = False
|
| 272 |
+
|
| 273 |
+
model_cls = registry.get_model_class(model_config.arch)
|
| 274 |
+
model = model_cls.from_config(model_config).to(device)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
torch.backends.cuda.matmul.allow_tf32 = False
|
| 278 |
+
torch.backends.cudnn.allow_tf32 = False
|
| 279 |
+
|
| 280 |
+
import contextlib
|
| 281 |
+
@contextlib.contextmanager
|
| 282 |
+
def _fp16_autocast_cm():
|
| 283 |
+
with torch.amp.autocast('cuda', dtype=torch.float16):
|
| 284 |
+
yield
|
| 285 |
+
model.maybe_autocast = lambda *a, **k: _fp16_autocast_cm()
|
| 286 |
+
|
| 287 |
+
# Initialize visual processor
|
| 288 |
+
try:
|
| 289 |
+
vis_processor_cfg = cfg.datasets_cfg.feature_face_caption.vis_processor.train
|
| 290 |
+
except Exception:
|
| 291 |
+
vis_processor_cfg = cfg.datasets_cfg.cc_align.vis_processor.train
|
| 292 |
+
vis_processor = registry.get_processor_class(vis_processor_cfg.name).from_config(vis_processor_cfg)
|
| 293 |
+
|
| 294 |
+
model.eval()
|
| 295 |
+
chat = Chat(model, vis_processor, device=device)
|
| 296 |
+
|
| 297 |
+
if hasattr(chat, "answer_prepare"):
|
| 298 |
+
_orig_answer_prepare = chat.answer_prepare
|
| 299 |
+
|
| 300 |
+
def _answer_prepare_sane(*args, **kwargs):
|
| 301 |
+
out = _orig_answer_prepare(*args, **kwargs)
|
| 302 |
+
if isinstance(out, dict) and "inputs_embeds" in out:
|
| 303 |
+
emb = out["inputs_embeds"]
|
| 304 |
+
if isinstance(emb, torch.Tensor):
|
| 305 |
+
ref_param = next(model.llama_model.parameters())
|
| 306 |
+
target_device = ref_param.device
|
| 307 |
+
target_dtype = ref_param.dtype
|
| 308 |
+
emb = emb.to(device=target_device, dtype=target_dtype).contiguous()
|
| 309 |
+
out["inputs_embeds"] = emb
|
| 310 |
+
|
| 311 |
+
for k in ("do_sample", "top_p", "repetition_penalty", "length_penalty", "num_beams"):
|
| 312 |
+
out.pop(k, None)
|
| 313 |
+
return out
|
| 314 |
+
|
| 315 |
+
chat.answer_prepare = _answer_prepare_sane
|
| 316 |
+
return chat, cfg
|
| 317 |
+
|
| 318 |
+
# ---------------- Main Function ----------------
|
| 319 |
+
def main():
|
| 320 |
+
parser = argparse.ArgumentParser(description="Batch inference for task with Emotion-LLaMA.")
|
| 321 |
+
parser.add_argument(
|
| 322 |
+
"--cfg-path",
|
| 323 |
+
default=os.path.join(EMOTION_LLAMA_PATH, " example_config/demo.yaml"),
|
| 324 |
+
help="Path to the Emotion-LLaMA configuration file.",
|
| 325 |
+
)
|
| 326 |
+
parser.add_argument("--max_new_tokens", type=int, default=32)
|
| 327 |
+
parser.add_argument("--max_length", type=int, default=1024)
|
| 328 |
+
parser.add_argument("--temperature", type=float, default=0.1)
|
| 329 |
+
parser.add_argument("--device", default="cuda:0", help="Device to run on.")
|
| 330 |
+
args = parser.parse_args()
|
| 331 |
+
|
| 332 |
+
if "cuda" in args.device:
|
| 333 |
+
if not torch.cuda.is_available():
|
| 334 |
+
print(f"CUDA device '{args.device}' is not available.")
|
| 335 |
+
sys.exit(1)
|
| 336 |
+
torch.cuda.set_device(args.device)
|
| 337 |
+
|
| 338 |
+
chat, cfg = init_model(args.cfg_path, args.device)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
dataset_dir = os.getcwd()
|
| 342 |
+
print(f"Running in directory: {dataset_dir}")
|
| 343 |
+
|
| 344 |
+
for level_dir in LEVEL_DIRS:
|
| 345 |
+
level_path = os.path.join(dataset_dir, level_dir)
|
| 346 |
+
if not os.path.isdir(level_path):
|
| 347 |
+
continue
|
| 348 |
+
|
| 349 |
+
task_dirs = sorted([d.path for d in os.scandir(level_path) if d.is_dir()])
|
| 350 |
+
for task_path in task_dirs:
|
| 351 |
+
process_task(
|
| 352 |
+
task_path,
|
| 353 |
+
chat,
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
if __name__ == "__main__":
|
| 358 |
+
random_seed = 42
|
| 359 |
+
np.random.seed(random_seed)
|
| 360 |
+
torch.manual_seed(random_seed)
|
| 361 |
+
cudnn.benchmark = False
|
| 362 |
+
cudnn.deterministic = True
|
| 363 |
+
|
| 364 |
+
main()
|
code/test_code/test_gemini_2.5_flash.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from google import genai
|
| 8 |
+
|
| 9 |
+
# --- Configuration ---
|
| 10 |
+
LEVEL_DIRS = ["level1", "level2", "level3"]
|
| 11 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 12 |
+
|
| 13 |
+
INLINE_SIZE_LIMIT_BYTES = 20 * 1024 * 1024
|
| 14 |
+
|
| 15 |
+
MODEL_NAME = "gemini-2.5-flash"
|
| 16 |
+
RESULT_SUFFIX = f"_{MODEL_NAME.replace('.', '_')}_result.json"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def get_mime_type(file_path: str) -> str:
|
| 20 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 21 |
+
|
| 22 |
+
# ---- Video ----
|
| 23 |
+
if ext in [".mp4", ".m4v", ".mov", ".avi", ".mkv", ".webm", ".mpg", ".mpeg", ".wmv", ".3gp", ".3gpp", ".flv"]:
|
| 24 |
+
return "video/mp4"
|
| 25 |
+
|
| 26 |
+
# ---- Audio ----
|
| 27 |
+
if ext in [".mp3", ".wav", ".aac", ".aiff", ".flac", ".ogg"]:
|
| 28 |
+
if ext == ".mp3":
|
| 29 |
+
return "audio/mp3"
|
| 30 |
+
if ext == ".wav":
|
| 31 |
+
return "audio/wav"
|
| 32 |
+
if ext == ".aac":
|
| 33 |
+
return "audio/aac"
|
| 34 |
+
if ext == ".aiff":
|
| 35 |
+
return "audio/aiff"
|
| 36 |
+
if ext == ".flac":
|
| 37 |
+
return "audio/flac"
|
| 38 |
+
if ext == ".ogg":
|
| 39 |
+
return "audio/ogg"
|
| 40 |
+
|
| 41 |
+
# ---- Image ----
|
| 42 |
+
if ext in [".jpg", ".jpeg"]:
|
| 43 |
+
return "image/jpeg"
|
| 44 |
+
if ext == ".png":
|
| 45 |
+
return "image/png"
|
| 46 |
+
if ext == ".webp":
|
| 47 |
+
return "image/webp"
|
| 48 |
+
if ext == ".gif":
|
| 49 |
+
return "image/gif"
|
| 50 |
+
|
| 51 |
+
return "application/octet-stream"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _poll_file_ready(client: genai.Client, file_obj, sleep_s: float = 2.0, max_wait_s: float = 300.0) -> Optional[object]:
|
| 55 |
+
start = time.time()
|
| 56 |
+
name = getattr(file_obj, "name", None)
|
| 57 |
+
state = getattr(file_obj, "state", None)
|
| 58 |
+
state_name = getattr(state, "name", None) or str(state)
|
| 59 |
+
|
| 60 |
+
while state_name and state_name.upper() in ("PROCESSING", "PENDING"):
|
| 61 |
+
if time.time() - start > max_wait_s:
|
| 62 |
+
return None
|
| 63 |
+
time.sleep(sleep_s)
|
| 64 |
+
try:
|
| 65 |
+
file_obj = client.files.get(name=name)
|
| 66 |
+
except Exception:
|
| 67 |
+
time.sleep(sleep_s)
|
| 68 |
+
state = getattr(file_obj, "state", None)
|
| 69 |
+
state_name = getattr(state, "name", None) or str(state)
|
| 70 |
+
|
| 71 |
+
return file_obj
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def process_single_sample(client: genai.Client, media_full_path: str, prompt_text: str) -> str:
|
| 75 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 76 |
+
file_size = os.path.getsize(media_full_path)
|
| 77 |
+
mime_type = get_mime_type(media_full_path)
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
if file_size < INLINE_SIZE_LIMIT_BYTES:
|
| 81 |
+
print(f"\n File size ({file_size / 1024**2:.2f} MB) is under limit. Using inline method.")
|
| 82 |
+
with open(media_full_path, "rb") as f:
|
| 83 |
+
file_bytes = f.read()
|
| 84 |
+
|
| 85 |
+
media_part = genai.types.Part(
|
| 86 |
+
inline_data=genai.types.Blob(data=file_bytes, mime_type=mime_type)
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
response = client.models.generate_content(
|
| 90 |
+
model=MODEL_NAME,
|
| 91 |
+
contents=[
|
| 92 |
+
media_part,
|
| 93 |
+
genai.types.Part(text=clean_prompt),
|
| 94 |
+
],
|
| 95 |
+
)
|
| 96 |
+
return getattr(response, "text", str(response))
|
| 97 |
+
|
| 98 |
+
else:
|
| 99 |
+
print(f"\n File size ({file_size / 1024**2:.2f} MB) exceeds limit. Using File API.")
|
| 100 |
+
uploaded_file = None
|
| 101 |
+
try:
|
| 102 |
+
print(f" Uploading: {os.path.basename(media_full_path)} ...")
|
| 103 |
+
uploaded_file = client.files.upload(file=media_full_path)
|
| 104 |
+
|
| 105 |
+
uploaded_file = _poll_file_ready(client, uploaded_file)
|
| 106 |
+
if uploaded_file is None:
|
| 107 |
+
raise RuntimeError("File processing timeout in Files API.")
|
| 108 |
+
|
| 109 |
+
print(" File is ready. Generating content ...")
|
| 110 |
+
response = client.models.generate_content(
|
| 111 |
+
model=MODEL_NAME,
|
| 112 |
+
contents=[
|
| 113 |
+
uploaded_file,
|
| 114 |
+
genai.types.Part(text=clean_prompt)
|
| 115 |
+
],
|
| 116 |
+
)
|
| 117 |
+
return getattr(response, "text", str(response))
|
| 118 |
+
finally:
|
| 119 |
+
try:
|
| 120 |
+
if uploaded_file and getattr(uploaded_file, "name", None):
|
| 121 |
+
print(f" Deleting uploaded file: {uploaded_file.name}")
|
| 122 |
+
client.files.delete(name=uploaded_file.name)
|
| 123 |
+
except Exception as _e:
|
| 124 |
+
print(f" Failed to delete uploaded file: {_e}")
|
| 125 |
+
|
| 126 |
+
except Exception as e:
|
| 127 |
+
return f"ERROR: {str(e)}"
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def process_task(task_path: str, client: genai.Client):
|
| 131 |
+
|
| 132 |
+
source_json_files = [
|
| 133 |
+
f for f in os.listdir(task_path)
|
| 134 |
+
if f.endswith(".json") and GENERIC_RESULT_PATTERN not in f
|
| 135 |
+
]
|
| 136 |
+
if not source_json_files:
|
| 137 |
+
print(f" No source JSON files found in {task_path}.")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
for json_filename in source_json_files:
|
| 141 |
+
dataset_json_path = os.path.join(task_path, json_filename)
|
| 142 |
+
result_json_path = os.path.join(task_path, f"{os.path.splitext(json_filename)[0]}{RESULT_SUFFIX}")
|
| 143 |
+
|
| 144 |
+
if os.path.exists(result_json_path):
|
| 145 |
+
print(f" Result file already exists, skipping: {os.path.basename(result_json_path)}")
|
| 146 |
+
continue
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
with open(dataset_json_path, "r", encoding="utf-8") as f:
|
| 150 |
+
data = json.load(f)
|
| 151 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 152 |
+
print(f" Could not read or parse JSON file {dataset_json_path}: {e}")
|
| 153 |
+
continue
|
| 154 |
+
|
| 155 |
+
all_results = []
|
| 156 |
+
for item in tqdm(data, desc=f" Processing {json_filename}"):
|
| 157 |
+
start_time = time.time()
|
| 158 |
+
model_output = ""
|
| 159 |
+
prompt = ""
|
| 160 |
+
ground_truth = ""
|
| 161 |
+
try:
|
| 162 |
+
prompt = item["conversations"][0]["value"]
|
| 163 |
+
ground_truth = item["conversations"][1]["value"]
|
| 164 |
+
media_path_key = "image" if "image" in item else "video"
|
| 165 |
+
media_relative_path = item.get(media_path_key)
|
| 166 |
+
if not media_relative_path:
|
| 167 |
+
raise ValueError("Missing 'image' or 'video' key in JSON item.")
|
| 168 |
+
|
| 169 |
+
media_full_path = os.path.join(task_path, media_relative_path)
|
| 170 |
+
if not os.path.exists(media_full_path):
|
| 171 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 172 |
+
|
| 173 |
+
model_output = process_single_sample(client, media_full_path, prompt)
|
| 174 |
+
|
| 175 |
+
except Exception as e:
|
| 176 |
+
model_output = f"ERROR: {str(e)}"
|
| 177 |
+
print(f" Failed to process item {item.get('id', 'N/A')}: {e}")
|
| 178 |
+
|
| 179 |
+
end_time = time.time()
|
| 180 |
+
all_results.append({
|
| 181 |
+
"id": item.get("id", "N/A"),
|
| 182 |
+
"prompt": prompt,
|
| 183 |
+
"model_output": model_output,
|
| 184 |
+
"ground_truth": ground_truth,
|
| 185 |
+
"processing_time_seconds": round(end_time - start_time, 2),
|
| 186 |
+
})
|
| 187 |
+
|
| 188 |
+
with open(result_json_path, "w", encoding="utf-8") as f:
|
| 189 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 190 |
+
print(f" Task complete. Results saved to: {result_json_path}")
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def main():
|
| 194 |
+
parser = argparse.ArgumentParser(
|
| 195 |
+
description=f"Test emotion.hallucination with {MODEL_NAME}, auto-selecting media strategy (google-genai)."
|
| 196 |
+
)
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--api-key",
|
| 199 |
+
default=os.getenv("GOOGLE_API_KEY", "KEY"),
|
| 200 |
+
help="Google Gemini API key (or set the GOOGLE_API_KEY environment variable)."
|
| 201 |
+
)
|
| 202 |
+
args = parser.parse_args()
|
| 203 |
+
|
| 204 |
+
if not args.api_key or args.api_key == "KEY":
|
| 205 |
+
print("\nPlease provide your Google Gemini API key via the --api-key argument or by setting the GOOGLE_API_KEY environment variable.")
|
| 206 |
+
return
|
| 207 |
+
|
| 208 |
+
try:
|
| 209 |
+
client = genai.Client(api_key=args.api_key)
|
| 210 |
+
except Exception as e:
|
| 211 |
+
print(f"Failed to initialize Gemini client: {e}")
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
dataset_dir = os.getcwd()
|
| 215 |
+
|
| 216 |
+
for level_dir in LEVEL_DIRS:
|
| 217 |
+
level_path = os.path.join(dataset_dir, level_dir)
|
| 218 |
+
if not os.path.isdir(level_path):
|
| 219 |
+
continue
|
| 220 |
+
|
| 221 |
+
task_dirs = sorted([d.path for d in os.scandir(level_path) if d.is_dir()])
|
| 222 |
+
for task_path in task_dirs:
|
| 223 |
+
process_task(task_path, client)
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
main()
|
code/test_code/test_gemini_2.5_pro.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from google import genai
|
| 8 |
+
|
| 9 |
+
# --- Configuration ---
|
| 10 |
+
LEVEL_DIRS = ["level1", "level2", "level3"]
|
| 11 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 12 |
+
PROMPT_IMAGE_PLACEHOLDER = "<image>"
|
| 13 |
+
PROMPT_VIDEO_PLACEHOLDER = "<video>"
|
| 14 |
+
|
| 15 |
+
INLINE_SIZE_LIMIT_BYTES = 20 * 1024 * 1024
|
| 16 |
+
|
| 17 |
+
MODEL_NAME = "gemini-2.5-pro"
|
| 18 |
+
RESULT_SUFFIX = "_gemini_2.5_pro_result.json"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_mime_type(file_path: str) -> str:
|
| 22 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 23 |
+
|
| 24 |
+
# --- Video ---
|
| 25 |
+
if ext in [".mp4", ".m4v", ".mov", ".avi", ".mkv", ".webm", ".mpg", ".mpeg", ".wmv", ".3gp", ".3gpp", ".flv"]:
|
| 26 |
+
return "video/mp4"
|
| 27 |
+
|
| 28 |
+
# --- Audio ---
|
| 29 |
+
if ext in [".mp3", ".wav", ".aac", ".aiff", ".flac", ".ogg"]:
|
| 30 |
+
return f"audio/{ext[1:]}"
|
| 31 |
+
|
| 32 |
+
# --- Image ---
|
| 33 |
+
if ext in [".jpg", ".jpeg"]:
|
| 34 |
+
return "image/jpeg"
|
| 35 |
+
if ext in [".png", ".webp", ".gif"]:
|
| 36 |
+
return f"image/{ext[1:]}"
|
| 37 |
+
|
| 38 |
+
return "application/octet-stream"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _poll_file_ready(client: genai.Client, file_obj, sleep_s: float = 2.0, max_wait_s: float = 300.0) -> Optional[object]:
|
| 42 |
+
start_time = time.time()
|
| 43 |
+
name = getattr(file_obj, "name", None)
|
| 44 |
+
if not name:
|
| 45 |
+
return file_obj
|
| 46 |
+
|
| 47 |
+
while time.time() - start_time < max_wait_s:
|
| 48 |
+
state = getattr(file_obj, "state", None)
|
| 49 |
+
state_name = getattr(state, "name", None) or str(state)
|
| 50 |
+
|
| 51 |
+
if state_name.upper() not in ("PROCESSING", "PENDING"):
|
| 52 |
+
|
| 53 |
+
return file_obj
|
| 54 |
+
|
| 55 |
+
time.sleep(sleep_s)
|
| 56 |
+
try:
|
| 57 |
+
file_obj = client.files.get(name=name)
|
| 58 |
+
except Exception:
|
| 59 |
+
|
| 60 |
+
time.sleep(sleep_s)
|
| 61 |
+
|
| 62 |
+
return None
|
| 63 |
+
|
| 64 |
+
def process_single_sample(client: genai.Client, media_full_path: str, prompt_text: str) -> str:
|
| 65 |
+
|
| 66 |
+
clean_prompt = prompt_text.replace(PROMPT_IMAGE_PLACEHOLDER, "").replace(PROMPT_VIDEO_PLACEHOLDER, "").strip()
|
| 67 |
+
file_size = os.path.getsize(media_full_path)
|
| 68 |
+
mime_type = get_mime_type(media_full_path)
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
if file_size < INLINE_SIZE_LIMIT_BYTES:
|
| 72 |
+
print(f"\n [INFO] File size ({file_size / 1024**2:.2f} MB) is under limit. Using inline method.")
|
| 73 |
+
with open(media_full_path, "rb") as f:
|
| 74 |
+
media_part = genai.types.Part(
|
| 75 |
+
inline_data=genai.types.Blob(data=f.read(), mime_type=mime_type)
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
contents = [media_part, genai.types.Part(text=clean_prompt)]
|
| 79 |
+
response = client.models.generate_content(model=MODEL_NAME, contents=contents)
|
| 80 |
+
return getattr(response, "text", str(response))
|
| 81 |
+
|
| 82 |
+
else:
|
| 83 |
+
print(f"\n File size ({file_size / 1024**2:.2f} MB) exceeds limit. Using File API.")
|
| 84 |
+
uploaded_file = None
|
| 85 |
+
try:
|
| 86 |
+
print(f" Uploading: {os.path.basename(media_full_path)}...")
|
| 87 |
+
uploaded_file = client.files.upload(file_path=media_full_path)
|
| 88 |
+
|
| 89 |
+
uploaded_file = _poll_file_ready(client, uploaded_file)
|
| 90 |
+
if uploaded_file is None:
|
| 91 |
+
raise RuntimeError("File processing timed out in Files API.")
|
| 92 |
+
|
| 93 |
+
print(" File is ready. Generating content...")
|
| 94 |
+
contents = [uploaded_file, genai.types.Part(text=clean_prompt)]
|
| 95 |
+
response = client.models.generate_content(model=MODEL_NAME, contents=contents)
|
| 96 |
+
return getattr(response, "text", str(response))
|
| 97 |
+
finally:
|
| 98 |
+
if uploaded_file and getattr(uploaded_file, "name", None):
|
| 99 |
+
try:
|
| 100 |
+
print(f" Deleting uploaded file: {uploaded_file.name}")
|
| 101 |
+
client.files.delete(name=uploaded_file.name)
|
| 102 |
+
except Exception as e:
|
| 103 |
+
print(f" Failed to delete uploaded file: {e}")
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
print(f" An error occurred during Gemini processing: {e}")
|
| 107 |
+
return f"ERROR: {str(e)}"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def process_task(task_path: str, client: genai.Client):
|
| 111 |
+
|
| 112 |
+
source_json_files = [
|
| 113 |
+
f for f in os.listdir(task_path)
|
| 114 |
+
if f.endswith(".json") and GENERIC_RESULT_PATTERN not in f
|
| 115 |
+
]
|
| 116 |
+
if not source_json_files:
|
| 117 |
+
print(f" No source JSON files found in {task_path}.")
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
for json_filename in source_json_files:
|
| 121 |
+
dataset_json_path = os.path.join(task_path, json_filename)
|
| 122 |
+
result_json_path = os.path.join(task_path, f"{os.path.splitext(json_filename)[0]}{RESULT_SUFFIX}")
|
| 123 |
+
|
| 124 |
+
if os.path.exists(result_json_path):
|
| 125 |
+
print(f" Result file already exists, skipping: {os.path.basename(result_json_path)}")
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
print(f" Reading and processing dataset: {json_filename}")
|
| 129 |
+
try:
|
| 130 |
+
with open(dataset_json_path, "r", encoding="utf-8") as f:
|
| 131 |
+
data = json.load(f)
|
| 132 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 133 |
+
print(f"Could not read or parse JSON file {dataset_json_path}: {e}")
|
| 134 |
+
continue
|
| 135 |
+
|
| 136 |
+
all_results = []
|
| 137 |
+
for item in tqdm(data, desc=f" Processing {json_filename}"):
|
| 138 |
+
start_time = time.time()
|
| 139 |
+
model_output = ""
|
| 140 |
+
prompt = ""
|
| 141 |
+
ground_truth = ""
|
| 142 |
+
try:
|
| 143 |
+
prompt = item["conversations"][0]["value"]
|
| 144 |
+
ground_truth = item["conversations"][1]["value"]
|
| 145 |
+
|
| 146 |
+
media_path_key = "image" if "image" in item else "video"
|
| 147 |
+
media_relative_path = item.get(media_path_key)
|
| 148 |
+
if not media_relative_path:
|
| 149 |
+
raise ValueError("Missing 'image' or 'video' key in JSON item.")
|
| 150 |
+
|
| 151 |
+
media_full_path = os.path.join(task_path, media_relative_path)
|
| 152 |
+
if not os.path.exists(media_full_path):
|
| 153 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 154 |
+
|
| 155 |
+
model_output = process_single_sample(client, media_full_path, prompt)
|
| 156 |
+
|
| 157 |
+
except Exception as e:
|
| 158 |
+
model_output = f"ERROR: {str(e)}"
|
| 159 |
+
print(f" Failed to process item {item.get('id', 'N/A')}: {e}")
|
| 160 |
+
|
| 161 |
+
end_time = time.time()
|
| 162 |
+
all_results.append({
|
| 163 |
+
"id": item.get("id", "N/A"),
|
| 164 |
+
"prompt": prompt,
|
| 165 |
+
"model_output": model_output,
|
| 166 |
+
"ground_truth": ground_truth,
|
| 167 |
+
"processing_time_seconds": round(end_time - start_time, 2),
|
| 168 |
+
})
|
| 169 |
+
|
| 170 |
+
with open(result_json_path, "w", encoding="utf-8") as f:
|
| 171 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 172 |
+
print(f" Task complete. Results saved to: {result_json_path}")
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def main():
|
| 176 |
+
|
| 177 |
+
parser = argparse.ArgumentParser(
|
| 178 |
+
description=f"Run batch inference on datasets using the Google Gemini '{MODEL_NAME}' model."
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--api-key",
|
| 182 |
+
default=os.getenv("GOOGLE_API_KEY", "GEMINI_API_KEY"),
|
| 183 |
+
help="Google Gemini API key. Can also be set via the GOOGLE_API_KEY environment variable."
|
| 184 |
+
)
|
| 185 |
+
args = parser.parse_args()
|
| 186 |
+
|
| 187 |
+
if not args.api_key or args.api_key == "GEMINI_API_KEY":
|
| 188 |
+
return
|
| 189 |
+
|
| 190 |
+
try:
|
| 191 |
+
genai.configure(api_key=args.api_key)
|
| 192 |
+
client = genai.GenerativeModel(MODEL_NAME)
|
| 193 |
+
except Exception as e:
|
| 194 |
+
print(f"Failed to initialize Gemini client: {e}")
|
| 195 |
+
return
|
| 196 |
+
|
| 197 |
+
dataset_dir = os.getcwd()
|
| 198 |
+
print(f"Running in directory: {dataset_dir}")
|
| 199 |
+
|
| 200 |
+
for level_dir in LEVEL_DIRS:
|
| 201 |
+
level_path = os.path.join(dataset_dir, level_dir)
|
| 202 |
+
if not os.path.isdir(level_path):
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
task_dirs = sorted([d.path for d in os.scandir(level_path) if d.is_dir()])
|
| 206 |
+
for task_path in task_dirs:
|
| 207 |
+
process_task(task_path, client)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
main()
|
code/test_code/test_gpt41.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import base64
|
| 5 |
+
import cv2
|
| 6 |
+
import tempfile
|
| 7 |
+
import subprocess
|
| 8 |
+
import shutil
|
| 9 |
+
import io
|
| 10 |
+
import time
|
| 11 |
+
import glob
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
def get_media_type(file_path: str) -> str:
|
| 17 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 18 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 19 |
+
return 'video'
|
| 20 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 21 |
+
return 'image'
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError(f"Unsupported file format: {ext}")
|
| 24 |
+
|
| 25 |
+
def encode_media_to_base64(media_path: str) -> str:
|
| 26 |
+
try:
|
| 27 |
+
with open(media_path, "rb") as media_file:
|
| 28 |
+
return base64.b64encode(media_file.read()).decode('utf-8')
|
| 29 |
+
except Exception as e:
|
| 30 |
+
raise IOError(f"Could not read or encode file {media_path}: {e}")
|
| 31 |
+
|
| 32 |
+
def extract_keyframes(video_path: str, max_frames: int = 20) -> list:
|
| 33 |
+
cap = cv2.VideoCapture(video_path)
|
| 34 |
+
if not cap.isOpened():
|
| 35 |
+
raise ValueError(f"Cannot open video file: {video_path}")
|
| 36 |
+
|
| 37 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 38 |
+
video_fps = cap.get(cv2.CAP_PROP_FPS)
|
| 39 |
+
duration = total_frames / video_fps if video_fps > 0 else 0
|
| 40 |
+
|
| 41 |
+
if duration <= 20:
|
| 42 |
+
target_frames = min(max_frames, int(duration))
|
| 43 |
+
frame_interval = max(1, int(video_fps))
|
| 44 |
+
else:
|
| 45 |
+
target_frames = max_frames
|
| 46 |
+
frame_interval = max(1, int(total_frames / max_frames))
|
| 47 |
+
|
| 48 |
+
keyframes = []
|
| 49 |
+
frame_count = 0
|
| 50 |
+
sampled_count = 0
|
| 51 |
+
while sampled_count < target_frames:
|
| 52 |
+
ret, frame = cap.read()
|
| 53 |
+
if not ret:
|
| 54 |
+
break
|
| 55 |
+
|
| 56 |
+
if frame_count % frame_interval == 0:
|
| 57 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 58 |
+
pil_image = Image.fromarray(frame_rgb)
|
| 59 |
+
keyframes.append(pil_image)
|
| 60 |
+
sampled_count += 1
|
| 61 |
+
|
| 62 |
+
frame_count += 1
|
| 63 |
+
|
| 64 |
+
cap.release()
|
| 65 |
+
print(f" Extracted {len(keyframes)} keyframes.")
|
| 66 |
+
return keyframes
|
| 67 |
+
|
| 68 |
+
def extract_audio_to_text(video_path: str, client: OpenAI) -> str:
|
| 69 |
+
temp_audio_path = ""
|
| 70 |
+
try:
|
| 71 |
+
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_audio:
|
| 72 |
+
temp_audio_path = temp_audio.name
|
| 73 |
+
|
| 74 |
+
command = [
|
| 75 |
+
'ffmpeg', '-i', video_path, '-vn', '-acodec', 'mp3',
|
| 76 |
+
'-ar', '16000', '-ac', '1', '-y', temp_audio_path
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
result = subprocess.run(command, capture_output=True, text=True, check=False)
|
| 80 |
+
if result.returncode != 0:
|
| 81 |
+
print(f" [WARN] Ffmpeg audio extraction failed: {result.stderr}")
|
| 82 |
+
return "Audio extraction failed."
|
| 83 |
+
|
| 84 |
+
with open(temp_audio_path, 'rb') as audio_file:
|
| 85 |
+
transcription = client.audio.transcriptions.create(
|
| 86 |
+
model="whisper-1",
|
| 87 |
+
file=audio_file,
|
| 88 |
+
response_format="text"
|
| 89 |
+
)
|
| 90 |
+
return transcription
|
| 91 |
+
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f" Audio processing failed: {e}")
|
| 94 |
+
return "Audio processing failed."
|
| 95 |
+
finally:
|
| 96 |
+
if temp_audio_path and os.path.exists(temp_audio_path):
|
| 97 |
+
os.unlink(temp_audio_path)
|
| 98 |
+
|
| 99 |
+
def process_dataset(dataset_path: str, client: OpenAI, model_name: str, result_suffix: str):
|
| 100 |
+
|
| 101 |
+
result_path = f"{os.path.splitext(dataset_path)[0]}{result_suffix}"
|
| 102 |
+
|
| 103 |
+
if os.path.exists(result_path):
|
| 104 |
+
print(f"Result file '{os.path.basename(result_path)}' already exists. Skipping.")
|
| 105 |
+
return
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
with open(dataset_path, 'r', encoding='utf-8') as f:
|
| 109 |
+
data = json.load(f)
|
| 110 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 111 |
+
print(f" Could not read or parse JSON file {dataset_path}: {e}")
|
| 112 |
+
return
|
| 113 |
+
|
| 114 |
+
all_results = []
|
| 115 |
+
base_dir = os.path.dirname(dataset_path)
|
| 116 |
+
|
| 117 |
+
for item in tqdm(data, desc=f"Processing items from {os.path.basename(dataset_path)}"):
|
| 118 |
+
start_time = time.time()
|
| 119 |
+
model_output = ""
|
| 120 |
+
try:
|
| 121 |
+
prompt = item['conversations'][0]['value']
|
| 122 |
+
ground_truth = item['conversations'][1]['value']
|
| 123 |
+
media_key = 'image' if 'image' in item else 'video'
|
| 124 |
+
media_relative_path = item.get(media_key)
|
| 125 |
+
|
| 126 |
+
if not media_relative_path:
|
| 127 |
+
raise ValueError("JSON item is missing 'image' or 'video' key.")
|
| 128 |
+
|
| 129 |
+
media_full_path = os.path.join(base_dir, media_relative_path)
|
| 130 |
+
if not os.path.exists(media_full_path):
|
| 131 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 132 |
+
|
| 133 |
+
media_type = get_media_type(media_full_path)
|
| 134 |
+
clean_prompt = prompt.replace("<image>", "").replace("<video>", "").strip()
|
| 135 |
+
|
| 136 |
+
messages = []
|
| 137 |
+
if media_type == 'image':
|
| 138 |
+
base64_media = encode_media_to_base64(media_full_path)
|
| 139 |
+
messages = [{
|
| 140 |
+
"role": "user",
|
| 141 |
+
"content": [
|
| 142 |
+
{"type": "text", "text": clean_prompt},
|
| 143 |
+
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_media}"}}
|
| 144 |
+
]
|
| 145 |
+
}]
|
| 146 |
+
else:
|
| 147 |
+
print(f"\n [INFO] Processing video: {os.path.basename(media_full_path)}")
|
| 148 |
+
keyframes = extract_keyframes(media_full_path)
|
| 149 |
+
audio_text = extract_audio_to_text(media_full_path, client)
|
| 150 |
+
|
| 151 |
+
enhanced_prompt = f"""Please analyze the following video content:
|
| 152 |
+
|
| 153 |
+
Original question: {clean_prompt}
|
| 154 |
+
|
| 155 |
+
Transcribed audio from the video:
|
| 156 |
+
"{audio_text}"
|
| 157 |
+
|
| 158 |
+
Analyze the keyframes and the audio transcription to provide a comprehensive answer."""
|
| 159 |
+
|
| 160 |
+
content = [{"type": "text", "text": enhanced_prompt}]
|
| 161 |
+
for frame in keyframes:
|
| 162 |
+
buffer = io.BytesIO()
|
| 163 |
+
frame.save(buffer, format='JPEG', quality=85)
|
| 164 |
+
frame_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
|
| 165 |
+
content.append({
|
| 166 |
+
"type": "image_url",
|
| 167 |
+
"image_url": {"url": f"data:image/jpeg;base64,{frame_base64}"}
|
| 168 |
+
})
|
| 169 |
+
|
| 170 |
+
messages = [{"role": "user", "content": content}]
|
| 171 |
+
|
| 172 |
+
response = client.chat.completions.create(
|
| 173 |
+
model=model_name,
|
| 174 |
+
messages=messages,
|
| 175 |
+
max_tokens=1024,
|
| 176 |
+
temperature=0.0
|
| 177 |
+
)
|
| 178 |
+
model_output = response.choices[0].message.content
|
| 179 |
+
|
| 180 |
+
except Exception as e:
|
| 181 |
+
model_output = f"ERROR: {str(e)}"
|
| 182 |
+
|
| 183 |
+
end_time = time.time()
|
| 184 |
+
all_results.append({
|
| 185 |
+
"id": item.get('id', 'N/A'),
|
| 186 |
+
"prompt": prompt,
|
| 187 |
+
"model_output": model_output,
|
| 188 |
+
"ground_truth": ground_truth,
|
| 189 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 190 |
+
})
|
| 191 |
+
|
| 192 |
+
# Save results
|
| 193 |
+
with open(result_path, 'w', encoding='utf-8') as f:
|
| 194 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 195 |
+
print(f" Processing complete. Results saved to: {result_path}")
|
| 196 |
+
|
| 197 |
+
def main():
|
| 198 |
+
parser = argparse.ArgumentParser(
|
| 199 |
+
description="Run inference on a dataset using a specified GPT model."
|
| 200 |
+
)
|
| 201 |
+
parser.add_argument("--api-key", required=True, help="OpenAI API key.")
|
| 202 |
+
parser.add_argument("--model-name", default="gpt-4o", help="The model name to use (e.g., 'gpt-4o').")
|
| 203 |
+
parser.add_argument("--result-suffix", default="_result.json", help="Suffix for generated result files.")
|
| 204 |
+
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
|
| 207 |
+
try:
|
| 208 |
+
client = OpenAI(api_key=args.api_key)
|
| 209 |
+
except Exception as e:
|
| 210 |
+
print(f"Failed to initialize OpenAI client: {e}")
|
| 211 |
+
return
|
| 212 |
+
|
| 213 |
+
if shutil.which('ffmpeg') is None:
|
| 214 |
+
print("[ffmpeg not found. Video audio extraction will be unavailable.")
|
| 215 |
+
source_files = [
|
| 216 |
+
f for f in glob.glob('*.json')
|
| 217 |
+
if not f.endswith(args.result_suffix)
|
| 218 |
+
]
|
| 219 |
+
|
| 220 |
+
if not source_files:
|
| 221 |
+
print("\n No source JSON files.")
|
| 222 |
+
else:
|
| 223 |
+
print(f"\nFound {len(source_files)} dataset to process.")
|
| 224 |
+
|
| 225 |
+
for dataset_file in sorted(source_files):
|
| 226 |
+
process_dataset(dataset_file, client, args.model_name, args.result_suffix)
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
if __name__ == "__main__":
|
| 230 |
+
main()
|
code/test_code/test_gpt4o.py
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import base64
|
| 5 |
+
import cv2
|
| 6 |
+
import tempfile
|
| 7 |
+
import subprocess
|
| 8 |
+
import shutil
|
| 9 |
+
import io
|
| 10 |
+
import time
|
| 11 |
+
import glob
|
| 12 |
+
from openai import OpenAI
|
| 13 |
+
from tqdm import tqdm
|
| 14 |
+
from PIL import Image
|
| 15 |
+
|
| 16 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 17 |
+
|
| 18 |
+
def get_media_type(file_path: str) -> str:
|
| 19 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 20 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 21 |
+
return 'video'
|
| 22 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 23 |
+
return 'image'
|
| 24 |
+
else:
|
| 25 |
+
raise ValueError(f"Unsupported file format: {ext}")
|
| 26 |
+
|
| 27 |
+
def encode_media_to_base64(media_path: str) -> str:
|
| 28 |
+
try:
|
| 29 |
+
with open(media_path, "rb") as media_file:
|
| 30 |
+
return base64.b64encode(media_file.read()).decode('utf-8')
|
| 31 |
+
except FileNotFoundError:
|
| 32 |
+
raise
|
| 33 |
+
except Exception as e:
|
| 34 |
+
raise IOError(f"Could not read or encode file {media_path}: {e}")
|
| 35 |
+
|
| 36 |
+
def extract_keyframes(video_path: str, max_frames: int = 20) -> list:
|
| 37 |
+
cap = cv2.VideoCapture(video_path)
|
| 38 |
+
if not cap.isOpened():
|
| 39 |
+
raise ValueError(f"Cannot open video file: {video_path}")
|
| 40 |
+
|
| 41 |
+
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 42 |
+
video_fps = cap.get(cv2.CAP_PROP_FPS)
|
| 43 |
+
duration = total_frames / video_fps if video_fps > 0 else 0
|
| 44 |
+
|
| 45 |
+
if duration <= 20:
|
| 46 |
+
target_frames = min(max_frames, int(duration))
|
| 47 |
+
frame_interval = max(1, int(video_fps)) # 1 frame per second
|
| 48 |
+
else:
|
| 49 |
+
target_frames = max_frames
|
| 50 |
+
frame_interval = max(1, int(total_frames / max_frames))
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
keyframes = []
|
| 54 |
+
frame_count = 0
|
| 55 |
+
sampled_count = 0
|
| 56 |
+
|
| 57 |
+
while cap.isOpened() and sampled_count < target_frames:
|
| 58 |
+
ret, frame = cap.read()
|
| 59 |
+
if not ret:
|
| 60 |
+
break
|
| 61 |
+
|
| 62 |
+
if frame_count % frame_interval == 0:
|
| 63 |
+
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 64 |
+
pil_image = Image.fromarray(frame_rgb)
|
| 65 |
+
keyframes.append(pil_image)
|
| 66 |
+
sampled_count += 1
|
| 67 |
+
|
| 68 |
+
frame_count += 1
|
| 69 |
+
|
| 70 |
+
cap.release()
|
| 71 |
+
return keyframes
|
| 72 |
+
|
| 73 |
+
def extract_audio_to_text(video_path: str, client: OpenAI) -> str:
|
| 74 |
+
try:
|
| 75 |
+
with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_audio:
|
| 76 |
+
temp_audio_path = temp_audio.name
|
| 77 |
+
command = [
|
| 78 |
+
'ffmpeg', '-i', video_path, '-vn', '-acodec', 'mp3',
|
| 79 |
+
'-ar', '16000', '-ac', '1', '-y', temp_audio_path
|
| 80 |
+
]
|
| 81 |
+
result = subprocess.run(command, capture_output=True, text=True)
|
| 82 |
+
|
| 83 |
+
if result.returncode != 0:
|
| 84 |
+
print(f"FFmpeg audio extraction failed: {result.stderr}")
|
| 85 |
+
os.unlink(temp_audio_path)
|
| 86 |
+
return "Audio extraction failed."
|
| 87 |
+
with open(temp_audio_path, 'rb') as audio_file:
|
| 88 |
+
|
| 89 |
+
transcription = client.audio.transcriptions.create(
|
| 90 |
+
model="whisper-1",
|
| 91 |
+
file=(os.path.basename(temp_audio_path), audio_file.read()),
|
| 92 |
+
response_format="text"
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
os.unlink(temp_audio_path)
|
| 96 |
+
return transcription
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
print(f"Audio processing failed: {e}")
|
| 100 |
+
|
| 101 |
+
if 'temp_audio_path' in locals() and os.path.exists(temp_audio_path):
|
| 102 |
+
os.unlink(temp_audio_path)
|
| 103 |
+
return "Audio processing failed."
|
| 104 |
+
|
| 105 |
+
def process_single_sample(client: OpenAI, media_full_path: str, prompt_text: str) -> str:
|
| 106 |
+
|
| 107 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 108 |
+
media_type = get_media_type(media_full_path)
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
content = [{"type": "text", "text": clean_prompt}]
|
| 112 |
+
|
| 113 |
+
if media_type == 'image':
|
| 114 |
+
base64_media = encode_media_to_base64(media_full_path)
|
| 115 |
+
content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{base64_media}"}})
|
| 116 |
+
|
| 117 |
+
elif media_type == 'video':
|
| 118 |
+
key_frames = extract_keyframes(media_full_path)
|
| 119 |
+
audio_text = ""
|
| 120 |
+
if shutil.which('ffmpeg'):
|
| 121 |
+
try:
|
| 122 |
+
audio_text = extract_audio_to_text(media_full_path, client)
|
| 123 |
+
except Exception as audio_e:
|
| 124 |
+
print(f" Could not extract audio from video: {audio_e}")
|
| 125 |
+
else:
|
| 126 |
+
print(" ffmpeg not found, skipping audio extraction.")
|
| 127 |
+
|
| 128 |
+
for frame in key_frames:
|
| 129 |
+
with io.BytesIO() as buffer:
|
| 130 |
+
frame.save(buffer, format='JPEG', quality=85)
|
| 131 |
+
frame_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
|
| 132 |
+
content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{frame_base64}"}})
|
| 133 |
+
|
| 134 |
+
if audio_text:
|
| 135 |
+
full_prompt_with_audio = f"{clean_prompt}\n\n--- Video Audio Transcription ---\n{audio_text}"
|
| 136 |
+
content[0] = {"type": "text", "text": full_prompt_with_audio}
|
| 137 |
+
|
| 138 |
+
messages = [{"role": "user", "content": content}]
|
| 139 |
+
response = client.chat.completions.create(
|
| 140 |
+
model="gpt-4o",
|
| 141 |
+
messages=messages,
|
| 142 |
+
max_tokens=1024,
|
| 143 |
+
temperature=0,
|
| 144 |
+
timeout=120.0
|
| 145 |
+
)
|
| 146 |
+
return response.choices[0].message.content
|
| 147 |
+
|
| 148 |
+
except Exception as e:
|
| 149 |
+
try:
|
| 150 |
+
messages = [{"role": "user", "content": clean_prompt}]
|
| 151 |
+
response = client.chat.completions.create(
|
| 152 |
+
model="gpt-4o",
|
| 153 |
+
messages=messages,
|
| 154 |
+
max_tokens=1024,
|
| 155 |
+
temperature=0,
|
| 156 |
+
timeout=60.0
|
| 157 |
+
)
|
| 158 |
+
return response.choices[0].message.content
|
| 159 |
+
except Exception as fallback_e:
|
| 160 |
+
print(f" Text-only fallback also failed: {fallback_e}")
|
| 161 |
+
return f"ERROR: Fallback failed. Details: {fallback_e}"
|
| 162 |
+
|
| 163 |
+
def process_dataset_file(dataset_path: str, client: OpenAI, result_suffix: str):
|
| 164 |
+
|
| 165 |
+
result_path = f"{os.path.splitext(dataset_path)[0]}{result_suffix}"
|
| 166 |
+
if os.path.exists(result_path):
|
| 167 |
+
print(f"Result file '{os.path.basename(result_path)}' already exists, skipping.")
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
try:
|
| 171 |
+
with open(dataset_path, 'r', encoding='utf-8') as f:
|
| 172 |
+
data = json.load(f)
|
| 173 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 174 |
+
print(f" Could not read or parse JSON file {dataset_path}: {e}")
|
| 175 |
+
return
|
| 176 |
+
|
| 177 |
+
all_results = []
|
| 178 |
+
base_dir = os.path.dirname(dataset_path)
|
| 179 |
+
|
| 180 |
+
for item in tqdm(data, desc=f" Processing {os.path.basename(dataset_path)}"):
|
| 181 |
+
start_time = time.time()
|
| 182 |
+
model_output = ""
|
| 183 |
+
try:
|
| 184 |
+
prompt = item['conversations'][0]['value']
|
| 185 |
+
ground_truth = item['conversations'][1]['value']
|
| 186 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 187 |
+
media_relative_path = item.get(media_path_key)
|
| 188 |
+
|
| 189 |
+
if not media_relative_path:
|
| 190 |
+
raise ValueError("JSON item is missing 'image' or 'video' key.")
|
| 191 |
+
|
| 192 |
+
media_full_path = os.path.join(base_dir, media_relative_path)
|
| 193 |
+
if not os.path.exists(media_full_path):
|
| 194 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 195 |
+
|
| 196 |
+
model_output = process_single_sample(client, media_full_path, prompt)
|
| 197 |
+
|
| 198 |
+
except Exception as e:
|
| 199 |
+
model_output = f"ERROR: {str(e)}"
|
| 200 |
+
print(f" Failed to process item {item.get('id', 'N/A')}: {e}")
|
| 201 |
+
|
| 202 |
+
end_time = time.time()
|
| 203 |
+
all_results.append({
|
| 204 |
+
"id": item.get('id', 'N/A'),
|
| 205 |
+
"prompt": prompt,
|
| 206 |
+
"model_output": model_output,
|
| 207 |
+
"ground_truth": ground_truth,
|
| 208 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 209 |
+
})
|
| 210 |
+
|
| 211 |
+
with open(result_path, 'w', encoding='utf-8') as f:
|
| 212 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 213 |
+
print(f" Processing complete. Results saved to: {result_path}")
|
| 214 |
+
|
| 215 |
+
def main():
|
| 216 |
+
parser = argparse.ArgumentParser(description="Run inference on a dataset using GPT-4o with multimodal capabilities.")
|
| 217 |
+
parser.add_argument("--api-key", required=True, help="OpenAI API key.")
|
| 218 |
+
parser.add_argument("--model-name", default="gpt-4o", help="The model to use (default: gpt-4o).")
|
| 219 |
+
parser.add_argument("--result-suffix", default="_gpt4o_result.json", help="Suffix for the output result files.")
|
| 220 |
+
|
| 221 |
+
args = parser.parse_args()
|
| 222 |
+
|
| 223 |
+
try:
|
| 224 |
+
client = OpenAI(api_key=args.api_key)
|
| 225 |
+
except Exception as e:
|
| 226 |
+
print(f"[Could not initialize OpenAI client: {e}")
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
+
if not shutil.which('ffmpeg'):
|
| 230 |
+
print("ffmpeg not found. Video audio extraction will be disabled.")
|
| 231 |
+
|
| 232 |
+
source_json_files = [
|
| 233 |
+
f for f in glob.glob('*.json')
|
| 234 |
+
if not f.endswith(args.result_suffix) and GENERIC_RESULT_PATTERN not in f
|
| 235 |
+
]
|
| 236 |
+
|
| 237 |
+
if not source_json_files:
|
| 238 |
+
print("\n No source JSON files.")
|
| 239 |
+
else:
|
| 240 |
+
print(f"\nFound {len(source_json_files)} dataset(s) to process.")
|
| 241 |
+
|
| 242 |
+
for json_file in sorted(source_json_files):
|
| 243 |
+
process_dataset_file(json_file, client, args.result_suffix)
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
main()
|
code/test_code/test_humanomni.py
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import sys
|
| 4 |
+
import time
|
| 5 |
+
import traceback
|
| 6 |
+
from typing import Dict, Any
|
| 7 |
+
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
import torch
|
| 10 |
+
import torch.multiprocessing as mp
|
| 11 |
+
from transformers import BertTokenizer
|
| 12 |
+
|
| 13 |
+
worker_model_objects: Dict[str, Any] = {}
|
| 14 |
+
|
| 15 |
+
def init_worker(model_path: str, bert_path: str, humanomni_project_path: str, device: str):
|
| 16 |
+
global worker_model_objects
|
| 17 |
+
|
| 18 |
+
if humanomni_project_path and humanomni_project_path not in sys.path:
|
| 19 |
+
sys.path.append(humanomni_project_path)
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from humanomni import model_init, mm_infer
|
| 23 |
+
from humanomni.utils import disable_torch_init
|
| 24 |
+
except ImportError:
|
| 25 |
+
print(f"[Worker PID: {os.getpid()}] ERROR: Failed to import HumanOmni. Ensure the humanomni_path is set correctly.", file=sys.stderr)
|
| 26 |
+
return
|
| 27 |
+
|
| 28 |
+
disable_torch_init()
|
| 29 |
+
|
| 30 |
+
model, processor, tokenizer = model_init(model_path, device=device)
|
| 31 |
+
bert_tokenizer = BertTokenizer.from_pretrained(bert_path)
|
| 32 |
+
|
| 33 |
+
worker_model_objects = {
|
| 34 |
+
"model": model,
|
| 35 |
+
"processor": processor,
|
| 36 |
+
"tokenizer": tokenizer,
|
| 37 |
+
"bert_tokenizer": bert_tokenizer,
|
| 38 |
+
"mm_infer": mm_infer,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
def get_media_type(file_path: str) -> str:
|
| 42 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 43 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 44 |
+
return 'video'
|
| 45 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 46 |
+
return 'image'
|
| 47 |
+
else:
|
| 48 |
+
return 'unknown'
|
| 49 |
+
|
| 50 |
+
def process_single_sample(media_full_path: str, prompt_text: str) -> str:
|
| 51 |
+
global worker_model_objects
|
| 52 |
+
try:
|
| 53 |
+
model = worker_model_objects['model']
|
| 54 |
+
processor = worker_model_objects['processor']
|
| 55 |
+
tokenizer = worker_model_objects['tokenizer']
|
| 56 |
+
bert_tokenizer = worker_model_objects['bert_tokenizer']
|
| 57 |
+
mm_infer = worker_model_objects['mm_infer']
|
| 58 |
+
|
| 59 |
+
media_type = get_media_type(media_full_path)
|
| 60 |
+
if media_type == 'unknown':
|
| 61 |
+
raise ValueError(f"Unsupported media type for file: {media_full_path}")
|
| 62 |
+
|
| 63 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 64 |
+
|
| 65 |
+
media_tensor, audio_tensor, modal_str = None, None, ""
|
| 66 |
+
|
| 67 |
+
if media_type == 'video':
|
| 68 |
+
media_tensor = processor['video'](media_full_path)
|
| 69 |
+
audio_tensor = processor['audio'](media_full_path)[0]
|
| 70 |
+
modal_str = 'video_audio'
|
| 71 |
+
elif media_type == 'image':
|
| 72 |
+
media_tensor = processor['image'](media_full_path)
|
| 73 |
+
if media_tensor.ndim == 3:
|
| 74 |
+
media_tensor = media_tensor.unsqueeze(0)
|
| 75 |
+
audio_tensor = None
|
| 76 |
+
modal_str = 'image'
|
| 77 |
+
|
| 78 |
+
output = mm_infer(
|
| 79 |
+
media_tensor,
|
| 80 |
+
instruct=clean_prompt,
|
| 81 |
+
model=model,
|
| 82 |
+
tokenizer=tokenizer,
|
| 83 |
+
modal=modal_str,
|
| 84 |
+
question=clean_prompt,
|
| 85 |
+
bert_tokeni=bert_tokenizer,
|
| 86 |
+
do_sample=False,
|
| 87 |
+
audio=audio_tensor
|
| 88 |
+
)
|
| 89 |
+
return output
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"ERROR: {e}\n{traceback.format_exc()}"
|
| 92 |
+
|
| 93 |
+
def text_only_fallback(prompt_text: str) -> str:
|
| 94 |
+
global worker_model_objects
|
| 95 |
+
try:
|
| 96 |
+
model = worker_model_objects['model']
|
| 97 |
+
tokenizer = worker_model_objects['tokenizer']
|
| 98 |
+
|
| 99 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 100 |
+
inputs = tokenizer(clean_prompt, return_tensors="pt").to(model.device)
|
| 101 |
+
|
| 102 |
+
output_ids = model.generate(
|
| 103 |
+
input_ids=inputs.input_ids,
|
| 104 |
+
attention_mask=inputs.attention_mask,
|
| 105 |
+
max_new_tokens=512,
|
| 106 |
+
do_sample=False
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 110 |
+
|
| 111 |
+
if response.startswith(clean_prompt):
|
| 112 |
+
return response[len(clean_prompt):].strip()
|
| 113 |
+
else:
|
| 114 |
+
return response
|
| 115 |
+
|
| 116 |
+
except Exception as e:
|
| 117 |
+
return f"ERROR in text-only fallback: {str(e)}"
|
| 118 |
+
|
| 119 |
+
def run_inference_task(media_full_path, prompt_text):
|
| 120 |
+
if not worker_model_objects: return "ERROR: Worker model not initialized."
|
| 121 |
+
return process_single_sample(media_full_path, prompt_text)
|
| 122 |
+
|
| 123 |
+
def run_fallback_task(prompt_text):
|
| 124 |
+
if not worker_model_objects: return "ERROR: Worker model not initialized."
|
| 125 |
+
return text_only_fallback(prompt_text)
|
| 126 |
+
|
| 127 |
+
def main():
|
| 128 |
+
class Config:
|
| 129 |
+
model_path = "example/model/HumanOmni_7B"
|
| 130 |
+
|
| 131 |
+
bert_model_path = "example/model/bert-base-uncased"
|
| 132 |
+
|
| 133 |
+
humanomni_path = "example/moodel"
|
| 134 |
+
|
| 135 |
+
input_dir = "example"
|
| 136 |
+
|
| 137 |
+
device = "cuda:7"
|
| 138 |
+
|
| 139 |
+
result_suffix = "_humanomni_result.json"
|
| 140 |
+
|
| 141 |
+
timeout = 60
|
| 142 |
+
|
| 143 |
+
config = Config()
|
| 144 |
+
|
| 145 |
+
os.environ['TRANSFORMERS_OFFLINE'] = '1'
|
| 146 |
+
|
| 147 |
+
worker_device = config.device
|
| 148 |
+
if "cuda" in config.device:
|
| 149 |
+
gpu_id = config.device.split(':')[-1]
|
| 150 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_id
|
| 151 |
+
worker_device = "cuda:0"
|
| 152 |
+
|
| 153 |
+
init_args = (config.model_path, config.bert_model_path, config.humanomni_path, worker_device)
|
| 154 |
+
pool_ref = [mp.Pool(processes=1, initializer=init_worker, initargs=init_args)]
|
| 155 |
+
|
| 156 |
+
try:
|
| 157 |
+
source_json_files = [
|
| 158 |
+
f for f in os.listdir(config.input_dir)
|
| 159 |
+
if f.endswith(".json") and not f.endswith(config.result_suffix)
|
| 160 |
+
]
|
| 161 |
+
|
| 162 |
+
if not source_json_files:
|
| 163 |
+
print("No source JSON files.")
|
| 164 |
+
return
|
| 165 |
+
|
| 166 |
+
for json_filename in source_json_files:
|
| 167 |
+
dataset_json_path = os.path.join(config.input_dir, json_filename)
|
| 168 |
+
result_json_path = os.path.join(config.input_dir, f"{os.path.splitext(json_filename)[0]}{config.result_suffix}")
|
| 169 |
+
|
| 170 |
+
if os.path.exists(result_json_path):
|
| 171 |
+
continue
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
with open(dataset_json_path, "r", encoding="utf-8") as f:
|
| 175 |
+
data = json.load(f)
|
| 176 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 177 |
+
continue
|
| 178 |
+
|
| 179 |
+
all_results = []
|
| 180 |
+
for item in tqdm(data, desc=f" Inferring on {json_filename}", unit="item"):
|
| 181 |
+
start_time = time.time()
|
| 182 |
+
model_output, prompt, ground_truth = "", "", ""
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
prompt = item["conversations"][0]["value"]
|
| 186 |
+
ground_truth = item["conversations"][1]["value"]
|
| 187 |
+
media_relative_path = item.get('image') or item.get('video')
|
| 188 |
+
|
| 189 |
+
if not media_relative_path:
|
| 190 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 191 |
+
else:
|
| 192 |
+
media_full_path = os.path.join(config.input_dir, media_relative_path)
|
| 193 |
+
if not os.path.exists(media_full_path):
|
| 194 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 195 |
+
else:
|
| 196 |
+
media_type = get_media_type(media_full_path)
|
| 197 |
+
|
| 198 |
+
if media_type == 'image':
|
| 199 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 200 |
+
elif media_type == 'video':
|
| 201 |
+
async_result = pool_ref[0].apply_async(run_inference_task, args=(media_full_path, prompt))
|
| 202 |
+
try:
|
| 203 |
+
model_output = async_result.get(timeout=config.timeout)
|
| 204 |
+
except (mp.TimeoutError, Exception) as e:
|
| 205 |
+
print(f"\n Worker task failed for item {item.get('id', 'N/A')}. Reason: {type(e).__name__}. Restarting and falling back.", file=sys.stderr)
|
| 206 |
+
pool_ref[0].terminate()
|
| 207 |
+
pool_ref[0].join()
|
| 208 |
+
pool_ref[0] = mp.Pool(processes=1, initializer=init_worker, initargs=init_args)
|
| 209 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 210 |
+
else: # Unknown media type
|
| 211 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 212 |
+
|
| 213 |
+
except Exception as e:
|
| 214 |
+
model_output = f"ERROR: An unexpected error occurred in the main loop: {e}"
|
| 215 |
+
|
| 216 |
+
all_results.append({
|
| 217 |
+
"id": item.get("id", "N/A"),
|
| 218 |
+
"prompt": prompt,
|
| 219 |
+
"model_output": model_output,
|
| 220 |
+
"ground_truth": ground_truth,
|
| 221 |
+
"processing_time_seconds": round(time.time() - start_time, 2),
|
| 222 |
+
})
|
| 223 |
+
|
| 224 |
+
with open(result_json_path, "w", encoding="utf-8") as f:
|
| 225 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 226 |
+
print(f"Results saved to: {result_json_path}")
|
| 227 |
+
|
| 228 |
+
finally:
|
| 229 |
+
if pool_ref and pool_ref[0]:
|
| 230 |
+
pool_ref[0].close()
|
| 231 |
+
pool_ref[0].join()
|
| 232 |
+
|
| 233 |
+
if __name__ == "__main__":
|
| 234 |
+
if torch.cuda.is_available():
|
| 235 |
+
try:
|
| 236 |
+
mp.set_start_method('spawn', force=True)
|
| 237 |
+
print("Multiprocessing start method set to 'spawn'.")
|
| 238 |
+
except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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import time
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
import torchvision.transforms as T
|
| 10 |
+
from decord import VideoReader, cpu
|
| 11 |
+
from torchvision.transforms.functional import InterpolationMode
|
| 12 |
+
from transformers import AutoModel, AutoTokenizer
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
| 16 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
| 17 |
+
|
| 18 |
+
DEFAULT_IMAGE_SIZE = 448
|
| 19 |
+
DEFAULT_VIDEO_SEGMENTS = 8
|
| 20 |
+
DEFAULT_MAX_PATCHES_PER_FRAME = 1
|
| 21 |
+
DEFAULT_MAX_PATCHES_PER_IMAGE = 6
|
| 22 |
+
|
| 23 |
+
def build_transform(input_size):
|
| 24 |
+
return T.Compose([
|
| 25 |
+
T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
|
| 26 |
+
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
|
| 27 |
+
T.ToTensor(),
|
| 28 |
+
T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD)
|
| 29 |
+
])
|
| 30 |
+
|
| 31 |
+
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
|
| 32 |
+
best_ratio_diff = float('inf')
|
| 33 |
+
best_ratio = (1, 1)
|
| 34 |
+
area = width * height
|
| 35 |
+
for ratio in target_ratios:
|
| 36 |
+
target_aspect_ratio = ratio[0] / ratio[1]
|
| 37 |
+
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
|
| 38 |
+
if ratio_diff < best_ratio_diff:
|
| 39 |
+
best_ratio_diff = ratio_diff
|
| 40 |
+
best_ratio = ratio
|
| 41 |
+
elif ratio_diff == best_ratio_diff:
|
| 42 |
+
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
|
| 43 |
+
best_ratio = ratio
|
| 44 |
+
return best_ratio
|
| 45 |
+
|
| 46 |
+
def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
|
| 47 |
+
orig_width, orig_height = image.size
|
| 48 |
+
aspect_ratio = orig_width / orig_height
|
| 49 |
+
|
| 50 |
+
target_ratios = set(
|
| 51 |
+
(i, j)
|
| 52 |
+
for n in range(min_num, max_num + 1)
|
| 53 |
+
for i in range(1, n + 1)
|
| 54 |
+
for j in range(1, n + 1)
|
| 55 |
+
if i * j <= max_num and i * j >= min_num
|
| 56 |
+
)
|
| 57 |
+
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
|
| 58 |
+
target_aspect_ratio = find_closest_aspect_ratio(
|
| 59 |
+
aspect_ratio, target_ratios, orig_width, orig_height, image_size
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
target_width = image_size * target_aspect_ratio[0]
|
| 63 |
+
target_height = image_size * target_aspect_ratio[1]
|
| 64 |
+
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
|
| 65 |
+
|
| 66 |
+
resized_img = image.resize((target_width, target_height))
|
| 67 |
+
processed_images = []
|
| 68 |
+
for i in range(blocks):
|
| 69 |
+
box = (
|
| 70 |
+
(i % (target_width // image_size)) * image_size,
|
| 71 |
+
(i // (target_width // image_size)) * image_size,
|
| 72 |
+
((i % (target_width // image_size)) + 1) * image_size,
|
| 73 |
+
((i // (target_width // image_size)) + 1) * image_size
|
| 74 |
+
)
|
| 75 |
+
processed_images.append(resized_img.crop(box))
|
| 76 |
+
assert len(processed_images) == blocks
|
| 77 |
+
if use_thumbnail and len(processed_images) != 1:
|
| 78 |
+
processed_images.append(image.resize((image_size, image_size)))
|
| 79 |
+
return processed_images
|
| 80 |
+
|
| 81 |
+
def get_frame_indices(bound, fps, max_frame, first_idx=0, num_segments=32):
|
| 82 |
+
if bound:
|
| 83 |
+
start, end = bound[0], bound[1]
|
| 84 |
+
else:
|
| 85 |
+
start, end = -100000, 100000
|
| 86 |
+
start_idx = max(first_idx, round(start * fps))
|
| 87 |
+
end_idx = min(round(end * fps), max_frame)
|
| 88 |
+
seg_size = float(end_idx - start_idx) / num_segments
|
| 89 |
+
frame_indices = np.array([
|
| 90 |
+
int(start_idx + (seg_size / 2) + np.round(seg_size * idx))
|
| 91 |
+
for idx in range(num_segments)
|
| 92 |
+
])
|
| 93 |
+
return frame_indices
|
| 94 |
+
|
| 95 |
+
def load_video(video_path, bound=None, input_size=448, max_num=1, num_segments=32):
|
| 96 |
+
vr = VideoReader(video_path, ctx=cpu(0), num_threads=1)
|
| 97 |
+
max_frame = len(vr) - 1
|
| 98 |
+
fps = float(vr.get_avg_fps())
|
| 99 |
+
|
| 100 |
+
pixel_values_list, num_patches_list = [], []
|
| 101 |
+
transform = build_transform(input_size=input_size)
|
| 102 |
+
frame_indices = get_frame_indices(bound, fps, max_frame, first_idx=0, num_segments=num_segments)
|
| 103 |
+
|
| 104 |
+
valid_indices = [i for i in frame_indices if i < len(vr)]
|
| 105 |
+
if not valid_indices:
|
| 106 |
+
raise ValueError(f"No valid frames could be sampled from video {video_path}.")
|
| 107 |
+
|
| 108 |
+
frames = vr.get_batch(valid_indices).asnumpy()
|
| 109 |
+
|
| 110 |
+
for frame_np in frames:
|
| 111 |
+
img = Image.fromarray(frame_np).convert('RGB')
|
| 112 |
+
tiles = dynamic_preprocess(img, image_size=input_size, use_thumbnail=True, max_num=max_num)
|
| 113 |
+
pixel_values = torch.stack([transform(tile) for tile in tiles])
|
| 114 |
+
num_patches_list.append(pixel_values.shape[0])
|
| 115 |
+
pixel_values_list.append(pixel_values)
|
| 116 |
+
|
| 117 |
+
pixel_values = torch.cat(pixel_values_list)
|
| 118 |
+
return pixel_values, num_patches_list
|
| 119 |
+
|
| 120 |
+
def get_media_type(file_path: str) -> str:
|
| 121 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 122 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 123 |
+
return 'video'
|
| 124 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 125 |
+
return 'image'
|
| 126 |
+
else:
|
| 127 |
+
raise ValueError(f"Unsupported file format: {ext} in file {file_path}")
|
| 128 |
+
|
| 129 |
+
def process_file(dataset_json_path: str, model, tokenizer, result_suffix: str):
|
| 130 |
+
json_filename = os.path.basename(dataset_json_path)
|
| 131 |
+
result_json_path = os.path.join(
|
| 132 |
+
os.path.dirname(dataset_json_path),
|
| 133 |
+
f"{os.path.splitext(json_filename)[0]}{result_suffix}"
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
if os.path.exists(result_json_path):
|
| 137 |
+
print(f"Result file '{os.path.basename(result_json_path)}' already exists. Skipping.")
|
| 138 |
+
return
|
| 139 |
+
|
| 140 |
+
try:
|
| 141 |
+
with open(dataset_json_path, 'r', encoding='utf-8') as f:
|
| 142 |
+
data = json.load(f)
|
| 143 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 144 |
+
print(f"Failed to read or parse JSON file {dataset_json_path}: {e}")
|
| 145 |
+
return
|
| 146 |
+
|
| 147 |
+
generation_config = dict(num_beams=1, max_new_tokens=2048, do_sample=False)
|
| 148 |
+
device = next(model.parameters()).device
|
| 149 |
+
all_results = []
|
| 150 |
+
|
| 151 |
+
base_path = os.path.dirname(dataset_json_path)
|
| 152 |
+
|
| 153 |
+
for item in tqdm(data, desc=f" Inferring on {json_filename}"):
|
| 154 |
+
start_time = time.time()
|
| 155 |
+
model_output = "N/A"
|
| 156 |
+
|
| 157 |
+
try:
|
| 158 |
+
prompt_text = item['conversations'][0]['value']
|
| 159 |
+
ground_truth = item['conversations'][1]['value']
|
| 160 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 161 |
+
media_relative_path = item.get(media_path_key)
|
| 162 |
+
if not media_relative_path:
|
| 163 |
+
raise ValueError("JSON item is missing 'image' or 'video' key.")
|
| 164 |
+
|
| 165 |
+
media_full_path = os.path.join(base_path, media_relative_path)
|
| 166 |
+
if not os.path.exists(media_full_path):
|
| 167 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 168 |
+
|
| 169 |
+
media_type = get_media_type(media_full_path)
|
| 170 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 171 |
+
|
| 172 |
+
pixel_values, num_patches_list, question = None, None, None
|
| 173 |
+
|
| 174 |
+
if media_type == 'image':
|
| 175 |
+
image = Image.open(media_full_path).convert('RGB')
|
| 176 |
+
transform = build_transform(input_size=DEFAULT_IMAGE_SIZE)
|
| 177 |
+
patches = dynamic_preprocess(image, image_size=DEFAULT_IMAGE_SIZE, use_thumbnail=True, max_num=DEFAULT_MAX_PATCHES_PER_IMAGE)
|
| 178 |
+
pixel_values = torch.stack([transform(p) for p in patches])
|
| 179 |
+
num_patches_list = [len(patches)]
|
| 180 |
+
question = f"<image>\n{clean_prompt}"
|
| 181 |
+
|
| 182 |
+
elif media_type == 'video':
|
| 183 |
+
pixel_values, num_patches_list = load_video(
|
| 184 |
+
media_full_path,
|
| 185 |
+
num_segments=DEFAULT_VIDEO_SEGMENTS,
|
| 186 |
+
max_num=DEFAULT_MAX_PATCHES_PER_FRAME,
|
| 187 |
+
input_size=DEFAULT_IMAGE_SIZE
|
| 188 |
+
)
|
| 189 |
+
video_prefix = ''.join([f'Frame{i+1}: <image>\n' for i in range(len(num_patches_list))])
|
| 190 |
+
question = f"{video_prefix}{clean_prompt}"
|
| 191 |
+
|
| 192 |
+
pixel_values = pixel_values.to(torch.bfloat16).to(device)
|
| 193 |
+
|
| 194 |
+
response = model.chat(
|
| 195 |
+
tokenizer=tokenizer,
|
| 196 |
+
pixel_values=pixel_values,
|
| 197 |
+
question=question,
|
| 198 |
+
generation_config=generation_config,
|
| 199 |
+
num_patches_list=num_patches_list,
|
| 200 |
+
history=None
|
| 201 |
+
)
|
| 202 |
+
model_output = response.strip()
|
| 203 |
+
|
| 204 |
+
except Exception as e:
|
| 205 |
+
model_output = f"ERROR: {str(e)}"
|
| 206 |
+
|
| 207 |
+
end_time = time.time()
|
| 208 |
+
all_results.append({
|
| 209 |
+
"id": item.get('id', 'N/A'),
|
| 210 |
+
"prompt": prompt_text,
|
| 211 |
+
"model_output": model_output,
|
| 212 |
+
"ground_truth": ground_truth,
|
| 213 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 214 |
+
})
|
| 215 |
+
|
| 216 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 217 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 218 |
+
|
| 219 |
+
def main():
|
| 220 |
+
parser = argparse.ArgumentParser(description="Batch inference with InternVL model on local JSON datasets.")
|
| 221 |
+
parser.add_argument("--model-path", required=True, help="Full path to the local model directory.")
|
| 222 |
+
parser.add_argument("--result-suffix", default="_result.json", help="Suffix for the generated result files.")
|
| 223 |
+
args = parser.parse_args()
|
| 224 |
+
|
| 225 |
+
try:
|
| 226 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 227 |
+
model = AutoModel.from_pretrained(
|
| 228 |
+
args.model_path,
|
| 229 |
+
torch_dtype=torch.bfloat16,
|
| 230 |
+
low_cpu_mem_usage=True,
|
| 231 |
+
trust_remote_code=True,
|
| 232 |
+
device_map="auto"
|
| 233 |
+
).eval()
|
| 234 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_path, trust_remote_code=True, use_fast=False)
|
| 235 |
+
except Exception as e:
|
| 236 |
+
print(f"Failed to load the model from {args.model_path}. Error: {e}")
|
| 237 |
+
return
|
| 238 |
+
|
| 239 |
+
current_dir = os.getcwd()
|
| 240 |
+
source_json_files = [
|
| 241 |
+
f for f in os.listdir(current_dir)
|
| 242 |
+
if f.endswith('.json') and not f.endswith(args.result_suffix)
|
| 243 |
+
]
|
| 244 |
+
|
| 245 |
+
if not source_json_files:
|
| 246 |
+
print(f"\nNo source JSON files: {current_dir}")
|
| 247 |
+
else:
|
| 248 |
+
for json_filename in sorted(source_json_files):
|
| 249 |
+
process_file(os.path.join(current_dir, json_filename), model, tokenizer, args.result_suffix)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
main()
|
code/test_code/test_llavanext.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import time
|
| 6 |
+
from PIL import Image
|
| 7 |
+
import numpy as np
|
| 8 |
+
import av
|
| 9 |
+
import torch
|
| 10 |
+
from transformers import LlavaNextVideoProcessor, LlavaNextVideoForConditionalGeneration
|
| 11 |
+
|
| 12 |
+
def get_media_type(file_path: str) -> str:
|
| 13 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 14 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 15 |
+
return 'video'
|
| 16 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 17 |
+
return 'image'
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError(f"Unsupported file format: {ext} in file {file_path}")
|
| 20 |
+
|
| 21 |
+
def read_video_pyav(container, indices):
|
| 22 |
+
frames = []
|
| 23 |
+
container.seek(0)
|
| 24 |
+
start_index = indices[0]
|
| 25 |
+
end_index = indices[-1]
|
| 26 |
+
for i, frame in enumerate(container.decode(video=0)):
|
| 27 |
+
if i > end_index:
|
| 28 |
+
break
|
| 29 |
+
if i >= start_index and i in indices:
|
| 30 |
+
frames.append(frame)
|
| 31 |
+
if not frames:
|
| 32 |
+
raise ValueError("Could not decode specified frames from the video.")
|
| 33 |
+
return np.stack([x.to_ndarray(format="rgb24") for x in frames])
|
| 34 |
+
|
| 35 |
+
def process_file(dataset_json_path: str, model, processor, result_suffix: str, device: str):
|
| 36 |
+
json_filename = os.path.basename(dataset_json_path)
|
| 37 |
+
result_json_path = os.path.join(
|
| 38 |
+
os.path.dirname(dataset_json_path),
|
| 39 |
+
f"{os.path.splitext(json_filename)[0]}{result_suffix}"
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
if os.path.exists(result_json_path):
|
| 43 |
+
print(f"[INFO] Result file '{os.path.basename(result_json_path)}' already exists. Skipping.")
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
try:
|
| 47 |
+
with open(dataset_json_path, 'r', encoding='utf-8') as f:
|
| 48 |
+
data = json.load(f)
|
| 49 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 50 |
+
print(f"Failed to read or parse JSON file {dataset_json_path}: {e}")
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
all_results = []
|
| 54 |
+
base_path = os.path.dirname(dataset_json_path)
|
| 55 |
+
|
| 56 |
+
for item in tqdm(data, desc=f" Inferring on {json_filename}"):
|
| 57 |
+
start_time = time.time()
|
| 58 |
+
model_output = "N/A"
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
prompt_text = item['conversations'][0]['value']
|
| 62 |
+
ground_truth = item['conversations'][1]['value']
|
| 63 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 64 |
+
media_relative_path = item.get(media_path_key)
|
| 65 |
+
if not media_relative_path:
|
| 66 |
+
raise ValueError("JSON item is missing 'image' or 'video' key.")
|
| 67 |
+
|
| 68 |
+
media_full_path = os.path.join(base_path, media_relative_path)
|
| 69 |
+
if not os.path.exists(media_full_path):
|
| 70 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 71 |
+
|
| 72 |
+
media_type = get_media_type(media_full_path)
|
| 73 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 74 |
+
|
| 75 |
+
conversation = [
|
| 76 |
+
{"role": "user", "content": [
|
| 77 |
+
{"type": "text", "text": clean_prompt},
|
| 78 |
+
{"type": media_type},
|
| 79 |
+
]},
|
| 80 |
+
]
|
| 81 |
+
prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
|
| 82 |
+
|
| 83 |
+
if media_type == 'image':
|
| 84 |
+
raw_image = Image.open(media_full_path)
|
| 85 |
+
inputs = processor(text=prompt, images=raw_image, return_tensors='pt').to(device, torch.float16)
|
| 86 |
+
|
| 87 |
+
elif media_type == 'video':
|
| 88 |
+
container = av.open(media_full_path)
|
| 89 |
+
total_frames = container.streams.video[0].frames
|
| 90 |
+
indices = np.arange(0, total_frames, total_frames / 8).astype(int)
|
| 91 |
+
clip = read_video_pyav(container, indices)
|
| 92 |
+
inputs = processor(text=prompt, videos=clip, return_tensors="pt").to(device, torch.float16)
|
| 93 |
+
|
| 94 |
+
output = model.generate(**inputs, max_new_tokens=1024, do_sample=False)
|
| 95 |
+
decoded_output = processor.batch_decode(output, skip_special_tokens=True)[0].strip()
|
| 96 |
+
|
| 97 |
+
assistant_marker = "ASSISTANT:"
|
| 98 |
+
if assistant_marker in decoded_output:
|
| 99 |
+
model_output = decoded_output.split(assistant_marker)[-1].strip()
|
| 100 |
+
else:
|
| 101 |
+
model_output = decoded_output
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
model_output = f"ERROR: {str(e)}"
|
| 105 |
+
|
| 106 |
+
end_time = time.time()
|
| 107 |
+
all_results.append({
|
| 108 |
+
"id": item.get('id', 'N/A'),
|
| 109 |
+
"prompt": prompt_text,
|
| 110 |
+
"model_output": model_output,
|
| 111 |
+
"ground_truth": ground_truth,
|
| 112 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 113 |
+
})
|
| 114 |
+
|
| 115 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 116 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 117 |
+
print(f" Processing complete. Results saved to: {result_json_path}")
|
| 118 |
+
|
| 119 |
+
def main():
|
| 120 |
+
parser = argparse.ArgumentParser(description="Batch inference with a local LLaVA-NeXT-Video model.")
|
| 121 |
+
parser.add_argument("--model-path", required=True, help="Full path to the local model directory.")
|
| 122 |
+
parser.add_argument("--result-suffix", required=True, help="Suffix for the generated result files (e.g., '_result.json').")
|
| 123 |
+
parser.add_argument("--device", default="cuda:0", help="Device to run the model on (e.g., 'cuda:0' or 'cpu').")
|
| 124 |
+
args = parser.parse_args()
|
| 125 |
+
|
| 126 |
+
try:
|
| 127 |
+
model = LlavaNextVideoForConditionalGeneration.from_pretrained(
|
| 128 |
+
args.model_path,
|
| 129 |
+
torch_dtype=torch.float16,
|
| 130 |
+
low_cpu_mem_usage=True,
|
| 131 |
+
).to(args.device)
|
| 132 |
+
processor = LlavaNextVideoProcessor.from_pretrained(args.model_path)
|
| 133 |
+
print(" Model and processor loaded successfully.")
|
| 134 |
+
except Exception as e:
|
| 135 |
+
print(f"Failed to load model from '{args.model_path}'. Error: {e}")
|
| 136 |
+
return
|
| 137 |
+
|
| 138 |
+
current_dir = os.getcwd()
|
| 139 |
+
source_json_files = [
|
| 140 |
+
f for f in os.listdir(current_dir)
|
| 141 |
+
if f.endswith('.json') and not f.endswith(args.result_suffix)
|
| 142 |
+
]
|
| 143 |
+
|
| 144 |
+
if not source_json_files:
|
| 145 |
+
print(f"\n[INFO] No source JSON files: {current_dir}")
|
| 146 |
+
else:
|
| 147 |
+
for json_filename in sorted(source_json_files):
|
| 148 |
+
process_file(
|
| 149 |
+
dataset_json_path=os.path.join(current_dir, json_filename),
|
| 150 |
+
model=model,
|
| 151 |
+
processor=processor,
|
| 152 |
+
result_suffix=args.result_suffix,
|
| 153 |
+
device=args.device
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
if __name__ == "__main__":
|
| 158 |
+
main()
|
code/test_code/test_llavaonevison.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import base64
|
| 5 |
+
from openai import OpenAI
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import time
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 11 |
+
|
| 12 |
+
def get_media_type(file_path: str) -> str:
|
| 13 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 14 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 15 |
+
return 'video'
|
| 16 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 17 |
+
return 'image'
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError(f"Unsupported file format: {ext}")
|
| 20 |
+
|
| 21 |
+
def encode_media_to_base64(media_path: str) -> str:
|
| 22 |
+
try:
|
| 23 |
+
with open(media_path, "rb") as media_file:
|
| 24 |
+
return base64.b64encode(media_file.read()).decode('utf-8')
|
| 25 |
+
except FileNotFoundError:
|
| 26 |
+
raise
|
| 27 |
+
except Exception as e:
|
| 28 |
+
raise IOError(f"Failed to read or encode file {media_path}: {e}")
|
| 29 |
+
|
| 30 |
+
def process_file(dataset_json_path: str, client: OpenAI, model_name: str, result_suffix: str):
|
| 31 |
+
json_filename = os.path.basename(dataset_json_path)
|
| 32 |
+
result_json_path = os.path.join(
|
| 33 |
+
os.path.dirname(dataset_json_path),
|
| 34 |
+
f"{os.path.splitext(json_filename)[0]}{result_suffix}"
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
if os.path.exists(result_json_path):
|
| 38 |
+
print(f"Result file '{os.path.basename(result_json_path)}' already exists. Skipping.")
|
| 39 |
+
return
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
with open(dataset_json_path, 'r', encoding='utf-8') as f:
|
| 43 |
+
data = json.load(f)
|
| 44 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 45 |
+
print(f"Failed to read or parse JSON file {dataset_json_path}: {e}")
|
| 46 |
+
return
|
| 47 |
+
|
| 48 |
+
all_results = []
|
| 49 |
+
base_path = os.path.dirname(dataset_json_path)
|
| 50 |
+
|
| 51 |
+
for item in tqdm(data, desc=f" Querying API for {json_filename}"):
|
| 52 |
+
start_time = time.time()
|
| 53 |
+
model_output = "N/A"
|
| 54 |
+
try:
|
| 55 |
+
prompt = item['conversations'][0]['value']
|
| 56 |
+
ground_truth = item['conversations'][1]['value']
|
| 57 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 58 |
+
media_relative_path = item.get(media_path_key)
|
| 59 |
+
if not media_relative_path:
|
| 60 |
+
raise ValueError("JSON item is missing 'image' or 'video' key.")
|
| 61 |
+
|
| 62 |
+
media_full_path = os.path.join(base_path, media_relative_path)
|
| 63 |
+
if not os.path.exists(media_full_path):
|
| 64 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 65 |
+
|
| 66 |
+
media_type = get_media_type(media_full_path)
|
| 67 |
+
media_base64 = encode_media_to_base64(media_full_path)
|
| 68 |
+
clean_prompt = prompt.replace("<image>", "").replace("<video>", "").strip()
|
| 69 |
+
|
| 70 |
+
if media_type == 'image':
|
| 71 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": clean_prompt}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{media_base64}"}}]}]
|
| 72 |
+
else:
|
| 73 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": clean_prompt}, {"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{media_base64}"}}]}]
|
| 74 |
+
|
| 75 |
+
response = client.chat.completions.create(model=model_name, messages=messages, max_tokens=1024, temperature=0.0)
|
| 76 |
+
model_output = response.choices[0].message.content
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
model_output = f"ERROR: {str(e)}"
|
| 80 |
+
|
| 81 |
+
end_time = time.time()
|
| 82 |
+
all_results.append({
|
| 83 |
+
"id": item.get('id', 'N/A'),
|
| 84 |
+
"prompt": prompt,
|
| 85 |
+
"model_output": model_output,
|
| 86 |
+
"ground_truth": ground_truth,
|
| 87 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 88 |
+
})
|
| 89 |
+
|
| 90 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 91 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 92 |
+
print(f" [SUCCESS] Processing complete. Results saved to: {result_json_path}")
|
| 93 |
+
|
| 94 |
+
def main():
|
| 95 |
+
parser = argparse.ArgumentParser(description="Batch inference for multimodal models using an OpenAI-compatible API.")
|
| 96 |
+
parser.add_argument("--model-endpoint", default="http://localhost:8004/v1", help="The API endpoint of the model server.")
|
| 97 |
+
parser.add_argument("--model-name", default="llavaonevision7b", help="The name of the model to use.")
|
| 98 |
+
parser.add_argument("--result-suffix", default="_result.json", help="Suffix for the generated result files.")
|
| 99 |
+
args = parser.parse_args()
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
client = OpenAI(base_url=args.model_endpoint, api_key="EMPTY")
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f"Could not initialize OpenAI client: {e}")
|
| 105 |
+
return
|
| 106 |
+
|
| 107 |
+
current_dir = os.getcwd()
|
| 108 |
+
source_json_files = [
|
| 109 |
+
f for f in os.listdir(current_dir)
|
| 110 |
+
if f.endswith('.json') and not f.endswith(GENERIC_RESULT_PATTERN)
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
if not source_json_files:
|
| 114 |
+
print(f"\nNo source JSON files: {current_dir}")
|
| 115 |
+
else:
|
| 116 |
+
for json_filename in sorted(source_json_files):
|
| 117 |
+
process_file(
|
| 118 |
+
dataset_json_path=os.path.join(current_dir, json_filename),
|
| 119 |
+
client=client,
|
| 120 |
+
model_name=args.model_name,
|
| 121 |
+
result_suffix=args.result_suffix
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
if __name__ == "__main__":
|
| 126 |
+
main()
|
code/test_code/test_minicpm.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import base64
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from tqdm import tqdm
|
| 6 |
+
import time
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
# --- Configuration ---
|
| 10 |
+
MODEL_ENDPOINT = "http://localhost:8000/v1"
|
| 11 |
+
MODEL_NAME = "minicpm"
|
| 12 |
+
RESULT_SUFFIX = "_minicpm_result.json"
|
| 13 |
+
|
| 14 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 15 |
+
|
| 16 |
+
def get_media_type(file_path: str) -> str:
|
| 17 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 18 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 19 |
+
return 'video'
|
| 20 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 21 |
+
return 'image'
|
| 22 |
+
else:
|
| 23 |
+
raise ValueError(f"Unsupported file format: {ext}")
|
| 24 |
+
|
| 25 |
+
def encode_media_to_base64(media_path: str) -> str:
|
| 26 |
+
try:
|
| 27 |
+
with open(media_path, "rb") as media_file:
|
| 28 |
+
return base64.b64encode(media_file.read()).decode('utf-8')
|
| 29 |
+
except FileNotFoundError:
|
| 30 |
+
print(f"Media file not found at: {media_path}")
|
| 31 |
+
raise
|
| 32 |
+
except Exception as e:
|
| 33 |
+
raise IOError(f"Could not read or encode file {media_path}: {e}")
|
| 34 |
+
|
| 35 |
+
def process_directory(client: OpenAI, model_name: str, result_suffix: str):
|
| 36 |
+
current_dir = os.getcwd()
|
| 37 |
+
source_json_files = [
|
| 38 |
+
f for f in os.listdir(current_dir)
|
| 39 |
+
if f.endswith('.json') and GENERIC_RESULT_PATTERN not in f
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
if not source_json_files:
|
| 43 |
+
print(f"[Info] No source JSON files to process in {current_dir}.")
|
| 44 |
+
return
|
| 45 |
+
|
| 46 |
+
for json_filename in source_json_files:
|
| 47 |
+
process_single_json(current_dir, json_filename, client, model_name, result_suffix)
|
| 48 |
+
|
| 49 |
+
def process_single_json(directory: str, json_filename: str, client: OpenAI, model_name: str, result_suffix: str):
|
| 50 |
+
dataset_json_path = os.path.join(directory, json_filename)
|
| 51 |
+
result_json_path = os.path.join(directory, f"{os.path.splitext(json_filename)[0]}{result_suffix}")
|
| 52 |
+
|
| 53 |
+
if os.path.exists(result_json_path):
|
| 54 |
+
print(f"Result file '{os.path.basename(result_json_path)}' already exists, skipping.")
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
print(f"Reading and processing dataset: {json_filename}")
|
| 58 |
+
try:
|
| 59 |
+
with open(dataset_json_path, 'r', encoding='utf-8') as f:
|
| 60 |
+
data = json.load(f)
|
| 61 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 62 |
+
return
|
| 63 |
+
|
| 64 |
+
all_results = []
|
| 65 |
+
for item in tqdm(data, desc=f" Processing {json_filename}", unit="item"):
|
| 66 |
+
start_time = time.time()
|
| 67 |
+
model_output = ""
|
| 68 |
+
try:
|
| 69 |
+
prompt = item['conversations'][0]['value']
|
| 70 |
+
ground_truth = item['conversations'][1]['value']
|
| 71 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 72 |
+
media_relative_path = item.get(media_path_key)
|
| 73 |
+
if not media_relative_path:
|
| 74 |
+
raise ValueError("JSON item is missing 'image' or 'video' key.")
|
| 75 |
+
|
| 76 |
+
media_full_path = os.path.join(directory, media_relative_path)
|
| 77 |
+
|
| 78 |
+
media_type = get_media_type(media_full_path)
|
| 79 |
+
media_base64 = encode_media_to_base64(media_full_path)
|
| 80 |
+
clean_prompt = prompt.replace("<image>", "").replace("<video>", "").strip()
|
| 81 |
+
|
| 82 |
+
content = [{"type": "text", "text": clean_prompt}]
|
| 83 |
+
if media_type == 'image':
|
| 84 |
+
content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{media_base64}"}})
|
| 85 |
+
else: # video
|
| 86 |
+
content.append({"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{media_base64}"}})
|
| 87 |
+
|
| 88 |
+
messages = [{"role": "user", "content": content}]
|
| 89 |
+
|
| 90 |
+
response = client.chat.completions.create(model=model_name, messages=messages, max_tokens=1024, temperature=0.0)
|
| 91 |
+
model_output = response.choices[0].message.content
|
| 92 |
+
|
| 93 |
+
except Exception as e:
|
| 94 |
+
model_output = f"ERROR: {str(e)}"
|
| 95 |
+
|
| 96 |
+
end_time = time.time()
|
| 97 |
+
|
| 98 |
+
all_results.append({
|
| 99 |
+
"id": item.get('id', 'N/A'),
|
| 100 |
+
"prompt": prompt,
|
| 101 |
+
"model_output": model_output,
|
| 102 |
+
"ground_truth": ground_truth,
|
| 103 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 104 |
+
})
|
| 105 |
+
|
| 106 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 107 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 108 |
+
print(f"Task complete. Results saved to: {result_json_path}")
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def main():
|
| 112 |
+
try:
|
| 113 |
+
client = OpenAI(base_url=MODEL_ENDPOINT, api_key="EMPTY")
|
| 114 |
+
except Exception as e:
|
| 115 |
+
print(f"[Fatal] Could not initialize OpenAI client: {e}")
|
| 116 |
+
sys.exit(1)
|
| 117 |
+
|
| 118 |
+
process_directory(client, MODEL_NAME, RESULT_SUFFIX)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
if __name__ == "__main__":
|
| 123 |
+
main()
|
code/test_code/test_qwen25_omni.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import time
|
| 5 |
+
import sys
|
| 6 |
+
import base64
|
| 7 |
+
import signal
|
| 8 |
+
import contextlib
|
| 9 |
+
from typing import Dict, Any, List
|
| 10 |
+
from tqdm import tqdm
|
| 11 |
+
from openai import OpenAI
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TimeoutError(Exception):
|
| 15 |
+
pass
|
| 16 |
+
|
| 17 |
+
@contextlib.contextmanager
|
| 18 |
+
def timeout(seconds: int, error_message: str = 'Function call timed out'):
|
| 19 |
+
def _handle_timeout(signum, frame):
|
| 20 |
+
raise TimeoutError(error_message)
|
| 21 |
+
|
| 22 |
+
signal.signal(signal.SIGALRM, _handle_timeout)
|
| 23 |
+
signal.alarm(seconds)
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
yield
|
| 27 |
+
finally:
|
| 28 |
+
signal.alarm(0)
|
| 29 |
+
|
| 30 |
+
def get_media_type(file_path: str) -> str:
|
| 31 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 32 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 33 |
+
return 'video'
|
| 34 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 35 |
+
return 'image'
|
| 36 |
+
else:
|
| 37 |
+
raise ValueError(f"Unsupported file format: {ext}")
|
| 38 |
+
|
| 39 |
+
def create_text_message(prompt: str) -> List[Dict[str, Any]]:
|
| 40 |
+
return [{"role": "user", "content": [{"type": "text", "text": prompt}]}]
|
| 41 |
+
|
| 42 |
+
def create_multimodal_message(prompt: str, media_path: str) -> List[Dict[str, Any]]:
|
| 43 |
+
media_type = get_media_type(media_path)
|
| 44 |
+
|
| 45 |
+
try:
|
| 46 |
+
with open(media_path, "rb") as media_file:
|
| 47 |
+
media_base64 = base64.b64encode(media_file.read()).decode('utf-8')
|
| 48 |
+
except IOError as e:
|
| 49 |
+
raise IOError(f"Could not read or encode file {media_path}: {e}")
|
| 50 |
+
|
| 51 |
+
content = [{"type": "text", "text": prompt}]
|
| 52 |
+
if media_type == 'image':
|
| 53 |
+
content.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{media_base64}"}})
|
| 54 |
+
elif media_type == 'video':
|
| 55 |
+
content.append({"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{media_base64}"}})
|
| 56 |
+
|
| 57 |
+
return [{"role": "user", "content": content}]
|
| 58 |
+
|
| 59 |
+
def get_model_response(client: OpenAI, model_name: str, messages: List[Dict[str, Any]]) -> str:
|
| 60 |
+
response = client.chat.completions.create(
|
| 61 |
+
model=model_name,
|
| 62 |
+
messages=messages,
|
| 63 |
+
max_tokens=1024,
|
| 64 |
+
temperature=0.0
|
| 65 |
+
)
|
| 66 |
+
return response.choices[0].message.content
|
| 67 |
+
|
| 68 |
+
def text_only_fallback(client: OpenAI, model_name: str, prompt_text: str) -> str:
|
| 69 |
+
print(" [INFO] Executing text-only fallback...", file=sys.stderr)
|
| 70 |
+
try:
|
| 71 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 72 |
+
messages = create_text_message(clean_prompt)
|
| 73 |
+
return get_model_response(client, model_name, messages)
|
| 74 |
+
except Exception as e:
|
| 75 |
+
return f"ERROR in text-only fallback: {str(e)}"
|
| 76 |
+
|
| 77 |
+
def process_file(client: OpenAI, model_name: str, result_suffix: str, json_filename: str):
|
| 78 |
+
result_json_path = f"{os.path.splitext(json_filename)[0]}{result_suffix}"
|
| 79 |
+
if os.path.exists(result_json_path):
|
| 80 |
+
print(f"[INFO] Skipping already processed file: {json_filename}")
|
| 81 |
+
return
|
| 82 |
+
with open(json_filename, 'r', encoding='utf-8') as f:
|
| 83 |
+
data = json.load(f)
|
| 84 |
+
|
| 85 |
+
all_results = []
|
| 86 |
+
for item in tqdm(data, desc=f" Processing {json_filename}", file=sys.stdout):
|
| 87 |
+
start_time = time.time()
|
| 88 |
+
model_output = ""
|
| 89 |
+
prompt_text = ""
|
| 90 |
+
ground_truth = ""
|
| 91 |
+
|
| 92 |
+
try:
|
| 93 |
+
prompt_text = item['conversations'][0]['value']
|
| 94 |
+
ground_truth = item['conversations'][1]['value']
|
| 95 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 96 |
+
|
| 97 |
+
media_relative_path = item.get('image') or item.get('video')
|
| 98 |
+
|
| 99 |
+
if not media_relative_path:
|
| 100 |
+
print(f"\n No media key found for item {item.get('id', 'N/A')}. Falling back to text-only.", file=sys.stderr)
|
| 101 |
+
model_output = text_only_fallback(client, model_name, prompt_text)
|
| 102 |
+
else:
|
| 103 |
+
media_full_path = os.path.abspath(media_relative_path)
|
| 104 |
+
if not os.path.exists(media_full_path):
|
| 105 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 106 |
+
|
| 107 |
+
try:
|
| 108 |
+
with timeout(seconds=300):
|
| 109 |
+
messages = create_multimodal_message(clean_prompt, media_full_path)
|
| 110 |
+
model_output = get_model_response(client, model_name, messages)
|
| 111 |
+
except TimeoutError:
|
| 112 |
+
print(f"\n Processing timed out for item {item.get('id', 'N/A')}. Falling back to text-only.", file=sys.stderr)
|
| 113 |
+
model_output = text_only_fallback(client, model_name, prompt_text)
|
| 114 |
+
|
| 115 |
+
except Exception as e:
|
| 116 |
+
error_message = f"ERROR: {str(e)}"
|
| 117 |
+
model_output = error_message
|
| 118 |
+
print(f"\n Failed to process item {item.get('id', 'N/A')}: {e}", file=sys.stderr)
|
| 119 |
+
|
| 120 |
+
end_time = time.time()
|
| 121 |
+
all_results.append({
|
| 122 |
+
"id": item.get('id', 'N/A'),
|
| 123 |
+
"prompt": prompt_text,
|
| 124 |
+
"model_output": model_output,
|
| 125 |
+
"ground_truth": ground_truth,
|
| 126 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 127 |
+
})
|
| 128 |
+
|
| 129 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 130 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 131 |
+
print(f" File processing complete. Results saved to: {result_json_path}")
|
| 132 |
+
|
| 133 |
+
def main():
|
| 134 |
+
parser = argparse.ArgumentParser(
|
| 135 |
+
description="Run inference on JSON files in the current directory using a specified model.",
|
| 136 |
+
formatter_class=argparse.RawTextHelpFormatter
|
| 137 |
+
)
|
| 138 |
+
parser.add_argument(
|
| 139 |
+
"--model-endpoint",
|
| 140 |
+
default="http://127.0.0.1:8000/v1",
|
| 141 |
+
help="The API endpoint for the model (e.g., 'http://127.0.0.1:8000/v1')."
|
| 142 |
+
)
|
| 143 |
+
parser.add_argument(
|
| 144 |
+
"--model-name",
|
| 145 |
+
default="qwen2.5-omni-7b",
|
| 146 |
+
help="The name of the model to use for inference."
|
| 147 |
+
)
|
| 148 |
+
parser.add_argument(
|
| 149 |
+
"--result-suffix",
|
| 150 |
+
default="_result.json",
|
| 151 |
+
help="The suffix to append to result filenames."
|
| 152 |
+
)
|
| 153 |
+
args = parser.parse_args()
|
| 154 |
+
|
| 155 |
+
try:
|
| 156 |
+
client = OpenAI(base_url=args.model_endpoint, api_key="EMPTY")
|
| 157 |
+
except Exception as e:
|
| 158 |
+
print(f"Could not create OpenAI client. Please check the endpoint: {e}", file=sys.stderr)
|
| 159 |
+
sys.exit(1)
|
| 160 |
+
|
| 161 |
+
current_dir = os.getcwd()
|
| 162 |
+
source_files = sorted([
|
| 163 |
+
f for f in os.listdir(current_dir)
|
| 164 |
+
if f.endswith('.json') and not f.endswith(args.result_suffix)
|
| 165 |
+
])
|
| 166 |
+
|
| 167 |
+
if not source_files:
|
| 168 |
+
print("No source JSON files.", file=sys.stderr)
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
for json_filename in source_files:
|
| 172 |
+
process_file(client, args.model_name, args.result_suffix, json_filename)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
if __name__ == "__main__":
|
| 177 |
+
main()
|
code/test_code/test_qwenvl.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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import tqdm
|
| 8 |
+
|
| 9 |
+
try:
|
| 10 |
+
import torch
|
| 11 |
+
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor
|
| 12 |
+
import av
|
| 13 |
+
except ImportError as e:
|
| 14 |
+
print(f"Original error: {e}")
|
| 15 |
+
exit(1)
|
| 16 |
+
|
| 17 |
+
# --- Configuration ---
|
| 18 |
+
DEFAULT_MODEL_PATH = "example/model/Qwen2.5-VL-model"
|
| 19 |
+
|
| 20 |
+
def get_media_type(file_path: str) -> str:
|
| 21 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 22 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 23 |
+
return 'video'
|
| 24 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 25 |
+
return 'image'
|
| 26 |
+
else:
|
| 27 |
+
raise ValueError(f"Unsupported file format: {ext} in file {file_path}")
|
| 28 |
+
|
| 29 |
+
def run_inference_on_file(
|
| 30 |
+
json_path: str,
|
| 31 |
+
model: Qwen2_5_VLForConditionalGeneration,
|
| 32 |
+
processor: AutoProcessor,
|
| 33 |
+
result_suffix: str,
|
| 34 |
+
fps: float,
|
| 35 |
+
max_pixels: int,
|
| 36 |
+
total_pixels: Optional[int],
|
| 37 |
+
gen_tokens: int
|
| 38 |
+
):
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
result_json_path = f"{os.path.splitext(json_path)[0]}{result_suffix}"
|
| 42 |
+
|
| 43 |
+
if os.path.exists(result_json_path):
|
| 44 |
+
print(f" [INFO] Result file '{os.path.basename(result_json_path)}' already exists. Skipping.")
|
| 45 |
+
return
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
with open(json_path, 'r', encoding='utf-8') as f:
|
| 49 |
+
data = json.load(f)
|
| 50 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 51 |
+
print(f"Could not read or parse JSON file {json_path}: {e}")
|
| 52 |
+
return
|
| 53 |
+
from qwen_vl_utils import process_vision_info
|
| 54 |
+
|
| 55 |
+
all_results = []
|
| 56 |
+
for item in tqdm(data, desc=f" Inferring on {os.path.basename(json_path)}"):
|
| 57 |
+
start_time = time.time()
|
| 58 |
+
model_output = "N/A"
|
| 59 |
+
|
| 60 |
+
try:
|
| 61 |
+
prompt_text = item['conversations'][0]['value']
|
| 62 |
+
ground_truth = item['conversations'][1]['value']
|
| 63 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 64 |
+
media_relative_path = item.get(media_path_key)
|
| 65 |
+
|
| 66 |
+
if not media_relative_path:
|
| 67 |
+
raise ValueError("JSON entry is missing 'image' or 'video' key.")
|
| 68 |
+
|
| 69 |
+
base_dir = os.path.dirname(json_path)
|
| 70 |
+
media_full_path = os.path.join(base_dir, media_relative_path)
|
| 71 |
+
|
| 72 |
+
if not os.path.exists(media_full_path):
|
| 73 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 74 |
+
|
| 75 |
+
media_type = get_media_type(media_full_path)
|
| 76 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 77 |
+
|
| 78 |
+
content: List[Dict[str, Any]] = []
|
| 79 |
+
media_abs_path = os.path.abspath(media_full_path)
|
| 80 |
+
|
| 81 |
+
if media_type == 'image':
|
| 82 |
+
content.append({"type": "image", "image": media_abs_path})
|
| 83 |
+
else: # video
|
| 84 |
+
video_item = {
|
| 85 |
+
"type": "video",
|
| 86 |
+
"video": media_abs_path,
|
| 87 |
+
"fps": float(fps),
|
| 88 |
+
"max_pixels": int(max_pixels),
|
| 89 |
+
}
|
| 90 |
+
if total_pixels is not None and total_pixels > 0:
|
| 91 |
+
video_item["total_pixels"] = int(total_pixels)
|
| 92 |
+
content.append(video_item)
|
| 93 |
+
|
| 94 |
+
content.append({"type": "text", "text": clean_prompt})
|
| 95 |
+
messages = [{"role": "user", "content": content}]
|
| 96 |
+
|
| 97 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 98 |
+
|
| 99 |
+
image_inputs, video_inputs, video_kwargs = process_vision_info(messages, return_video_kwargs=True)
|
| 100 |
+
|
| 101 |
+
inputs = processor(
|
| 102 |
+
text=[text], images=image_inputs, videos=video_inputs,
|
| 103 |
+
padding=True, return_tensors="pt", **video_kwargs,
|
| 104 |
+
)
|
| 105 |
+
inputs = inputs.to(model.device)
|
| 106 |
+
|
| 107 |
+
generated_ids = model.generate(**inputs, max_new_tokens=gen_tokens, do_sample=False)
|
| 108 |
+
generated_ids_trimmed = [out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 109 |
+
output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
|
| 110 |
+
model_output = (output_text[0] if output_text else "").strip()
|
| 111 |
+
|
| 112 |
+
except Exception as e:
|
| 113 |
+
model_output = f"ERROR: {str(e)}\n{traceback.format_exc()}"
|
| 114 |
+
|
| 115 |
+
end_time = time.time()
|
| 116 |
+
all_results.append({
|
| 117 |
+
"id": item.get('id', 'N/A'),
|
| 118 |
+
"prompt": prompt_text,
|
| 119 |
+
"model_output": model_output,
|
| 120 |
+
"ground_truth": ground_truth,
|
| 121 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 122 |
+
})
|
| 123 |
+
|
| 124 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 125 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main():
|
| 129 |
+
parser = argparse.ArgumentParser(description="Qwen2.5-VL Batch Inference (High-Performance Mode)")
|
| 130 |
+
parser.add_argument("--model-path", default=DEFAULT_MODEL_PATH, help="Path to the local model directory.")
|
| 131 |
+
parser.add_argument("--result-suffix", default="_result.json", help="Suffix for result files.")
|
| 132 |
+
parser.add_argument("--fps", type=float, default=1.0, help="Frame rate for video sampling.")
|
| 133 |
+
parser.add_argument("--max-pixels", type=int, default=360*420, help="Maximum pixels per frame.")
|
| 134 |
+
parser.add_argument("--total-pixels", type=int, default=0, help="Total pixel limit for a video (0 for unlimited).")
|
| 135 |
+
parser.add_argument("--max-new-tokens", type=int, default=1024, help="Maximum number of new tokens to generate.")
|
| 136 |
+
args = parser.parse_args()
|
| 137 |
+
|
| 138 |
+
if not args.model_path or args.model_path == "path/to/your/Qwen2.5-VL-model":
|
| 139 |
+
exit(1)
|
| 140 |
+
|
| 141 |
+
print(f"Model Path: {args.model_path}")
|
| 142 |
+
|
| 143 |
+
try:
|
| 144 |
+
import flash_attn
|
| 145 |
+
attn_implementation = "flash_attention_2"
|
| 146 |
+
print("Flash Attention 2 detected. Using for better performance.")
|
| 147 |
+
except ImportError:
|
| 148 |
+
attn_implementation = "eager"
|
| 149 |
+
print("Flash Attention 2 not found. ")
|
| 150 |
+
|
| 151 |
+
print(f"Loading model with bfloat16 + {attn_implementation}...")
|
| 152 |
+
|
| 153 |
+
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
|
| 154 |
+
args.model_path,
|
| 155 |
+
torch_dtype=torch.bfloat16,
|
| 156 |
+
attn_implementation=attn_implementation,
|
| 157 |
+
device_map="auto",
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
processor = AutoProcessor.from_pretrained(args.model_path)
|
| 161 |
+
current_dir = os.getcwd()
|
| 162 |
+
source_files = [
|
| 163 |
+
f for f in os.listdir(current_dir)
|
| 164 |
+
if f.endswith('.json') and not f.endswith(args.result_suffix)
|
| 165 |
+
]
|
| 166 |
+
|
| 167 |
+
if not source_files:
|
| 168 |
+
print(f"\nNo source JSON files.")
|
| 169 |
+
else:
|
| 170 |
+
print(f"\nFound {len(source_files)} JSON file(s) to process.")
|
| 171 |
+
|
| 172 |
+
for json_filename in sorted(source_files):
|
| 173 |
+
json_full_path = os.path.join(current_dir, json_filename)
|
| 174 |
+
run_inference_on_file(
|
| 175 |
+
json_full_path, model, processor, args.result_suffix,
|
| 176 |
+
fps=args.fps, max_pixels=args.max_pixels,
|
| 177 |
+
total_pixels=(args.total_pixels if args.total_pixels > 0 else None),
|
| 178 |
+
gen_tokens=args.max_new_tokens
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
if __name__ == "__main__":
|
| 183 |
+
main()
|
code/test_code/test_r1omni.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import argparse
|
| 5 |
+
import time
|
| 6 |
+
import sys
|
| 7 |
+
import glob
|
| 8 |
+
from typing import Dict, Any, List
|
| 9 |
+
from tqdm import tqdm
|
| 10 |
+
import torch
|
| 11 |
+
import torch.multiprocessing as mp
|
| 12 |
+
from transformers import BertTokenizer
|
| 13 |
+
|
| 14 |
+
from humanomni import model_init, mm_infer
|
| 15 |
+
from humanomni.utils import disable_torch_init
|
| 16 |
+
|
| 17 |
+
worker_model_objects: Dict[str, Any] = {}
|
| 18 |
+
|
| 19 |
+
def init_worker(model_path: str, bert_path: str, device: str):
|
| 20 |
+
global worker_model_objects
|
| 21 |
+
try:
|
| 22 |
+
disable_torch_init()
|
| 23 |
+
model, processor, tokenizer = model_init(model_path, device=device)
|
| 24 |
+
bert_tokenizer = BertTokenizer.from_pretrained(bert_path)
|
| 25 |
+
worker_model_objects = {
|
| 26 |
+
"model": model,
|
| 27 |
+
"processor": processor,
|
| 28 |
+
"tokenizer": tokenizer,
|
| 29 |
+
"bert_tokenizer": bert_tokenizer,
|
| 30 |
+
}
|
| 31 |
+
except Exception as e:
|
| 32 |
+
import traceback
|
| 33 |
+
traceback.print_exc()
|
| 34 |
+
raise e
|
| 35 |
+
|
| 36 |
+
def get_media_type(file_path: str) -> str:
|
| 37 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 38 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 39 |
+
return 'video'
|
| 40 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 41 |
+
return 'image'
|
| 42 |
+
else:
|
| 43 |
+
return 'unknown'
|
| 44 |
+
|
| 45 |
+
def process_single_sample(media_full_path: str, prompt_text: str) -> str:
|
| 46 |
+
global worker_model_objects
|
| 47 |
+
try:
|
| 48 |
+
model = worker_model_objects['model']
|
| 49 |
+
processor = worker_model_objects['processor']
|
| 50 |
+
tokenizer = worker_model_objects['tokenizer']
|
| 51 |
+
bert_tokenizer = worker_model_objects['bert_tokenizer']
|
| 52 |
+
|
| 53 |
+
media_type = get_media_type(media_full_path)
|
| 54 |
+
if media_type == 'unknown':
|
| 55 |
+
raise ValueError(f"Unsupported media type for file: {media_full_path}")
|
| 56 |
+
|
| 57 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 58 |
+
media_tensor, audio_tensor, modal_str = None, None, ""
|
| 59 |
+
|
| 60 |
+
if media_type == 'video':
|
| 61 |
+
media_tensor = processor['video'](media_full_path)
|
| 62 |
+
audio_tensor = processor['audio'](media_full_path)[0]
|
| 63 |
+
modal_str = 'video_audio'
|
| 64 |
+
elif media_type == 'image':
|
| 65 |
+
media_tensor = processor['image'](media_full_path)
|
| 66 |
+
modal_str = 'image'
|
| 67 |
+
|
| 68 |
+
output = mm_infer(
|
| 69 |
+
media=media_tensor,
|
| 70 |
+
instruct=clean_prompt,
|
| 71 |
+
model=model,
|
| 72 |
+
tokenizer=tokenizer,
|
| 73 |
+
modal=modal_str,
|
| 74 |
+
question=clean_prompt,
|
| 75 |
+
bert_tokeni=bert_tokenizer,
|
| 76 |
+
do_sample=False,
|
| 77 |
+
audio=audio_tensor
|
| 78 |
+
)
|
| 79 |
+
return output
|
| 80 |
+
except Exception as e:
|
| 81 |
+
import traceback
|
| 82 |
+
return f"ERROR: {e}\n{traceback.format_exc()}"
|
| 83 |
+
|
| 84 |
+
def text_only_fallback(prompt_text: str) -> str:
|
| 85 |
+
|
| 86 |
+
global worker_model_objects
|
| 87 |
+
try:
|
| 88 |
+
model = worker_model_objects['model']
|
| 89 |
+
tokenizer = worker_model_objects['tokenizer']
|
| 90 |
+
|
| 91 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 92 |
+
inputs = tokenizer(clean_prompt, return_tensors="pt").to(model.device)
|
| 93 |
+
|
| 94 |
+
output_ids = model.generate(
|
| 95 |
+
input_ids=inputs.input_ids,
|
| 96 |
+
attention_mask=inputs.attention_mask,
|
| 97 |
+
max_new_tokens=512,
|
| 98 |
+
do_sample=False
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
response = tokenizer.decode(output_ids[0], skip_special_tokens=True)
|
| 102 |
+
|
| 103 |
+
if response.startswith(clean_prompt):
|
| 104 |
+
return response[len(clean_prompt):].strip()
|
| 105 |
+
return response
|
| 106 |
+
except Exception as e:
|
| 107 |
+
return f"ERROR in text-only fallback: {str(e)}"
|
| 108 |
+
|
| 109 |
+
def run_inference_task(media_full_path: str, prompt_text: str) -> str:
|
| 110 |
+
if not worker_model_objects: return "ERROR: Worker model not initialized."
|
| 111 |
+
return process_single_sample(media_full_path, prompt_text)
|
| 112 |
+
|
| 113 |
+
def run_fallback_task(prompt_text: str) -> str:
|
| 114 |
+
if not worker_model_objects: return "ERROR: Worker model not initialized."
|
| 115 |
+
return text_only_fallback(prompt_text)
|
| 116 |
+
|
| 117 |
+
def process_json_file(
|
| 118 |
+
dataset_json_path: str,
|
| 119 |
+
result_suffix: str,
|
| 120 |
+
pool_ref: List[mp.Pool],
|
| 121 |
+
model_path: str,
|
| 122 |
+
bert_path: str,
|
| 123 |
+
device: str
|
| 124 |
+
):
|
| 125 |
+
|
| 126 |
+
base_dir = os.path.dirname(dataset_json_path)
|
| 127 |
+
json_filename = os.path.basename(dataset_json_path)
|
| 128 |
+
result_json_path = os.path.join(base_dir, f"{os.path.splitext(json_filename)[0]}{result_suffix}")
|
| 129 |
+
|
| 130 |
+
if os.path.exists(result_json_path):
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
try:
|
| 134 |
+
with open(dataset_json_path, "r", encoding="utf-8") as f:
|
| 135 |
+
data = json.load(f)
|
| 136 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
all_results = []
|
| 140 |
+
for item in tqdm(data, desc=f" Inferring on {json_filename}", unit="item"):
|
| 141 |
+
start_time = time.time()
|
| 142 |
+
model_output, prompt, ground_truth = "", "", ""
|
| 143 |
+
pool = pool_ref[0]
|
| 144 |
+
|
| 145 |
+
try:
|
| 146 |
+
prompt = item["conversations"][0]["value"]
|
| 147 |
+
ground_truth = item["conversations"][1]["value"]
|
| 148 |
+
media_relative_path = item.get('image') or item.get('video')
|
| 149 |
+
|
| 150 |
+
if not media_relative_path:
|
| 151 |
+
model_output = pool.apply(run_fallback_task, args=(prompt,))
|
| 152 |
+
else:
|
| 153 |
+
media_full_path = os.path.join(base_dir, media_relative_path)
|
| 154 |
+
if not os.path.exists(media_full_path):
|
| 155 |
+
model_output = pool.apply(run_fallback_task, args=(prompt,))
|
| 156 |
+
else:
|
| 157 |
+
async_result = pool.apply_async(run_inference_task, args=(media_full_path, prompt))
|
| 158 |
+
try:
|
| 159 |
+
model_output = async_result.get(timeout=60)
|
| 160 |
+
except (mp.TimeoutError, Exception) as e:
|
| 161 |
+
pool.terminate()
|
| 162 |
+
pool.join()
|
| 163 |
+
pool_ref[0] = mp.Pool(processes=1, initializer=init_worker, initargs=(model_path, bert_path, device))
|
| 164 |
+
model_output = pool_ref[0].apply(run_fallback_task, args=(prompt,))
|
| 165 |
+
|
| 166 |
+
except Exception as e:
|
| 167 |
+
model_output = f"ERROR: Main loop error: {e}"
|
| 168 |
+
print(f"\n {model_output}")
|
| 169 |
+
|
| 170 |
+
end_time = time.time()
|
| 171 |
+
all_results.append({
|
| 172 |
+
"id": item.get("id", "N/A"),
|
| 173 |
+
"prompt": prompt,
|
| 174 |
+
"model_output": model_output,
|
| 175 |
+
"ground_truth": ground_truth,
|
| 176 |
+
"processing_time_seconds": round(end_time - start_time, 2),
|
| 177 |
+
})
|
| 178 |
+
|
| 179 |
+
with open(result_json_path, "w", encoding="utf-8") as f:
|
| 180 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 181 |
+
|
| 182 |
+
def main():
|
| 183 |
+
parser = argparse.ArgumentParser(description="Batch inference with R1-Omni model on local JSON datasets.")
|
| 184 |
+
parser.add_argument("--model-path", required=True, help="Path to the R1-Omni model directory.")
|
| 185 |
+
parser.add_argument("--bert-path", required=True, help="Path to the bert-base-uncased tokenizer directory.")
|
| 186 |
+
parser.add_argument("--input-dir", default=".", help="Directory containing JSON datasets and media files.")
|
| 187 |
+
parser.add_argument("--device", default="cuda:0", help="Device to run the model on (e.g., 'cuda:0', 'cpu').")
|
| 188 |
+
parser.add_argument("--result-suffix", default="_r1omni_result.json", help="Suffix for result JSON files.")
|
| 189 |
+
args = parser.parse_args()
|
| 190 |
+
|
| 191 |
+
os.environ['TRANSFORMERS_OFFLINE'] = '1'
|
| 192 |
+
|
| 193 |
+
worker_device = args.device
|
| 194 |
+
if "cuda" in args.device:
|
| 195 |
+
gpu_id = args.device.split(':')[-1]
|
| 196 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_id
|
| 197 |
+
worker_device = "cuda:0"
|
| 198 |
+
|
| 199 |
+
pool_ref = [mp.Pool(
|
| 200 |
+
processes=1,
|
| 201 |
+
initializer=init_worker,
|
| 202 |
+
initargs=(args.model_path, args.bert_path, worker_device)
|
| 203 |
+
)]
|
| 204 |
+
|
| 205 |
+
try:
|
| 206 |
+
source_json_files = glob.glob(os.path.join(args.input_dir, "*.json"))
|
| 207 |
+
source_json_files = [f for f in source_json_files if not f.endswith(args.result_suffix)]
|
| 208 |
+
|
| 209 |
+
if not source_json_files:
|
| 210 |
+
return
|
| 211 |
+
|
| 212 |
+
for json_path in sorted(source_json_files):
|
| 213 |
+
process_json_file(
|
| 214 |
+
json_path,
|
| 215 |
+
args.result_suffix,
|
| 216 |
+
pool_ref,
|
| 217 |
+
args.model_path,
|
| 218 |
+
args.bert_path,
|
| 219 |
+
worker_device
|
| 220 |
+
)
|
| 221 |
+
finally:
|
| 222 |
+
pool_ref[0].close()
|
| 223 |
+
pool_ref[0].join()
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
if torch.cuda.is_available():
|
| 228 |
+
try:
|
| 229 |
+
mp.set_start_method('spawn', force=True)
|
| 230 |
+
except RuntimeError:
|
| 231 |
+
pass
|
| 232 |
+
main()
|
code/test_code/test_videollama3.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
from tqdm import tqdm
|
| 5 |
+
import time
|
| 6 |
+
import torch
|
| 7 |
+
from transformers import AutoModelForCausalLM, AutoProcessor
|
| 8 |
+
|
| 9 |
+
LEVEL_DIRS = ["level1", "level2", "level3"]
|
| 10 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 11 |
+
|
| 12 |
+
def get_media_type(file_path: str) -> str:
|
| 13 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 14 |
+
if ext in ['.mp4', '.avi', '.mov', '.mkv', '.webm']:
|
| 15 |
+
return 'video'
|
| 16 |
+
elif ext in ['.jpg', '.jpeg', '.png', '.bmp', '.gif', '.webp']:
|
| 17 |
+
return 'image'
|
| 18 |
+
else:
|
| 19 |
+
raise ValueError(f"Unsupported file extension: {ext} in file {file_path}")
|
| 20 |
+
|
| 21 |
+
def process_task(task_path: str, model, processor, result_suffix: str, device: str):
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
source_json_files = [
|
| 25 |
+
f for f in os.listdir(task_path)
|
| 26 |
+
if f.endswith('.json') and GENERIC_RESULT_PATTERN not in f
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
if not source_json_files:
|
| 30 |
+
return
|
| 31 |
+
|
| 32 |
+
for json_filename in source_json_files:
|
| 33 |
+
dataset_json_path = os.path.join(task_path, json_filename)
|
| 34 |
+
result_json_path = os.path.join(task_path, f"{os.path.splitext(json_filename)[0]}{result_suffix}")
|
| 35 |
+
|
| 36 |
+
if os.path.exists(result_json_path):
|
| 37 |
+
continue
|
| 38 |
+
|
| 39 |
+
try:
|
| 40 |
+
with open(dataset_json_path, 'r', encoding='utf-8') as f:
|
| 41 |
+
data = json.load(f)
|
| 42 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 43 |
+
continue
|
| 44 |
+
|
| 45 |
+
all_results = []
|
| 46 |
+
for item in tqdm(data, desc=f" Processing {json_filename}"):
|
| 47 |
+
start_time = time.time()
|
| 48 |
+
model_output = "N/A"
|
| 49 |
+
|
| 50 |
+
try:
|
| 51 |
+
prompt_text = item['conversations'][0]['value']
|
| 52 |
+
ground_truth = item['conversations'][1]['value']
|
| 53 |
+
media_path_key = 'image' if 'image' in item else 'video'
|
| 54 |
+
media_relative_path = item.get(media_path_key)
|
| 55 |
+
|
| 56 |
+
if not media_relative_path:
|
| 57 |
+
raise ValueError("Missing 'image' or 'video' key in JSON entry.")
|
| 58 |
+
|
| 59 |
+
media_full_path = os.path.join(task_path, media_relative_path)
|
| 60 |
+
if not os.path.exists(media_full_path):
|
| 61 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 62 |
+
|
| 63 |
+
media_type = get_media_type(media_full_path)
|
| 64 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 65 |
+
|
| 66 |
+
if media_type == 'image':
|
| 67 |
+
media_content = {"type": "image", "image": {"image_path": media_full_path}}
|
| 68 |
+
else:
|
| 69 |
+
media_content = {"type": "video", "video": {"video_path": media_full_path, "fps": 1, "max_frames": 128}}
|
| 70 |
+
|
| 71 |
+
conversation = [
|
| 72 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
| 73 |
+
{
|
| 74 |
+
"role": "user",
|
| 75 |
+
"content": [
|
| 76 |
+
media_content,
|
| 77 |
+
{"type": "text", "text": clean_prompt},
|
| 78 |
+
]
|
| 79 |
+
},
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
inputs = processor(conversation=conversation, return_tensors="pt")
|
| 83 |
+
inputs = {k: v.to(device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items()}
|
| 84 |
+
if "pixel_values" in inputs:
|
| 85 |
+
inputs["pixel_values"] = inputs["pixel_values"].to(torch.bfloat16)
|
| 86 |
+
|
| 87 |
+
output = model.generate(**inputs, max_new_tokens=1024, do_sample=False)
|
| 88 |
+
response = processor.batch_decode(output, skip_special_tokens=True)[0].strip()
|
| 89 |
+
|
| 90 |
+
last_turn_markers = ['assistant\n', 'assistant:']
|
| 91 |
+
for marker in last_turn_markers:
|
| 92 |
+
if marker in response.lower():
|
| 93 |
+
response = response.split(marker, 1)[-1].strip()
|
| 94 |
+
break
|
| 95 |
+
model_output = response
|
| 96 |
+
|
| 97 |
+
except Exception as e:
|
| 98 |
+
model_output = f"ERROR: {str(e)}"
|
| 99 |
+
|
| 100 |
+
end_time = time.time()
|
| 101 |
+
all_results.append({
|
| 102 |
+
"id": item.get('id', 'N/A'),
|
| 103 |
+
"prompt": prompt_text,
|
| 104 |
+
"model_output": model_output,
|
| 105 |
+
"ground_truth": ground_truth,
|
| 106 |
+
"processing_time_seconds": round(end_time - start_time, 2)
|
| 107 |
+
})
|
| 108 |
+
|
| 109 |
+
with open(result_json_path, 'w', encoding='utf-8') as f:
|
| 110 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def main():
|
| 114 |
+
parser = argparse.ArgumentParser(description="Batch processing script for a local multimodal model using the Transformers library.")
|
| 115 |
+
|
| 116 |
+
parser.add_argument("--model-path", required=True, help="Full path to the local model directory")
|
| 117 |
+
parser.add_argument("--result-suffix", required=True, help="Suffix for the generated result files")
|
| 118 |
+
parser.add_argument("--device", default="cuda:0", help="Device to run the model")
|
| 119 |
+
|
| 120 |
+
args = parser.parse_args()
|
| 121 |
+
try:
|
| 122 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 123 |
+
args.model_path,
|
| 124 |
+
trust_remote_code=True,
|
| 125 |
+
torch_dtype=torch.bfloat16,
|
| 126 |
+
attn_implementation="flash_attention_2",
|
| 127 |
+
device_map=args.device
|
| 128 |
+
)
|
| 129 |
+
processor = AutoProcessor.from_pretrained(args.model_path, trust_remote_code=True)
|
| 130 |
+
except Exception as e:
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
for level_dir in LEVEL_DIRS:
|
| 134 |
+
level_path = os.path.join(os.getcwd(), level_dir)
|
| 135 |
+
if not os.path.isdir(level_path):
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
task_dirs = sorted([d.path for d in os.scandir(level_path) if d.is_dir()])
|
| 139 |
+
for task_path in task_dirs:
|
| 140 |
+
process_task(task_path, model, processor, args.result_suffix, args.device)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
if __name__ == "__main__":
|
| 144 |
+
main()
|
code/train_code/train_gemini.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import argparse
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
from google import genai
|
| 8 |
+
import random
|
| 9 |
+
from collections import deque
|
| 10 |
+
#config
|
| 11 |
+
GENERIC_RESULT_PATTERN = "_result.json"
|
| 12 |
+
|
| 13 |
+
INLINE_SIZE_LIMIT_BYTES = 20 * 1024 * 1024
|
| 14 |
+
|
| 15 |
+
MODEL_NAME = "gemini-2.5-pro"
|
| 16 |
+
RESULT_SUFFIX = "_gemini_2.5_pro_result.json"
|
| 17 |
+
|
| 18 |
+
REQUESTS_PER_MINUTE = 30
|
| 19 |
+
MIN_REQUEST_INTERVAL = 60.0 / REQUESTS_PER_MINUTE
|
| 20 |
+
|
| 21 |
+
MAX_RETRIES = 5
|
| 22 |
+
INITIAL_RETRY_DELAY = 5
|
| 23 |
+
MAX_RETRY_DELAY = 120
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RateLimiter:
|
| 27 |
+
|
| 28 |
+
def __init__(self, requests_per_minute):
|
| 29 |
+
self.requests_per_minute = requests_per_minute
|
| 30 |
+
self.min_interval = 60.0 / requests_per_minute
|
| 31 |
+
self.last_request_time = 0
|
| 32 |
+
self.request_times = deque(maxlen=requests_per_minute)
|
| 33 |
+
|
| 34 |
+
def wait_if_needed(self):
|
| 35 |
+
current_time = time.time()
|
| 36 |
+
|
| 37 |
+
time_since_last = current_time - self.last_request_time
|
| 38 |
+
if time_since_last < self.min_interval:
|
| 39 |
+
sleep_time = self.min_interval - time_since_last
|
| 40 |
+
time.sleep(sleep_time)
|
| 41 |
+
current_time = time.time()
|
| 42 |
+
|
| 43 |
+
minute_ago = current_time - 60
|
| 44 |
+
while self.request_times and self.request_times[0] < minute_ago:
|
| 45 |
+
self.request_times.popleft()
|
| 46 |
+
|
| 47 |
+
if len(self.request_times) >= self.requests_per_minute:
|
| 48 |
+
sleep_time = 60 - (current_time - self.request_times[0]) + 0.1
|
| 49 |
+
if sleep_time > 0:
|
| 50 |
+
print(f" [RATE LIMIT] Waiting {sleep_time:.1f}s to respect rate limits...")
|
| 51 |
+
time.sleep(sleep_time)
|
| 52 |
+
current_time = time.time()
|
| 53 |
+
|
| 54 |
+
self.last_request_time = current_time
|
| 55 |
+
self.request_times.append(current_time)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_mime_type(file_path: str) -> str:
|
| 59 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 60 |
+
|
| 61 |
+
if ext in [".mp4", ".m4v", ".mov", ".avi", ".mkv", ".webm", ".mpg", ".mpeg", ".wmv", ".3gp", ".3gpp", ".flv"]:
|
| 62 |
+
return "video/mp4"
|
| 63 |
+
|
| 64 |
+
audio_types = {
|
| 65 |
+
".mp3": "audio/mp3",
|
| 66 |
+
".wav": "audio/wav",
|
| 67 |
+
".aac": "audio/aac",
|
| 68 |
+
".aiff": "audio/aiff",
|
| 69 |
+
".flac": "audio/flac",
|
| 70 |
+
".ogg": "audio/ogg"
|
| 71 |
+
}
|
| 72 |
+
if ext in audio_types:
|
| 73 |
+
return audio_types[ext]
|
| 74 |
+
|
| 75 |
+
image_types = {
|
| 76 |
+
".jpg": "image/jpeg",
|
| 77 |
+
".jpeg": "image/jpeg",
|
| 78 |
+
".png": "image/png",
|
| 79 |
+
".webp": "image/webp",
|
| 80 |
+
".gif": "image/gif"
|
| 81 |
+
}
|
| 82 |
+
if ext in image_types:
|
| 83 |
+
return image_types[ext]
|
| 84 |
+
|
| 85 |
+
return "application/octet-stream"
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _poll_file_ready(client: genai.Client, file_obj, sleep_s: float = 2.0, max_wait_s: float = 300.0) -> Optional[object]:
|
| 89 |
+
"""Poll file processing status."""
|
| 90 |
+
start = time.time()
|
| 91 |
+
name = getattr(file_obj, "name", None)
|
| 92 |
+
state = getattr(file_obj, "state", None)
|
| 93 |
+
state_name = getattr(state, "name", None) or str(state)
|
| 94 |
+
|
| 95 |
+
while state_name and state_name.upper() in ("PROCESSING", "PENDING"):
|
| 96 |
+
if time.time() - start > max_wait_s:
|
| 97 |
+
return None
|
| 98 |
+
time.sleep(sleep_s)
|
| 99 |
+
try:
|
| 100 |
+
file_obj = client.files.get(name=name)
|
| 101 |
+
except Exception:
|
| 102 |
+
time.sleep(sleep_s)
|
| 103 |
+
state = getattr(file_obj, "state", None)
|
| 104 |
+
state_name = getattr(state, "name", None) or str(state)
|
| 105 |
+
|
| 106 |
+
return file_obj
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def process_single_sample_with_retry(
|
| 110 |
+
client: genai.Client,
|
| 111 |
+
media_full_path: str,
|
| 112 |
+
prompt_text: str,
|
| 113 |
+
rate_limiter: RateLimiter,
|
| 114 |
+
item_id: str = "N/A"
|
| 115 |
+
) -> str:
|
| 116 |
+
"""Process a single sample with retry logic and rate limiting."""
|
| 117 |
+
retry_delay = INITIAL_RETRY_DELAY
|
| 118 |
+
last_error = None
|
| 119 |
+
|
| 120 |
+
for attempt in range(MAX_RETRIES):
|
| 121 |
+
try:
|
| 122 |
+
rate_limiter.wait_if_needed()
|
| 123 |
+
|
| 124 |
+
return process_single_sample(client, media_full_path, prompt_text)
|
| 125 |
+
|
| 126 |
+
except Exception as e:
|
| 127 |
+
last_error = e
|
| 128 |
+
error_str = str(e)
|
| 129 |
+
|
| 130 |
+
if any(x in error_str.lower() for x in ["503", "overloaded", "rate", "quota", "429"]):
|
| 131 |
+
if attempt < MAX_RETRIES - 1:
|
| 132 |
+
jitter = random.uniform(0, retry_delay * 0.3)
|
| 133 |
+
sleep_time = retry_delay + jitter
|
| 134 |
+
|
| 135 |
+
print(f"\n [RETRY] Item {item_id}: API overloaded/rate limited. "
|
| 136 |
+
f"Waiting {sleep_time:.1f}s... (Attempt {attempt + 1}/{MAX_RETRIES})")
|
| 137 |
+
time.sleep(sleep_time)
|
| 138 |
+
|
| 139 |
+
retry_delay = min(retry_delay * 2, MAX_RETRY_DELAY)
|
| 140 |
+
|
| 141 |
+
if "503" in error_str:
|
| 142 |
+
rate_limiter.min_interval *= 1.2
|
| 143 |
+
print(f" [THROTTLE] Slowing down to {60/rate_limiter.min_interval:.1f} RPM")
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
print(f"\n Item {item_id}: {error_str}")
|
| 147 |
+
return f"ERROR: {error_str}"
|
| 148 |
+
|
| 149 |
+
print(f"\n Item {item_id}: Max retries exceeded")
|
| 150 |
+
return f"ERROR: Max retries exceeded - {last_error}"
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def process_single_sample(client: genai.Client, media_full_path: str, prompt_text: str) -> str:
|
| 154 |
+
clean_prompt = prompt_text.replace("<image>", "").replace("<video>", "").strip()
|
| 155 |
+
file_size = os.path.getsize(media_full_path)
|
| 156 |
+
mime_type = get_mime_type(media_full_path)
|
| 157 |
+
|
| 158 |
+
if file_size < INLINE_SIZE_LIMIT_BYTES:
|
| 159 |
+
with open(media_full_path, "rb") as f:
|
| 160 |
+
file_bytes = f.read()
|
| 161 |
+
|
| 162 |
+
media_part = genai.types.Part(
|
| 163 |
+
inline_data=genai.types.Blob(data=file_bytes, mime_type=mime_type)
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
response = client.models.generate_content(
|
| 167 |
+
model=MODEL_NAME,
|
| 168 |
+
contents=[
|
| 169 |
+
media_part,
|
| 170 |
+
genai.types.Part(text=clean_prompt),
|
| 171 |
+
],
|
| 172 |
+
)
|
| 173 |
+
text_response = getattr(response, "text", None)
|
| 174 |
+
if text_response is None:
|
| 175 |
+
return "ERROR: Empty response from model"
|
| 176 |
+
return text_response
|
| 177 |
+
|
| 178 |
+
else:
|
| 179 |
+
uploaded_file = None
|
| 180 |
+
try:
|
| 181 |
+
print(f"\n [UPLOAD] Uploading: {os.path.basename(media_full_path)} ({file_size/1024**2:.1f} MB)...")
|
| 182 |
+
uploaded_file = client.files.upload(file=media_full_path)
|
| 183 |
+
|
| 184 |
+
uploaded_file = _poll_file_ready(client, uploaded_file)
|
| 185 |
+
if uploaded_file is None:
|
| 186 |
+
raise RuntimeError("File processing timeout in Files API.")
|
| 187 |
+
|
| 188 |
+
response = client.models.generate_content(
|
| 189 |
+
model=MODEL_NAME,
|
| 190 |
+
contents=[
|
| 191 |
+
uploaded_file,
|
| 192 |
+
genai.types.Part(text=clean_prompt)
|
| 193 |
+
],
|
| 194 |
+
)
|
| 195 |
+
text_response = getattr(response, "text", None)
|
| 196 |
+
if text_response is None:
|
| 197 |
+
return "ERROR: Empty response from model"
|
| 198 |
+
return text_response
|
| 199 |
+
finally:
|
| 200 |
+
try:
|
| 201 |
+
if uploaded_file and getattr(uploaded_file, "name", None):
|
| 202 |
+
client.files.delete(name=uploaded_file.name)
|
| 203 |
+
except Exception:
|
| 204 |
+
pass
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def save_result_immediately(result_json_path: str, all_results: list):
|
| 208 |
+
os.makedirs(os.path.dirname(result_json_path) or ".", exist_ok=True)
|
| 209 |
+
|
| 210 |
+
temp_path = result_json_path + f".tmp_{os.getpid()}"
|
| 211 |
+
try:
|
| 212 |
+
with open(temp_path, "w", encoding="utf-8") as f:
|
| 213 |
+
json.dump(all_results, f, indent=4, ensure_ascii=False)
|
| 214 |
+
|
| 215 |
+
os.replace(temp_path, result_json_path)
|
| 216 |
+
|
| 217 |
+
os.sync() if hasattr(os, 'sync') else None
|
| 218 |
+
|
| 219 |
+
except Exception as e:
|
| 220 |
+
print(f"\n Failed to save results: {e}")
|
| 221 |
+
if os.path.exists(temp_path):
|
| 222 |
+
os.remove(temp_path)
|
| 223 |
+
raise
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def load_existing_results(result_json_path: str) -> tuple[list, set]:
|
| 227 |
+
if os.path.exists(result_json_path):
|
| 228 |
+
try:
|
| 229 |
+
with open(result_json_path, "r", encoding="utf-8") as f:
|
| 230 |
+
existing_results = json.load(f)
|
| 231 |
+
processed_ids = {item.get("id") for item in existing_results if item.get("id")}
|
| 232 |
+
return existing_results, processed_ids
|
| 233 |
+
except Exception as e:
|
| 234 |
+
print(f"Could not load existing results: {e}")
|
| 235 |
+
return [], set()
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def process_json_file(
|
| 239 |
+
json_path: str,
|
| 240 |
+
client: genai.Client,
|
| 241 |
+
resume: bool = True,
|
| 242 |
+
requests_per_minute: int = REQUESTS_PER_MINUTE
|
| 243 |
+
):
|
| 244 |
+
json_filename = os.path.basename(json_path)
|
| 245 |
+
working_dir = os.path.dirname(json_path) or "."
|
| 246 |
+
result_json_path = os.path.join(
|
| 247 |
+
working_dir,
|
| 248 |
+
f"{os.path.splitext(json_filename)[0]}{RESULT_SUFFIX}"
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
rate_limiter = RateLimiter(requests_per_minute)
|
| 252 |
+
|
| 253 |
+
all_results = []
|
| 254 |
+
processed_ids = set()
|
| 255 |
+
if resume:
|
| 256 |
+
all_results, processed_ids = load_existing_results(result_json_path)
|
| 257 |
+
if processed_ids:
|
| 258 |
+
print(f"Found {len(processed_ids)} already processed items")
|
| 259 |
+
|
| 260 |
+
try:
|
| 261 |
+
with open(json_path, "r", encoding="utf-8") as f:
|
| 262 |
+
data = json.load(f)
|
| 263 |
+
print(f"Loaded {len(data)} total items from source file")
|
| 264 |
+
except (json.JSONDecodeError, FileNotFoundError) as e:
|
| 265 |
+
print(f" Could not read JSON file {json_path}: {e}")
|
| 266 |
+
return
|
| 267 |
+
|
| 268 |
+
items_to_process = []
|
| 269 |
+
for i, item in enumerate(data):
|
| 270 |
+
item_id = item.get("id", f"item_{i}")
|
| 271 |
+
if "id" not in item:
|
| 272 |
+
item["id"] = item_id
|
| 273 |
+
if resume and item_id in processed_ids:
|
| 274 |
+
continue
|
| 275 |
+
items_to_process.append(item)
|
| 276 |
+
|
| 277 |
+
if not items_to_process:
|
| 278 |
+
print(f"All items already processed!")
|
| 279 |
+
return
|
| 280 |
+
|
| 281 |
+
if not os.path.exists(result_json_path):
|
| 282 |
+
save_result_immediately(result_json_path, all_results)
|
| 283 |
+
print(f" Result file: {result_json_path}\n")
|
| 284 |
+
|
| 285 |
+
with tqdm(items_to_process, desc="Progress", ncols=100) as pbar:
|
| 286 |
+
for idx, item in enumerate(pbar):
|
| 287 |
+
start_time = time.time()
|
| 288 |
+
item_id = item.get("id", f"item_{idx}")
|
| 289 |
+
|
| 290 |
+
pbar.set_description(f"Processing {item_id}")
|
| 291 |
+
|
| 292 |
+
try:
|
| 293 |
+
prompt = item["conversations"][0]["value"]
|
| 294 |
+
ground_truth = item["conversations"][1]["value"]
|
| 295 |
+
|
| 296 |
+
media_path_key = "image" if "image" in item else "video"
|
| 297 |
+
media_relative_path = item.get(media_path_key)
|
| 298 |
+
if not media_relative_path:
|
| 299 |
+
raise ValueError("Missing 'image' or 'video' key")
|
| 300 |
+
|
| 301 |
+
media_full_path = os.path.join(working_dir, media_relative_path)
|
| 302 |
+
if not os.path.exists(media_full_path):
|
| 303 |
+
raise FileNotFoundError(f"Media file not found: {media_full_path}")
|
| 304 |
+
|
| 305 |
+
model_output = process_single_sample_with_retry(
|
| 306 |
+
client, media_full_path, prompt, rate_limiter, item_id
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
except Exception as e:
|
| 310 |
+
model_output = f"ERROR: {str(e)}"
|
| 311 |
+
print(f"\n[ERROR] Failed item {item_id}: {e}")
|
| 312 |
+
prompt = item.get("conversations", [{}])[0].get("value", "")
|
| 313 |
+
ground_truth = item.get("conversations", [{}, {}])[1].get("value", "")
|
| 314 |
+
|
| 315 |
+
end_time = time.time()
|
| 316 |
+
processing_time = round(end_time - start_time, 2)
|
| 317 |
+
|
| 318 |
+
if model_output is None:
|
| 319 |
+
model_output = "ERROR: Null response from model"
|
| 320 |
+
|
| 321 |
+
result_item = {
|
| 322 |
+
"id": item_id,
|
| 323 |
+
"prompt": prompt,
|
| 324 |
+
"model_output": model_output,
|
| 325 |
+
"ground_truth": ground_truth,
|
| 326 |
+
"processing_time_seconds": processing_time,
|
| 327 |
+
}
|
| 328 |
+
|
| 329 |
+
all_results.append(result_item)
|
| 330 |
+
|
| 331 |
+
save_result_immediately(result_json_path, all_results)
|
| 332 |
+
|
| 333 |
+
current_rpm = 60 / rate_limiter.min_interval
|
| 334 |
+
|
| 335 |
+
success_count = sum(1 for r in all_results
|
| 336 |
+
if r.get("model_output") and not str(r["model_output"]).startswith("ERROR"))
|
| 337 |
+
error_count = len(all_results) - success_count
|
| 338 |
+
|
| 339 |
+
pbar.set_postfix({
|
| 340 |
+
"Saved": len(all_results),
|
| 341 |
+
"OK": success_count,
|
| 342 |
+
"Err": error_count,
|
| 343 |
+
"RPM": f"{current_rpm:.1f}",
|
| 344 |
+
"Time": f"{processing_time:.1f}s"
|
| 345 |
+
})
|
| 346 |
+
|
| 347 |
+
success_count = sum(1 for r in all_results
|
| 348 |
+
if r.get("model_output") and not str(r["model_output"]).startswith("ERROR"))
|
| 349 |
+
error_count = len(all_results) - success_count
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def main():
|
| 353 |
+
parser = argparse.ArgumentParser(
|
| 354 |
+
description=f"Process task with {MODEL_NAME} - saves after each item."
|
| 355 |
+
)
|
| 356 |
+
parser.add_argument(
|
| 357 |
+
"--api-key",
|
| 358 |
+
default=os.getenv("GOOGLE_API_KEY", "API_KEY"),
|
| 359 |
+
help="Google Gemini API key (or set env GOOGLE_API_KEY)."
|
| 360 |
+
)
|
| 361 |
+
parser.add_argument(
|
| 362 |
+
"--json-file",
|
| 363 |
+
type=str,
|
| 364 |
+
help="Specific JSON file to process."
|
| 365 |
+
)
|
| 366 |
+
parser.add_argument(
|
| 367 |
+
"--no-resume",
|
| 368 |
+
action="store_true",
|
| 369 |
+
help="Start from scratch (ignore existing results)."
|
| 370 |
+
)
|
| 371 |
+
parser.add_argument(
|
| 372 |
+
"--rpm",
|
| 373 |
+
type=int,
|
| 374 |
+
default=REQUESTS_PER_MINUTE,
|
| 375 |
+
help=f"Requests per minute limit (default: {REQUESTS_PER_MINUTE})."
|
| 376 |
+
)
|
| 377 |
+
args = parser.parse_args()
|
| 378 |
+
|
| 379 |
+
if not args.api_key:
|
| 380 |
+
print("\nPlease provide your Google Gemini API key.")
|
| 381 |
+
return
|
| 382 |
+
|
| 383 |
+
try:
|
| 384 |
+
client = genai.Client(api_key=args.api_key)
|
| 385 |
+
except Exception as e:
|
| 386 |
+
print(f"\n Failed to initialize Gemini client: {e}")
|
| 387 |
+
return
|
| 388 |
+
|
| 389 |
+
if args.json_file:
|
| 390 |
+
if not os.path.exists(args.json_file):
|
| 391 |
+
print(f"\n JSON file not found: {args.json_file}")
|
| 392 |
+
return
|
| 393 |
+
process_json_file(args.json_file, client, not args.no_resume, args.rpm)
|
| 394 |
+
else:
|
| 395 |
+
current_dir = os.getcwd()
|
| 396 |
+
json_files = [
|
| 397 |
+
f for f in os.listdir(current_dir)
|
| 398 |
+
if f.endswith(".json") and GENERIC_RESULT_PATTERN not in f
|
| 399 |
+
]
|
| 400 |
+
|
| 401 |
+
if not json_files:
|
| 402 |
+
print(f"\nNo source JSON files found in current directory.")
|
| 403 |
+
return
|
| 404 |
+
for f in json_files:
|
| 405 |
+
print(f" - {f}")
|
| 406 |
+
|
| 407 |
+
for json_file in json_files:
|
| 408 |
+
json_path = os.path.join(current_dir, json_file)
|
| 409 |
+
process_json_file(json_path, client, not args.no_resume, args.rpm)
|
| 410 |
+
|
| 411 |
+
if __name__ == "__main__":
|
| 412 |
+
main()
|
code/train_code/train_gpt4o.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
API_KEY = os.environ.get("OPENAI_API_KEY", "api-key")
|
| 8 |
+
client = OpenAI(api_key=API_KEY)
|
| 9 |
+
MODEL_NAME = "gpt-4o"
|
| 10 |
+
|
| 11 |
+
INPUT_FILE = "example.json"
|
| 12 |
+
OUTPUT_FILE = "gpt4o_results.json"
|
| 13 |
+
|
| 14 |
+
TEST_MODE = True
|
| 15 |
+
TEST_ITEMS = 5
|
| 16 |
+
|
| 17 |
+
MAX_RETRY = 3
|
| 18 |
+
SLEEP_BETWEEN_RETRY = 3
|
| 19 |
+
REASONING_EFFORT = "high"
|
| 20 |
+
|
| 21 |
+
def call_gpt4o_with_retry(prompt, attempt_num=1):
|
| 22 |
+
for retry in range(MAX_RETRY):
|
| 23 |
+
try:
|
| 24 |
+
|
| 25 |
+
response = client.responses.create(
|
| 26 |
+
model=MODEL_NAME,
|
| 27 |
+
reasoning={"effort": REASONING_EFFORT},
|
| 28 |
+
input=[{
|
| 29 |
+
"role": "user",
|
| 30 |
+
"content": [{"type": "input_text", "text": prompt}]
|
| 31 |
+
}]
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
return response.output_text
|
| 35 |
+
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f" Error on attempt {retry + 1}: {str(e)}")
|
| 38 |
+
if retry < MAX_RETRY - 1:
|
| 39 |
+
print(f" Retrying in {SLEEP_BETWEEN_RETRY} seconds...")
|
| 40 |
+
time.sleep(SLEEP_BETWEEN_RETRY)
|
| 41 |
+
else:
|
| 42 |
+
print(f"Failed after {MAX_RETRY} attempts")
|
| 43 |
+
return None
|
| 44 |
+
return None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def extract_prompt_and_truth(conversations):
|
| 48 |
+
prompt = None
|
| 49 |
+
ground_truth = None
|
| 50 |
+
|
| 51 |
+
if conversations and len(conversations) > 0 and conversations[0]["from"] == "human":
|
| 52 |
+
prompt = conversations[0]["value"].strip()
|
| 53 |
+
|
| 54 |
+
if len(conversations) >= 2 and conversations[1]["from"] == "gpt":
|
| 55 |
+
ground_truth = conversations[1]["value"]
|
| 56 |
+
|
| 57 |
+
return prompt, ground_truth
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
if not os.path.exists(INPUT_FILE):
|
| 62 |
+
print(f"Error: Input file '{INPUT_FILE}' not found")
|
| 63 |
+
return
|
| 64 |
+
|
| 65 |
+
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
|
| 66 |
+
data = json.load(f)
|
| 67 |
+
|
| 68 |
+
print(f"Loaded {len(data)} items from {INPUT_FILE}")
|
| 69 |
+
|
| 70 |
+
items_to_process = data[:TEST_ITEMS] if TEST_MODE else data
|
| 71 |
+
results = []
|
| 72 |
+
|
| 73 |
+
for idx, item in enumerate(items_to_process, 1):
|
| 74 |
+
item_id = item.get("id")
|
| 75 |
+
conversations = item.get("conversations", [])
|
| 76 |
+
|
| 77 |
+
print(f"\n[{idx}/{len(items_to_process)}] Processing ID: {item_id}")
|
| 78 |
+
|
| 79 |
+
if not conversations:
|
| 80 |
+
print(f"Skipping: missing conversations")
|
| 81 |
+
continue
|
| 82 |
+
|
| 83 |
+
prompt, ground_truth = extract_prompt_and_truth(conversations)
|
| 84 |
+
|
| 85 |
+
if not prompt:
|
| 86 |
+
print(f"Skipping: no prompt found")
|
| 87 |
+
continue
|
| 88 |
+
|
| 89 |
+
print(f" Ground Truth: {ground_truth}")
|
| 90 |
+
|
| 91 |
+
response1 = call_gpt4o_with_retry(prompt, attempt_num=1)
|
| 92 |
+
|
| 93 |
+
response2 = call_gpt4o_with_retry(prompt, attempt_num=2)
|
| 94 |
+
|
| 95 |
+
result = {
|
| 96 |
+
"id": item_id,
|
| 97 |
+
"response_1": response1,
|
| 98 |
+
"response_2": response2,
|
| 99 |
+
"ground_truth": ground_truth
|
| 100 |
+
}
|
| 101 |
+
results.append(result)
|
| 102 |
+
|
| 103 |
+
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
|
| 104 |
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
main()
|
code/train_code/train_gpt5.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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base64
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
from openai import OpenAI
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
API_KEY = os.environ.get("OPENAI_API_KEY", "api-key")
|
| 10 |
+
client = OpenAI(api_key=API_KEY)
|
| 11 |
+
MODEL_NAME = "gpt-5"
|
| 12 |
+
|
| 13 |
+
INPUT_FILE = "example.json"
|
| 14 |
+
OUTPUT_FILE = "gpt5_results.json"
|
| 15 |
+
|
| 16 |
+
TEST_MODE = True
|
| 17 |
+
TEST_ITEMS = 5
|
| 18 |
+
VIDEO_SAMPLE_INTERVAL = 25
|
| 19 |
+
|
| 20 |
+
MAX_RETRY = 3
|
| 21 |
+
SLEEP_BETWEEN_RETRY = 3
|
| 22 |
+
REASONING_EFFORT = "high"
|
| 23 |
+
|
| 24 |
+
VIDEO_EXTENSIONS = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv']
|
| 25 |
+
IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
|
| 26 |
+
|
| 27 |
+
def encode_image_to_base64(image_path):
|
| 28 |
+
try:
|
| 29 |
+
with open(image_path, "rb") as image_file:
|
| 30 |
+
return base64.b64encode(image_file.read()).decode('utf-8')
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"Error encoding image {image_path}: {str(e)}")
|
| 33 |
+
return None
|
| 34 |
+
|
| 35 |
+
def process_video(video_path, sample_interval=VIDEO_SAMPLE_INTERVAL):
|
| 36 |
+
try:
|
| 37 |
+
video = cv2.VideoCapture(video_path)
|
| 38 |
+
base64_frames = []
|
| 39 |
+
frame_count = 0
|
| 40 |
+
|
| 41 |
+
while video.isOpened():
|
| 42 |
+
success, frame = video.read()
|
| 43 |
+
if not success:
|
| 44 |
+
break
|
| 45 |
+
frame_count += 1
|
| 46 |
+
|
| 47 |
+
if (frame_count - 1) % sample_interval == 0:
|
| 48 |
+
_, buffer = cv2.imencode(".jpg", frame)
|
| 49 |
+
base64_frames.append(base64.b64encode(buffer).decode("utf-8"))
|
| 50 |
+
|
| 51 |
+
video.release()
|
| 52 |
+
print(f"Processed video: {frame_count} total frames, sampled {len(base64_frames)} frames")
|
| 53 |
+
return base64_frames
|
| 54 |
+
|
| 55 |
+
except Exception as e:
|
| 56 |
+
print(f"Error processing video {video_path}: {str(e)}")
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
def determine_media_type(file_path):
|
| 60 |
+
ext = Path(file_path).suffix.lower()
|
| 61 |
+
|
| 62 |
+
if ext in VIDEO_EXTENSIONS:
|
| 63 |
+
return 'video'
|
| 64 |
+
elif ext in IMAGE_EXTENSIONS:
|
| 65 |
+
return 'image'
|
| 66 |
+
else:
|
| 67 |
+
print(f" Unknown extension {ext}, treating as video")
|
| 68 |
+
return 'video'
|
| 69 |
+
|
| 70 |
+
def call_gpt5_with_retry(prompt, media_path, attempt_num=1):
|
| 71 |
+
media_type = determine_media_type(media_path)
|
| 72 |
+
|
| 73 |
+
if not os.path.exists(media_path):
|
| 74 |
+
print(f" Warning: File {media_path} not found")
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
for retry in range(MAX_RETRY):
|
| 78 |
+
try:
|
| 79 |
+
print(f" Attempt {attempt_num}.{retry + 1}: Processing {media_type}...")
|
| 80 |
+
|
| 81 |
+
if media_type == 'video':
|
| 82 |
+
frames = process_video(media_path)
|
| 83 |
+
if not frames:
|
| 84 |
+
print(f" No frames extracted from {media_path}")
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
content = [
|
| 88 |
+
{"type": "input_text", "text": prompt},
|
| 89 |
+
*[
|
| 90 |
+
{
|
| 91 |
+
"type": "input_image",
|
| 92 |
+
"image_url": f"data:image/jpeg;base64,{frame}"
|
| 93 |
+
}
|
| 94 |
+
for frame in frames
|
| 95 |
+
]
|
| 96 |
+
]
|
| 97 |
+
else:
|
| 98 |
+
base64_image = encode_image_to_base64(media_path)
|
| 99 |
+
if not base64_image:
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
content = [
|
| 103 |
+
{"type": "input_text", "text": prompt},
|
| 104 |
+
{
|
| 105 |
+
"type": "input_image",
|
| 106 |
+
"image_url": f"data:image/jpeg;base64,{base64_image}"
|
| 107 |
+
}
|
| 108 |
+
]
|
| 109 |
+
|
| 110 |
+
response = client.responses.create(
|
| 111 |
+
model=MODEL_NAME,
|
| 112 |
+
reasoning={"effort": REASONING_EFFORT},
|
| 113 |
+
input=[{
|
| 114 |
+
"role": "user",
|
| 115 |
+
"content": content
|
| 116 |
+
}]
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
return response.output_text
|
| 120 |
+
|
| 121 |
+
except Exception as e:
|
| 122 |
+
print(f" Error on attempt {retry + 1}: {str(e)}")
|
| 123 |
+
if retry < MAX_RETRY - 1:
|
| 124 |
+
print(f" Retrying in {SLEEP_BETWEEN_RETRY} seconds...")
|
| 125 |
+
time.sleep(SLEEP_BETWEEN_RETRY)
|
| 126 |
+
else:
|
| 127 |
+
print(f" Failed after {MAX_RETRY} attempts")
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
def extract_prompt_and_truth(conversations):
|
| 133 |
+
prompt = None
|
| 134 |
+
ground_truth = None
|
| 135 |
+
|
| 136 |
+
if conversations and len(conversations) > 0 and conversations[0]["from"] == "human":
|
| 137 |
+
full_value = conversations[0]["value"]
|
| 138 |
+
prompt = full_value.replace("<video>", "").replace("<image>", "").strip()
|
| 139 |
+
|
| 140 |
+
if len(conversations) >= 2 and conversations[1]["from"] == "gpt":
|
| 141 |
+
ground_truth = conversations[1]["value"]
|
| 142 |
+
|
| 143 |
+
return prompt, ground_truth
|
| 144 |
+
|
| 145 |
+
def main():
|
| 146 |
+
|
| 147 |
+
if not os.path.exists(INPUT_FILE):
|
| 148 |
+
print(f"Error: Input file '{INPUT_FILE}' not found")
|
| 149 |
+
return
|
| 150 |
+
|
| 151 |
+
with open(INPUT_FILE, 'r', encoding='utf-8') as f:
|
| 152 |
+
data = json.load(f)
|
| 153 |
+
|
| 154 |
+
print(f"Loaded {len(data)} items from {INPUT_FILE}")
|
| 155 |
+
|
| 156 |
+
items_to_process = data[:TEST_ITEMS] if TEST_MODE else data
|
| 157 |
+
results = []
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
for idx, item in enumerate(items_to_process, 1):
|
| 161 |
+
item_id = item.get("id")
|
| 162 |
+
media_path = item.get("video") or item.get("image")
|
| 163 |
+
conversations = item.get("conversations", [])
|
| 164 |
+
|
| 165 |
+
print(f"\n[{idx}/{len(items_to_process)}] Processing ID: {item_id}")
|
| 166 |
+
print(f" Media: {media_path}")
|
| 167 |
+
|
| 168 |
+
if not media_path or not conversations:
|
| 169 |
+
print(f"Skipping: missing media path or conversations")
|
| 170 |
+
continue
|
| 171 |
+
|
| 172 |
+
prompt, ground_truth = extract_prompt_and_truth(conversations)
|
| 173 |
+
|
| 174 |
+
if not prompt:
|
| 175 |
+
print(f"Skipping: no prompt found")
|
| 176 |
+
continue
|
| 177 |
+
|
| 178 |
+
response1 = call_gpt5_with_retry(prompt, media_path, attempt_num=1)
|
| 179 |
+
|
| 180 |
+
response2 = call_gpt5_with_retry(prompt, media_path, attempt_num=2)
|
| 181 |
+
|
| 182 |
+
result = {
|
| 183 |
+
"id": item_id,
|
| 184 |
+
"media_path": media_path,
|
| 185 |
+
"response_1": response1,
|
| 186 |
+
"response_2": response2,
|
| 187 |
+
"ground_truth": ground_truth
|
| 188 |
+
}
|
| 189 |
+
results.append(result)
|
| 190 |
+
|
| 191 |
+
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
|
| 192 |
+
json.dump(results, f, ensure_ascii=False, indent=2)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
main()
|
data/with_prompt/level3/FilmStim.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/with_prompt/level3/MUStARD.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/without_prompt/level1/CMU-MOSI.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/without_prompt/level1/EmoSet.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/without_prompt/level1/FMSA-SC.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/without_prompt/level1/MER2023.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/without_prompt/level1/Memotion.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/without_prompt/level1/RAVDSS_song.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|