Quantcast
Channel: Zammad - Community - Latest posts
Viewing all articles
Browse latest Browse all 6827

Unable to translate certain strings from rails console

$
0
0

If anyone is interested this is my quick hack to solve this using the API

import csv
import requests
import logging
import os
import urllib3

# Suppress only the single InsecureRequestWarning from urllib3 needed
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


API_URL = 'https://example.com/api/v1/translations'
API_TOKEN = 'yourtoken'

headers = {
    'Authorization': f'Token token={API_TOKEN}',
    'Content-Type': 'application/json'
}


def fetch_all_translations():
    translations = []
    page = 1
    per_page = 50  # Adjust the per_page value based on the API's pagination settings
    while True:
        response = requests.get(f"{API_URL}?page={page}&per_page={per_page}", headers=headers, verify=False)
        if response.status_code == 200:
            data = response.json()
            translations.extend(data)
            if len(data) < per_page:
                break  # Exit the loop if we have fetched all pages
            page += 1
        else:
            logger.error(f"Failed to fetch translations. Status code: {response.status_code}, Response: {response.text}")
            break
    return translations

def find_translation_id(translations, locale, source):
    for translation in translations:
        if translation['locale'] == locale and translation['source'] == source:
            return translation['id']
    return None

def update_translation(translation_id, target):
    data = {
        'target': target
    }
    response = requests.put(f"{API_URL}/{translation_id}", json=data, headers=headers, verify=False)
    if response.status_code == 200:
        logger.info(f"Translation ID '{translation_id}' updated successfully.")
    else:
        logger.error(f"Failed to update translation ID '{translation_id}'. Status code: {response.status_code}, Response: {response.text}")

def add_translation(locale, source, target):
    data = {
        'locale': locale,
        'source': source,
        'target': target
    }
    response = requests.post(API_URL, json=data, headers=headers, verify=False)
    if response.status_code == 201:
        logger.info(f"Translation for '{source}' added successfully.")
    else:
        logger.error(f"Failed to add translation for '{source}'. Status code: {response.status_code}, Response: {response.text}")

def add_or_update_translations_from_csv(csv_file):
    translations = fetch_all_translations()
    with open(csv_file, 'r', encoding='utf-8') as file:
        reader = csv.DictReader(file, delimiter=';')
        for row in reader:
            try:
                locale = row['locale']
                source = row['source']
                target = row['target']
                translation_id = find_translation_id(translations, locale, source)
                if translation_id:
                    update_translation(translation_id, target)
                else:
                    add_translation(locale, source, target)
            except KeyError as e:
                logger.error(f"Missing key {e} in CSV row. Skipping this row.")
            except Exception as e:
                logger.error(f"An error occurred: {e}")

# Example usage
csv_file_path = 'test.csv'
add_or_update_translations_from_csv(csv_file_path)

Basically is loads the csv file which is set up as

locale;source;target
de-de;Customer;DSB
de-de;Organization;Schule

Looks case sensitively for the source in the whole translations then adds the target as translation for the defined locale

It’s hacky, but it works

Have fun!


Viewing all articles
Browse latest Browse all 6827

Trending Articles