Can you make the code gather all the nonenglish texts (should ignore numbers and other non letters ) into 1 text, Translate everything with 1 call and put back translated versions? It takes a lot time to go thru file by file.

import os
import json
import re
import time
from transformers import pipeline
import torch

class GameTranslator:
    def __init__(self):
        print("Initializing the translation model. Please wait...")
        self.model_name = "facebook/nllb-200-distilled-600M"
        
        # Check if CUDA is available and has enough memory
        if torch.cuda.is_available() and torch.cuda.get_device_properties(0).total_memory > 4 * 1024 * 1024 * 1024:
            self.device = 0
            print("Using GPU for translation")
        else:
            self.device = -1
            print("Using CPU for translation")
            
        self.translator = pipeline("translation", 
                                   model=self.model_name,
                                   device=self.device)
        
        self.lang_codes = {
            'en': 'eng_Latn', 'ja': 'jpn_Jpan', 'zh': 'zho_Hans',
            'ko': 'kor_Hang', 'ru': 'rus_Cyrl', 'fr': 'fra_Latn',
            'de': 'deu_Latn', 'es': 'spa_Latn', 'it': 'ita_Latn',
            'pt': 'por_Latn'
        }
        
    def translate_batch(self, texts, source_lang):
        if not texts:
            return []
        source_code = self.lang_codes.get(source_lang, 'eng_Latn')
        target_code = 'eng_Latn'
        
        try:
            results = self.translator(texts, 
                                      src_lang=source_code, 
                                      tgt_lang=target_code)
            # Handle the case where results may not be a list
            if isinstance(results, dict):
                results = [results]
            translations = [res['translation_text'] for res in results]
            return translations
        except Exception as e:
            print(f"Translation error: {e}")
            # Return original texts in case of error
            return texts

def detect_engine(folder_path):
    engines = set()
    
    for root, dirs, files in os.walk(folder_path):
        if any(f.endswith('.rpy') for f in files) and 'game' in dirs:
            engines.add('RenPy')
        
        if any(f in files for f in ['Game.rpgproject', 'RPG_RT.lmt', 'RPG_RT.ldb', 'RPG_RT.ini']):
            engines.add('RPGMaker')
        elif any(f.endswith('.json') and 'data' in dirs for f in files):
            engines.add('RPGMaker')
        
        if any(f.endswith('.wolf') for f in files) or 'Data.wolf' in files or 'Data' in dirs:
            engines.add('WolfRPG')
        
        if 'Runtime.json' in files or any(f.startswith('srpg_studio') for f in files):
            engines.add('SRPGStudio')
        
        if any(f.endswith('.ks') for f in files) or 'tyrano' in dirs:
            engines.add('TyranoBuilder')
        
        if 'ProjectSettings' in dirs and 'Assets' in dirs:
            engines.add('Unity')
        
        if 'Content' in dirs and 'Config' in dirs:
            engines.add('UnrealEngine')
        
        if any(f.endswith('.tscn') for f in files) or 'project.godot' in files:
            engines.add('Godot')
    
    return list(engines)

