Spaces:
Sleeping
Sleeping
File size: 11,396 Bytes
20dc456 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 |
import json
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import Dict, List, Optional
from claudette import Chat, models
@dataclass
class Context:
tibetan: str
english: str
commentaries: List[str]
sanskrit: Optional[str] = None
class AnalysisType(Enum):
SEMANTIC = "semantic"
TERM_GENERATION = "term_generation"
EVALUATION = "evaluation"
class BuddhistTermAnalyzer:
def __init__(self):
# Use Claude 3.5 Sonnet
self.model = models[1] # claude-3-5-sonnet
self.total_api_calls_cost = 0
self.token_usage = {}
# Initialize different chats for different analysis types
self.system_prompts = {
AnalysisType.SEMANTIC: """You are an expert in Buddhist terminology analysis with deep knowledge of Sanskrit and Tibetan.
Analyze the given term through a systematic philological approach.
You must ONLY respond with a valid JSON object, no other text.
Never include any explanatory text before or after the JSON.
Required JSON structure:
{
"sanskrit_analysis": {
"term": "string", # Sanskrit equivalent
"morphology": "string", # Morphological breakdown
"literal_meaning": "string", # Literal meaning in Sanskrit
"technical_usage": "string" # Technical usage in Sanskrit Buddhist literature
},
"tibetan_mapping": {
"term": "string", # Tibetan term
"morphology": "string", # Morphological breakdown of Tibetan
"translation_strategy": "string", # How Tibetan translates the Sanskrit
"semantic_extension": "string" # Any semantic changes or extensions in Tibetan
},
"commentary_insights": [
{
"source": "string", # Which commentary
"explanation": "string", # Key explanation
"technical_points": ["string"] # Technical clarifications
}
],
"english_renderings": [
{
"translation": "string",
"accuracy_score": number, # 1-10
"captures_sanskrit": boolean,
"captures_tibetan": boolean,
"notes": "string"
}
],
"semantic_synthesis": {
"core_meaning": "string", # Core meaning synthesized from all sources
"technical_usage": ["string"], # List of technical usages found in context
"connotative_aspects": ["string"] # Important connotations and implications
},
"usage_examples": [
{
"source_text": "string", # Original context
"usage_type": "string", # How term is used here
"commentary_explanation": "string" # What commentary says about this usage
}
]
}""",
AnalysisType.TERM_GENERATION: """You are an expert Buddhist translator.
You must ONLY respond with a valid JSON object, no other text.
Never include any explanatory text before or after the JSON.
Required JSON structure:
{
"academic": {
"terms": ["term1", "term2"],
"reasoning": "string"
},
"practitioner": {
"terms": ["term1", "term2"],
"reasoning": "string"
},
"general": {
"terms": ["term1", "term2"],
"reasoning": "string"
}
}""",
AnalysisType.EVALUATION: """You are an expert evaluator of Buddhist translations.
You must ONLY respond with a valid JSON object, no other text.
Never include any explanatory text before or after the JSON.
Required JSON structure:
{
"evaluations": {
"term": {
"technical_score": 0.0,
"cultural_score": 0.0,
"audience_score": 0.0,
"reasoning": "string"
}
}
}""",
}
# Initialize chats with respective system prompts
self.chats = {
analysis_type: Chat(self.model, sp=system_prompt)
for analysis_type, system_prompt in self.system_prompts.items()
}
def create_semantic_prompt(self, tibetan_term: str, contexts: List[Dict]) -> str:
return f"""
Analyze this Buddhist term following these steps:
Target Term: {tibetan_term}
Analysis Process:
1. First analyze the Sanskrit source:
- Identify the Sanskrit equivalent
- Break down its morphology
- Understand its literal and technical meanings
2. Map to Tibetan:
- Analyze how Tibetan translates the Sanskrit
- Note any semantic extensions or modifications
- Understand the translation strategy
3. Study the commentaries:
- Extract key explanations
- Note technical clarifications
- Identify special usages explained
4. Evaluate English translations:
- Compare against Sanskrit and Tibetan meanings
- Assess accuracy and completeness
- Note which aspects are captured/missed
5. Synthesize understanding:
- Combine insights from all sources
- Document technical usage patterns
- Note important connotations
Contexts:
{json.dumps(contexts, indent=2, ensure_ascii=False)}
Important:
- Base analysis strictly on provided contexts
- Use commentaries to resolve ambiguities
- Pay special attention to technical terms in commentaries
- Note when English translations diverge from Sanskrit/Tibetan
- Document specific usage examples from the context
Remember: Return ONLY the JSON object with no other text."""
def create_generation_prompt(
self, tibetan_term: str, semantic_analysis: Dict
) -> str:
return f"""
Respond ONLY with a JSON object containing translation candidates:
Term: {tibetan_term}
Semantic Analysis:
{json.dumps(semantic_analysis, indent=2, ensure_ascii=False)}
Remember: Return ONLY the JSON object with no other text."""
def create_evaluation_prompt(
self, tibetan_term: str, candidates: Dict, semantic_analysis: Dict
) -> str:
return f"""
Respond ONLY with a JSON object evaluating these candidates:
Term: {tibetan_term}
Candidates:
{json.dumps(candidates, indent=2, ensure_ascii=False)}
Semantic Analysis:
{json.dumps(semantic_analysis, indent=2, ensure_ascii=False)}
Remember: Return ONLY the JSON object with no other text."""
def _track_usage(self, analysis_type: AnalysisType, response):
cost = self.chats[analysis_type].cost
self.total_api_calls_cost += cost
self.token_usage[str(analysis_type)] = {
"token_usage": repr(response.usage),
"api_call_cost": cost,
}
def analyze_term(self, tibetan_term: str, contexts: List[Dict]) -> Dict:
"""Main analysis pipeline using cached prompts"""
# 1. Semantic Analysis with cache
semantic_prompt = self.create_semantic_prompt(tibetan_term, contexts)
semantic_response = self.chats[AnalysisType.SEMANTIC](semantic_prompt)
self._track_usage(AnalysisType.SEMANTIC, semantic_response)
semantic_analysis = json.loads(semantic_response.content[0].text)
# 2. Term Generation with cache
generation_prompt = self.create_generation_prompt(
tibetan_term, semantic_analysis
)
generation_response = self.chats[AnalysisType.TERM_GENERATION](
generation_prompt
)
self._track_usage(AnalysisType.TERM_GENERATION, generation_response)
semantic_analysis = json.loads(semantic_response.content[0].text)
candidates = json.loads(generation_response.content[0].text)
# 3. Evaluation with cache
evaluation_prompt = self.create_evaluation_prompt(
tibetan_term, candidates, semantic_analysis
)
evaluation_response = self.chats[AnalysisType.EVALUATION](evaluation_prompt)
self._track_usage(AnalysisType.EVALUATION, evaluation_response)
evaluations = json.loads(evaluation_response.content[0].text)
# Combine results
return self.format_results(
tibetan_term,
semantic_analysis,
candidates,
evaluations,
)
def format_results(
self,
tibetan_term: str,
semantic_analysis: Dict,
candidates: Dict,
evaluations: Dict,
) -> Dict:
"""Format the final results"""
return {
"tibetan_term": tibetan_term,
"recommendations": {
"Academic": {
"term": candidates["academic"]["terms"][0],
"reasoning": candidates["academic"]["reasoning"],
},
"Practitioner": {
"term": candidates["practitioner"]["terms"][0],
"reasoning": candidates["practitioner"]["reasoning"],
},
"General": {
"term": candidates["general"]["terms"][0],
"reasoning": candidates["general"]["reasoning"],
},
},
"analysis": semantic_analysis,
"evaluations": evaluations["evaluations"],
"total_api_calls_cost": self.total_api_calls_cost,
"token_usage": self.token_usage,
}
class TermStandardizationAgent:
def __init__(self):
self.analyzer = BuddhistTermAnalyzer()
def select_best_terms(self, tibetan_term: str, contexts: List[Dict]) -> Dict:
"""Main entry point for term standardization"""
results = self.analyzer.analyze_term(tibetan_term, contexts)
return results
# Example usage
def main():
from pathlib import Path
# Initialize agent
agent = TermStandardizationAgent()
# Test input
tibetan_term = "བྱང་ཆུབ་སེམས་"
contexts_fn = Path(__file__).parent / "data" / f"{tibetan_term}.json"
contexts = json.load(contexts_fn.open())
# Process term
results = agent.select_best_terms(tibetan_term, contexts)
date_time = datetime.now().strftime("%Y%m%d%H%M%S")
results_path = Path(__file__).parent / "results"
results_path.mkdir(exist_ok=True, parents=True)
result_fn = results_path / f"{tibetan_term}_{date_time}.json"
json.dump(results, result_fn.open("w"), indent=2, ensure_ascii=False)
print(f"Results saved to: {result_fn}")
if __name__ == "__main__":
main()
|