File size: 2,401 Bytes
cfc20e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)