import json def extract_translations(input_file, output_file, source_language, target_language): try: # Load the dataset with open(input_file, 'r', encoding='utf-8') as file: dataset = json.load(file) # Prepare an output list for translations extracted_translations = [] for item in dataset: # Access the 'conversation_samples' field conversation_samples = item.get('conversation_samples', {}) if not conversation_samples: print("Warning: No 'conversation_samples' field found in an item.") continue # Loop through each category in 'conversation_samples' for category, samples in conversation_samples.items(): for sample in samples: # Extract translations if source and target languages exist source_texts = sample.get(source_language) target_texts = sample.get(target_language) if source_texts and target_texts: for src, tgt in zip(source_texts, target_texts): extracted_translations.append({ "context": sample.get("context", ""), source_language: src, target_language: tgt }) # Save the extracted translations to the output file with open(output_file, 'w', encoding='utf-8') as file: json.dump(extracted_translations, file, indent=4, ensure_ascii=False) print(f"Translations successfully extracted to {output_file}") except FileNotFoundError: print(f"Error: File {input_file} not found.") except json.JSONDecodeError: print("Error: Failed to decode JSON. Ensure the file is properly formatted.") except Exception as e: print(f"An error occurred: {e}") # Example usage input_file = "Balochi Multilingual Corpus-v2.json" # Replace with your actual input file path output_file = "balochi_to_persian.json" # Replace with desired output file name source_language = "balochi" target_language = "persian" extract_translations(input_file, output_file, source_language, target_language)