| import requests |
| import time |
| import re |
|
|
| |
| API_URL = "https://mhdacm-mitikoman.hf.space/translate" |
|
|
| def translate_text(text): |
| """ارسال یک متن به API برای ترجمه""" |
| try: |
| response = requests.post( |
| API_URL, |
| json={"text": text, "src_lang": "eng_Latn", "tgt_lang": "pes_Arab"}, |
| headers={"Content-Type": "application/json"} |
| ) |
| |
| if response.status_code == 200: |
| return response.json()["translation"] |
| else: |
| print(f"خطا در ترجمه: {response.status_code}") |
| return text |
| except Exception as e: |
| print(f"خطا: {e}") |
| return text |
|
|
| def translate_srt_file(input_file, output_file): |
| """ترجمه فایل زیرنویس SRT""" |
| print(f"📖 در حال خواندن فایل: {input_file}") |
| |
| with open(input_file, 'r', encoding='utf-8') as f: |
| lines = f.readlines() |
| |
| translated_lines = [] |
| total_lines = len(lines) |
| |
| for i, line in enumerate(lines): |
| line = line.rstrip('\n') |
| |
| |
| if '-->' in line: |
| translated_lines.append(line) |
| |
| elif line.strip().isdigit(): |
| translated_lines.append(line) |
| |
| elif line.strip() == '': |
| translated_lines.append('') |
| |
| else: |
| print(f"🔄 در حال ترجمه خط {i+1}/{total_lines}: {line[:50]}...") |
| translated = translate_text(line) |
| translated_lines.append(translated) |
| time.sleep(0.5) |
| |
| |
| with open(output_file, 'w', encoding='utf-8') as f: |
| f.write('\n'.join(translated_lines)) |
| |
| print(f"✅ ترجمه کامل شد! فایل خروجی: {output_file}") |
|
|
| |
| if __name__ == "__main__": |
| |
| input_file = "sample.srt" |
| output_file = "sample_fa.srt" |
| |
| |
| translate_srt_file(input_file, output_file) |
| |
| |
| print("\n📝 نتیجه ترجمه:") |
| print("-" * 50) |
| with open(output_file, 'r', encoding='utf-8') as f: |
| print(f.read()) |