Using the openai API as the judge model, write the code for a poetry translation…
- User
Using the openai API as the judge model, write the code for a poetry translation benchmark. Then explain what you came with.
Assistant
Using the openai API as the judge model, write the code for a poetry translation benchmark. Then explain what you came with.
Here's an example code for a poetry translation benchmark using the OpenAI API as a judge:
import openai
import json
from typing import List, Dict
import numpy as np
from tqdm import tqdm
class PoetryTranslationBenchmark:
def __init__(self, api_key: str):
openai.api_key = api_key
self.judge_prompt = """
You are a poetry expert and translator. Evaluate the quality of this poetry translation
based on the following criteria:
1. Semantic accuracy (0-10): How well the meaning is preserved
2. Poetic elements (0-10): Preservation of rhythm, rhyme, and literary devices
3. Cultural nuance (0-10): Retention of cultural context and references
4. Emotional impact (0-10): How well the emotional essence is conveyed
Source poem:
{source}
Translation:
{translation}
Provide your evaluation as a JSON object with these scores and a brief explanation.
"""
def evaluate_translation(self, source_poem: str, translation: str) -> Dict:
try:
prompt = self.judge_prompt.format(
source=source_poem,
translation=translation
)
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a poetry translation expert."},
{"role": "user", "content": prompt}
],
temperature=0.3
)
evaluation = json.loads(response.choices[0].message.content)
return evaluation
except Exception as e:
print(f"Error during evaluation: {e}")
return None
def run_benchmark(self, test_set: List[Dict]) -> Dict:
"""
test_set should be a list of dictionaries with format:
{
'source': source_poem,
'reference': reference_translation,
'system_translation': system_translation
}
"""
results = []
for item in tqdm(test_set):
# Evaluate system translation
system_eval = self.evaluate_translation(
item['source'],
item['system_translation']
)
# Evaluate reference translation
reference_eval = self.evaluate_translation(
item['source'],
item['reference']
)
if system_eval and reference_eval:
results.append({
'source': item['source'],
'system_translation': item['system_translation'],
'reference': item['reference'],
'system_scores': system_eval,
'reference_scores': reference_eval
})
# Calculate aggregate metrics
aggregate_metrics = self.calculate_aggregate_metrics(results)
return {
'detailed_results': results,
'aggregate_metrics': aggregate_metrics
}
def calculate_aggregate_metrics(self, results: List[Dict]) -> Dict:
system_scores = {
'semantic_accuracy': [],
'poetic_elements': [],
'cultural_nuance': [],
'emotional_impact': []
}
reference_scores = {
'semantic_accuracy': [],
'poetic_elements': [],
'cultural_nuance': [],
'emotional_impact': []
}
for result in results:
for key in system_scores.keys():
system_scores[key].append(result['system_scores'][key])
reference_scores[key].append(result['reference_scores'][key])
# Calculate means and standard deviations
metrics = {}
for key in system_scores.keys():
metrics[f'system_{key}_mean'] = np.mean(system_scores[key])
metrics[f'system_{key}_std'] = np.std(system_scores[key])
metrics[f'reference_{key}_mean'] = np.mean(reference_scores[key])
metrics[f'reference_{key}_std'] = np.std(reference_scores[key])
return metrics
# Example usage
if __name__ == "__main__":
test_set = [
{
'source': """
Nel mezzo del cammin di nostra vita
mi ritrovai per una selva oscura,
ché la diritta via era smarrita.
""",
'reference': """
Midway upon the journey of our life
I found myself within a forest dark,
For the straightforward pathway had been lost.
""",
'system_translation': """
In the middle of life's journey
I found myself in a dark wood,
Where the right path was lost.
"""
}
# Add more test cases...
]
benchmark = PoetryTranslationBenchmark('your-api-key')
results = benchmark.run_benchmark(test_set)
print(json.dumps(results, indent=2))
This code implements a poetry translation benchmark system that uses the OpenAI API (GPT-4) as a judge. Here's an explanation of the key components:
PoetryTranslationBenchmark Class:
evaluate_translation Method:
run_benchmark Method:
calculate_aggregate_metrics Method:
Key Features:
To use this benchmark:
The benchmark can be extended by:
Remember to handle API rate limits and costs appropriately when using this benchmark with large test sets.