def process_file(filepath, translator, source_lang):
    start_time = time.time()
    
    try:
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()
    except UnicodeDecodeError:
        try:
            with open(filepath, 'r', encoding='shift-jis') as f:
                content = f.read()
        except:
            print(f"Skipping unreadable file: {filepath}")
            return False
    
    total_strings = 0
    translated_strings = 0
    
    if filepath.endswith('.rpy'):
        # Updated regex pattern to match text within quotes
        pattern = r'(\".*?\"|\'.*?\')'
        matches = list(re.finditer(pattern, content))
        texts = []
        spans = []
        for match in matches:
            text = match.group(1)
            if text.strip() and not text.startswith('#') and not text.startswith('python:'):
                total_strings += 1
                texts.append(text.strip('"\''))
                spans.append(match.span(1))
        # Batch translation
        translations = translator.translate_batch(texts, source_lang)
        # Replace original texts with translations
        new_content = content
        offset = 0
        for (start, end), translated in zip(spans, translations):
            translated_text = '"' + translated.replace('"', '\\"') + '"'
            new_content = new_content[:start+offset] + translated_text + new_content[end+offset:]
            offset += len(translated_text) - (end - start)
        translated_strings = total_strings
                        
    elif filepath.endswith('.json'):
        data = json.loads(content)
        
        texts_to_translate = []
        locations = []
        
        def collect_texts(d, path=[]):
            nonlocal total_strings
            if isinstance(d, dict):
                for key, value in d.items():
                    new_path = path + [key]
                    if isinstance(value, str) and not key.endswith(('Path', 'path', 'File', 'file', 'Image', 'image')):
                        if value.strip():
                            total_strings +=1
                            texts_to_translate.append(value)
                            locations.append(new_path)
                    elif isinstance(value, (dict, list)):
                        collect_texts(value, new_path)
            elif isinstance(d, list):
                for index, item in enumerate(d):
                    new_path = path + [index]
                    if isinstance(item, str):
                        if item.strip():
                            total_strings +=1
                            texts_to_translate.append(item)
                            locations.append(new_path)
                    elif isinstance(item, (dict, list)):
                        collect_texts(item, new_path)
                        
        collect_texts(data)
        
        # Batch translation
        translations = translator.translate_batch(texts_to_translate, source_lang)
        translated_strings = len(translations)
        
        def set_value_by_path(d, path, value):
            for key in path[:-1]:
                d = d[key]
            d[path[-1]] = value
            
        for path, translated in zip(locations, translations):
            set_value_by_path(data, path, translated)
            
        new_content = json.dumps(data, ensure_ascii=False, indent=2)
                
    elif filepath.endswith(('.txt', '.wolf')):
        # Updated regex pattern to match text within [TEXT] tags
        pattern = r'\[TEXT\](.*?)\[/TEXT\]'
        matches = list(re.finditer(pattern, content, re.DOTALL))
        texts = []
        spans = []
        for match in matches:
            text = match.group(1)
            total_strings += 1
            texts.append(text)
            spans.append(match.span(1))
        # Batch translation
        translations = translator.translate_batch(texts, source_lang)
        # Replace original texts with translations
        new_content = content
        offset = 0
        for (start, end), translated in zip(spans, translations):
            new_content = new_content[:start+offset] + translated + new_content[end+offset:]
            offset += len(translated) - (end - start)
        translated_strings = total_strings
                    
    else:
        print(f"Skipping unsupported file: {filepath}")
        return False
        
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(new_content)
        
    elapsed_time = time.time() - start_time
    print(f"Translated {translated_strings}/{total_strings} strings in '{filepath}' in {elapsed_time:.1f} seconds.")
    return elapsed_time

def main():
    translator = GameTranslator()
    folder_path = input("Enter the game folder path: ")
    source_lang = input("Enter the source language code (e.g., 'ja' for Japanese): ")
    
    engines = detect_engine(folder_path)
    if not engines:
        print("Could not detect game engine. Please check the folder.")
        return
    
    print(f"Detected engine: {engines[0]} - Starting translation...")
    
    files_to_translate = []
    for root, _, files in os.walk(folder_path):
        for file in files:
            if file == 'Animations.json':
                continue  # Skip Animations.json
    
            filepath = os.path.join(root, file)
    
            if engines[0] == "RenPy" and file.endswith('.rpy'):
                files_to_translate.append(filepath)
            elif engines[0] == "RPGMaker" and file.endswith('.json'):
                files_to_translate.append(filepath)
            elif engines[0] == "WolfRPG" and file.endswith(('.txt', '.wolf')):
                files_to_translate.append(filepath)
            elif engines[0] == "SRPGStudio" and file.endswith('.json'):
                files_to_translate.append(filepath)
                
    total_files = len(files_to_translate)
    print(f"Found {total_files} files to translate")
    
    total_time = 0
    for i, filepath in enumerate(files_to_translate, 1):
        file_time = process_file(filepath, translator, source_lang)
        if file_time:
            total_time += file_time
            avg_time = total_time / i
            remaining_time = avg_time * (total_files - i)
            print(f"Estimated time remaining: {remaining_time:.1f} seconds\n")
        
    print("Translation completed!")

if __name__ == "__main__":
    main()