237 lines
24 KiB
Python
237 lines
24 KiB
Python
import yaml
|
|
import sys
|
|
import re
|
|
|
|
# File Paths
|
|
SOURCE_FILE = r"C:\Users\joao.goncalves\Desktop\zabbix-itguys\templates_gold\windows_active_agent\template_windows_gold_ptbr.yaml"
|
|
TARGET_FILE = r"C:\Users\joao.goncalves\Desktop\zabbix-itguys\templates_gold\windows_active_agent\template_windows_gold_ptbr.yaml" # Overwrite
|
|
|
|
# Translations Dictionary
|
|
TRANSLATIONS = {
|
|
# Items & General Descriptions
|
|
'The agent always returns "1" for this item. May be used in combination with `nodata()` for the availability check.': 'O agente sempre retorna "1" para este item. Pode ser usado com `nodata()` para verificação de disponibilidade.',
|
|
'Cache Bytes is the sum of the Memory\\System Cache Resident Bytes, Memory\\System Driver Resident Bytes, Memory\\System Code Resident Bytes, and Memory\\Pool Paged Resident Bytes counters. This counter displays the last observed value only; it is not an average.': 'Cache Bytes é a soma dos bytes residentes do Cache do Sistema, Drivers, Código e Pool Paged. Mostra apenas o último valor observado, não a média.',
|
|
'This indicates the number of page table entries not currently in use by the system. If the number is less than 5,000, there may be a memory leak or you running out of memory.': 'Indica o número de entradas da tabela de páginas não utilizadas. Se menor que 5.000, pode haver vazamento de memória.',
|
|
'Page Faults/sec is the average number of pages faulted per second. It is measured in number of pages faulted per second because only one page is faulted in each fault operation, hence this is also equal to the number of page fault operations. This counter includes both hard faults (those that require disk access) and soft faults (where the faulted page is found elsewhere in physical memory.) Most processors can handle large numbers of soft faults without significant consequence. However, hard faults, which require disk access, can cause significant delays.': 'Page Faults/seg é a média de falhas de página por segundo. Inclui falhas hard (disco) e soft (memória). Falhas hard causam atrasos significativos.',
|
|
'This measures the rate at which pages are read from or written to disk to resolve hard page faults.': 'Mede a taxa de leitura/escrita de páginas no disco para resolver hard faults.',
|
|
'If the value is greater than 1,000, as a result of excessive paging, there may be a memory leak.': 'Se > 1.000, indica paginação excessiva e possível vazamento de memória.',
|
|
'The Memory Pages/sec in the last 5 minutes exceeds `{$MEM.PAGE_SEC.CRIT.MAX}`. If the value is greater than 1,000, as a result of excessive paging, there may be a memory leak.': 'A taxa de Pages/sec excedeu `{$MEM.PAGE_SEC.CRIT.MAX}` nos últimos 5m. Se > 1.000, indica possível vazamento de memória.',
|
|
'This measures the size, in bytes, of the non-paged pool. This is an area of system memory for objects that cannot be written to disk but instead must remain in physical memory as long as they are allocated.': 'Mede o tamanho (bytes) do pool não paginado (memória física obrigatória).',
|
|
'There is a possible memory leak if the value is greater than 175MB (or 100MB with the /3GB switch). Consequently, Event ID 2019 is recorded in the system event log.': 'Possível vazamento se > 175MB (Event ID 2019).',
|
|
'The used space of swap volume/file in percent.': 'Espaço usado do arquivo de swap em porcentagem.',
|
|
'Processor DPC time is the time that a single processor spent receiving and servicing deferred procedure calls (DPCs). DPCs are interrupts that run at a lower priority than standard interrupts. `% DPC Time` is a component of `% Privileged Time` because DPCs are executed in privileged mode. If a high `% DPC Time` is sustained, there may be a processor bottleneck or an application or hardware related issue that can significantly diminish overall system performance.': 'Tempo de DPC é o tempo gasto em chamadas de procedimento diferido (DPCs). Alto uso constante indica gargalo de CPU, driver ou hardware.',
|
|
'The processor information `% Interrupt Time` counter indicates how much time the processor spends handling hardware interrupts during sample intervals. It reflects the activity of devices like the system clock, mouse, disk drivers, and network cards. A value above 20% suggests possible hardware issues.': 'Tempo de Interrupção indica tempo da CPU tratando interrupções de hardware (mouse, disco, rede). Acima de 20% sugere problemas de hardware.',
|
|
'The CPU Interrupt Time in the last 5 minutes exceeds `{$CPU.INTERRUPT.CRIT.MAX}`%.': 'O Tempo de Interrupção da CPU nos últimos 5 minutos excede `{$CPU.INTERRUPT.CRIT.MAX}`%.',
|
|
'The processor information `% Privileged Time` counter shows the percent of time that the processor is spent executing in Kernel (or Privileged) mode. Privileged mode includes services interrupts inside Interrupt Service Routines (ISRs), executing Deferred Procedure Calls (DPCs), Device Driver calls and other kernel-mode functions of the Windows Operating System.': 'Tempo Privilegiado mostra % de tempo da CPU em modo Kernel (Drivers, DPCs, ISRs).',
|
|
'The CPU: Tempo Privilegiado (Kernel) in the last 5 minutes exceeds {$CPU.PRIV.CRIT.MAX}%.': 'O Tempo Privilegiado (Kernel) da CPU excede {$CPU.PRIV.CRIT.MAX}% nos últimos 5m.',
|
|
'The processor information `% User Time` counter shows the percent of time that the processor(s) is spent executing in User mode.': 'Tempo de Usuário mostra % de tempo da CPU em modo Usuário (Aplicações).',
|
|
'Context Switches/sec is the combined rate at which all processors on the computer are switched from one thread to another.': 'Context Switches/sec é a taxa de troca de threads nos processadores.',
|
|
'Context switches occur when a running thread voluntarily relinquishes the processor, is preempted by a higher priority ready thread, or switches between user-mode and privileged (kernel) mode to use an Executive or subsystem service.': 'Ocorre quando threads cedem lugar a outras ou alternam modos.',
|
|
'It is the sum of Thread\\Context Switches/sec for all threads running on all processors in the computer and is measured in numbers of switches.': 'É a soma de trocas de contexto para todas as threads.',
|
|
'There are context switch counters on the System and Thread objects. This counter displays the difference between the values observed in the last two samples, divided by the duration of the sample interval.': 'Mostra a diferença entre amostras dividida pelo intervalo.',
|
|
'The Processor Queue Length shows the number of threads that are observed as delayed in the processor Ready Queue and are waiting to be executed.': 'Processor Queue Length mostra threads aguardando execução na fila da CPU.',
|
|
'The number of threads used by all running processes.': 'Número total de threads usadas por todos os processos.',
|
|
'The number of processes.': 'Número total de processos em execução.',
|
|
'CPU: Utilização Total expressed in %.': 'Utilização Total da CPU expressa em %.',
|
|
'The host name of the system.': 'Nome do host do sistema.',
|
|
'The name of the system has changed. Acknowledge to close the problem manually.': 'O nome do sistema mudou. Reconheça para fechar o problema manualmente.',
|
|
'The local system time of the host.': 'Hora local do sistema.',
|
|
'The architecture of the operating system.': 'Arquitetura do sistema operacional.',
|
|
'The description of the operating system has changed. Possible reasons are that the system has been updated or replaced. Acknowledge to close the problem manually.': 'A descrição do SO mudou. O sistema pode ter sido atualizado. Reconheça para fechar.',
|
|
'The free space of the swap volume/file expressed in bytes.': 'Espaço livre do arquivo de swap em bytes.',
|
|
'The free space of the swap volume/file expressed in %.': 'Espaço livre do arquivo de swap em %.',
|
|
'The total space of the swap volume/file expressed in bytes.': 'Tamanho total do arquivo de swap em bytes.',
|
|
'Sistema: Descrição of the host.': 'Descrição do sistema operacional do host.',
|
|
'The system uptime expressed in the following format: "N days, hh:mm:ss".': 'Tempo de atividade do sistema no formato: "N dias, hh:mm:ss".',
|
|
'The `vfs.fs.get` key acquires raw information set about the filesystems. Later to be extracted by preprocessing in dependent items.': 'A chave `vfs.fs.get` adquire informações brutas sobre sistemas de arquivos para pré-processamento.',
|
|
'Memória: Total expressed in bytes.': 'Memória total expressa em bytes.',
|
|
'Memória: Usada in bytes.': 'Memória usada em bytes.',
|
|
'Memória: % de Utilização in %.': 'Porcentagem de memória utilizada.',
|
|
'Raw data of `win32_networkadapter.`': 'Dados brutos de `win32_networkadapter`.',
|
|
'The number of logical processors available on the computer.': 'Número de processadores lógicos disponíveis.',
|
|
'Used for monitoring the availability status of the agent.': 'Usado para monitorar a disponibilidade do agente.',
|
|
|
|
# Discovery Rules & Prototypes
|
|
'Discovery of installed network interfaces.': 'Descoberta de interfaces de rede instaladas.',
|
|
'The number of incoming packets dropped on the network interface.': 'Número de pacotes de entrada descartados na interface.',
|
|
'The number of incoming packets with errors on the network interface.': 'Número de pacotes de entrada com erros na interface.',
|
|
'Incoming traffic on the network interface.': 'Tráfego de entrada na interface de rede.',
|
|
'The number of outgoing packets dropped on the network interface.': 'Número de pacotes de saída descartados na interface.',
|
|
'The number of outgoing packets with errors on the network interface.': 'Número de pacotes de saída com erros na interface.',
|
|
'Outgoing traffic on the network interface.': 'Tráfego de saída na interface de rede.',
|
|
'Estimated bandwidth of the network interface if any.': 'Largura de banda estimada da interface de rede.',
|
|
'The operational status of the network interface.': 'Status operacional da interface de rede.',
|
|
'This trigger expression works as follows:': 'Esta trigger funciona assim:',
|
|
'1. It can be triggered if the operations status is down.': '1. Dispara se o status operacional for Down.',
|
|
'2. `{$IFCONTROL:"{#IFNAME}"}=1` - a user can redefine the context macro to "0", marking this interface as not important.': '2. `{$IFCONTROL:"{#IFNAME}"}=1` - defina a macro como "0" para ignorar esta interface.',
|
|
'Used for the discovery of Windows services of different types as defined in the template\'s macros.': 'Descoberta de serviços Windows baseada nas macros do template.',
|
|
'The service has a state other than "Running" for the last three times.': 'O serviço não está no estado "Running" nas últimas 3 verificações.',
|
|
'Discovery of filesystems of different types.': 'Descoberta de sistemas de arquivos.',
|
|
'Available storage space expressed in bytes.': 'Espaço disponível em bytes.',
|
|
'Calculated as the percentage of currently used space compared to the maximum available space.': 'Calculado como porcentagem de espaço usado em relação ao total.',
|
|
'The volume\'s space usage exceeds the `{$VFS.FS.PUSED.MAX.CRIT:"{#FSNAME}"}%` limit.': 'O uso do volume excede o limite crítico `{$VFS.FS.PUSED.MAX.CRIT:"{#FSNAME}"}%`.',
|
|
'The trigger expression is based on the current used and maximum available spaces.': 'A trigger baseia-se no espaço usado e máximo disponível.',
|
|
'Event name represents the total volume space, which can differ from the maximum available space, depending on the filesystem type.': 'O nome do evento mostra o espaço total, que pode diferir do disponível dependendo do sistema de arquivos.',
|
|
'The volume\'s space usage exceeds the `{$VFS.FS.PUSED.MAX.WARN:"{#FSNAME}"}%` limit.': 'O uso do volume excede o limite de aviso `{$VFS.FS.PUSED.MAX.WARN:"{#FSNAME}"}%`.',
|
|
'Total space expressed in bytes.': 'Espaço total em bytes.',
|
|
'Used storage expressed in bytes.': 'Espaço usado em bytes.',
|
|
'Intermediate data of `{#FSNAME}` filesystem.': 'Dados intermediários do sistema de arquivos `{#FSNAME}`.',
|
|
|
|
# Macros Section
|
|
'Timeout after which agent is considered unavailable. Works only for agents reachable from Zabbix server/proxy (passive mode).': 'Timeout para considerar agente indisponível (apenas modo passivo).',
|
|
'The critical threshold of the % Interrupt Time counter.': 'Limiar crítico para % Interrupt Time.',
|
|
'The threshold of the % Privileged Time counter.': 'Limiar crítico para % Privileged Time.',
|
|
'The threshold of the Processor Queue Length counter.': 'Limiar para Processor Queue Length.',
|
|
'The critical threshold of the CPU: Utilização Total expressed in %.': 'Limiar crítico para Utilização Total da CPU (%).',
|
|
'Warning threshold of error packet rate. Can be used with interface name as context.': 'Limiar de aviso para taxa de erros de pacote.',
|
|
'Used as a threshold in the interface utilization trigger.': 'Limiar para trigger de utilização de interface.',
|
|
'Macro for the interface operational state for the "link down" trigger. Can be used with interface name as context.': 'Macro para estado operacional (trigger link down). Use 0 para desativar.',
|
|
'The warning threshold of the Memory Pages/sec counter.': 'Limiar de aviso para Memory Pages/sec.',
|
|
'The warning threshold of the Free System Page Table Entries counter.': 'Limiar de aviso para Free System Page Table Entries.',
|
|
'The warning threshold of the Memory util item.': 'Limiar de aviso para uso de memória.',
|
|
'Used in Network interface discovery. Can be overridden on the host or linked template level.': 'Usado na descoberta de interface de rede. Pode ser sobrescrito.',
|
|
'Used in Service discovery. Can be overridden on the host or linked template level.': 'Usado na descoberta de serviços. Pode ser sobrescrito.',
|
|
'The warning threshold of the minimum free swap.': 'Limiar de aviso para swap livre mínimo.',
|
|
'The upper threshold for difference of system time.': 'Limiar superior para diferença de tempo do sistema.',
|
|
'The lower threshold for difference of system time. Used in recovery expression to avoid trigger flapping.': 'Limiar inferior para diferença de tempo (recuperação).',
|
|
'Used in physical disk discovery. Can be overridden on the host or linked template level.': 'Usado na descoberta de disco físico.',
|
|
'Disk read average response time (in s) before the trigger fires.': 'Tempo médio de leitura (s) para disparar trigger.',
|
|
'The warning threshold of disk time utilization in percent.': 'Limiar de aviso para utilização de disco (%).',
|
|
'Disk write average response time (in s) before the trigger fires.': 'Tempo médio de escrita (s) para disparar trigger.',
|
|
'Used in filesystem discovery. Can be overridden on the host or linked template level.': 'Usado na descoberta de sistema de arquivos.',
|
|
'The critical threshold of the filesystem utilization.': 'Limiar crítico de utilização do sistema de arquivos.',
|
|
'The warning threshold of the filesystem utilization.': 'Limiar de aviso de utilização do sistema de arquivos.',
|
|
'The CPU Queue Length in the last 5 minutes exceeds `{$CPU.QUEUE.CRIT.MAX}`. According to actual observations, PQL should not exceed the number of cores * 2. To fine-tune the conditions, use the macro `{$CPU.QUEUE.CRIT.MAX }`.': 'A fila da CPU excedeu `{$CPU.QUEUE.CRIT.MAX}` nos últimos 5m. Idealmente PQL < Cores * 2.',
|
|
'This trigger is ignored, if there is no swap configured': 'Esta trigger é ignorada se não houver swap configurado.',
|
|
|
|
# Missing Discovery Prototypes (Added in V2)
|
|
'{#DEVNAME}: Disk utilization by idle time': '{#DEVNAME}: Utilização de disco por tempo ocioso',
|
|
'{#DEVNAME}: Average disk read queue length': '{#DEVNAME}: Tamanho médio da fila de leitura',
|
|
'{#DEVNAME}: Disk read request avg waiting time': '{#DEVNAME}: Tempo médio de espera de leitura',
|
|
'{#DEVNAME}: Disk write request avg waiting time': '{#DEVNAME}: Tempo médio de espera de escrita',
|
|
'{#DEVNAME}: Average disk write queue length': '{#DEVNAME}: Tamanho médio da fila de escrita',
|
|
'{#DEVNAME}: Disk average queue size (avgqu-sz)': '{#DEVNAME}: Tamanho médio da fila de disco (avgqu-sz)',
|
|
'{#DEVNAME}: Disk read rate': '{#DEVNAME}: Taxa de leitura de disco',
|
|
'{#DEVNAME}: Disk write rate': '{#DEVNAME}: Taxa de escrita de disco',
|
|
'State of service "{#SERVICE.NAME}" ({#SERVICE.DISPLAYNAME})': 'Estado do serviço "{#SERVICE.NAME}" ({#SERVICE.DISPLAYNAME})',
|
|
'FS [{#FSLABEL}({#FSNAME})]: Space: Available': 'FS [{#FSLABEL}({#FSNAME})]: Espaço: Disponível',
|
|
'FS [{#FSLABEL}({#FSNAME})]: Space: Used, in %': 'FS [{#FSLABEL}({#FSNAME})]: Espaço: Usado, em %',
|
|
'FS [{#FSLABEL}({#FSNAME})]: Space: Total': 'FS [{#FSLABEL}({#FSNAME})]: Espaço: Total',
|
|
'FS [{#FSLABEL}({#FSNAME})]: Space: Used': 'FS [{#FSLABEL}({#FSNAME})]: Espaço: Usado',
|
|
'FS [{#FSLABEL}({#FSNAME})]: Get data': 'FS [{#FSLABEL}({#FSNAME})]: Obter dados',
|
|
'Windows: {#DEVNAME}: Disk is overloaded': 'Windows: {#DEVNAME}: Disco sobrecarregado',
|
|
'Windows: {#DEVNAME}: Disk read request responses are too high': 'Windows: {#DEVNAME}: Tempo de resposta de leitura muito alto',
|
|
'Windows: {#DEVNAME}: Disk write request responses are too high': 'Windows: {#DEVNAME}: Tempo de resposta de escrita muito alto',
|
|
'Windows: "{#SERVICE.NAME}" ({#SERVICE.DISPLAYNAME}) is not running': 'Windows: "{#SERVICE.NAME}" ({#SERVICE.DISPLAYNAME}) não está rodando',
|
|
'Windows: FS [{#FSLABEL}({#FSNAME})]: Space is critically low': 'Windows: FS [{#FSLABEL}({#FSNAME})]: Espaço criticamente baixo',
|
|
'Windows: FS [{#FSLABEL}({#FSNAME})]: Space is low': 'Windows: FS [{#FSLABEL}({#FSNAME})]: Espaço baixo',
|
|
|
|
# Trigger Descriptions
|
|
'The volume\'s space usage exceeds the `{$VFS.FS.PUSED.MAX.CRIT:"{#FSNAME}"}%` limit.': 'O uso de espaço do volume excede o limite crítico de `{$VFS.FS.PUSED.MAX.CRIT:"{#FSNAME}"}%`.',
|
|
'The volume\'s space usage exceeds the `{$VFS.FS.PUSED.MAX.WARN:"{#FSNAME}"}%` limit.': 'O uso de espaço do volume excede o limite de aviso de `{$VFS.FS.PUSED.MAX.WARN:"{#FSNAME}"}%`.',
|
|
|
|
# Remaining Triggers
|
|
'Windows: CPU: Tamanho da Fila (Queue Length) is too high': 'Windows: CPU: Tamanho da Fila (Queue Length) muito alto',
|
|
'Windows: CPU: Tamanho da Fila (Queue Length) is too high (over {$CPU.QUEUE.CRIT.MAX} for 5m)': 'Windows: CPU: Tamanho da Fila (Queue Length) muito alto (acima de {$CPU.QUEUE.CRIT.MAX} por 5m)',
|
|
'Windows: High swap space usage': 'Windows: Uso de Swap Elevado',
|
|
'Windows: High swap space usage (less than {$SWAP.PFREE.MIN.WARN}% free)': 'Windows: Uso de Swap Elevado (menos de {$SWAP.PFREE.MIN.WARN}% livre)',
|
|
|
|
# Network Trigger Descriptions (Arthur Style)
|
|
'The utilization of the network interface is close to its estimated maximum bandwidth.':
|
|
'⚠️ Uso de banda elevado.\n\n📉 Impacto: A interface atingiu o limite de tráfego. O acesso ao servidor ficará lento e pacotes podem ser descartados.\n🛠️ Ação: 1. Identifique qual processo/usuário está consumindo banda. 2. Avalie necessidade de upgrade de link.',
|
|
|
|
'This Ethernet connection has transitioned down from its known maximum speed. This might be a sign of autonegotiation issues. Acknowledge to close the problem manually.':
|
|
'⚠️ A velocidade da interface caiu (Ex: 1Gb -> 100Mb).\n\n📉 Impacto: Lentidão na transferência de dados.\n🛠️ Ação: 1. Verifique a categoria do cabo (Cat5e/Cat6). 2. Verifique configurações de Duplex/Speed no switch e servidor.',
|
|
|
|
'It recovers when it is below 80% of the `{$IF.ERRORS.WARN:"{#IFNAME}"}` threshold.':
|
|
'⚠️ Erros de transmissão detectados.\n\n📉 Impacto: Perda de pacotes, retransmissões e lentidão.\n🛠️ Ação: 1. Substitua o cabo de rede. 2. Teste outra porta no switch.',
|
|
|
|
# Disk Trigger Descriptions (Arthur Style)
|
|
'The disk appears to be under heavy load.':
|
|
'⚠️ Disco operando perto da capacidade máxima.\n\n📉 Impacto: Lentidão geral no sistema, aplicações travando e demora para buscar arquivos.\n🛠️ Ação: 1. Verifique quais processos estão consumindo I/O (Resource Monitor). 2. Considere mover arquivos para outro disco ou upgrade para SSD.',
|
|
|
|
'This trigger might indicate the disk {#DEVNAME} saturation.':
|
|
'⚠️ Latência alta no disco (Lentidão).\n\n📉 Impacto: O sistema demora para ler/gravar dados. Bancos de dados e sistemas de arquivos serão afetados.\n🛠️ Ação: 1. Verifique saúde do disco (SMART/Event Log). 2. Verifique se há backup ou antivírus rodando no momento.',
|
|
|
|
# Event Names
|
|
'for 5m)': 'por 5m)',
|
|
|
|
# Discovery Rule Names
|
|
'Network interfaces discovery': 'Descoberta de interfaces de rede',
|
|
'Physical disks discovery': 'Descoberta de discos físicos',
|
|
'Windows services discovery': 'Descoberta de serviços Windows',
|
|
'Mounted filesystem discovery': 'Descoberta de sistemas de arquivos montados',
|
|
|
|
# Disk Graph Prototypes
|
|
'{#DEVNAME}: Disk average queue length': '{#DEVNAME}: Tamanho médio da fila de disco',
|
|
'{#DEVNAME}: Disk average waiting time': '{#DEVNAME}: Tempo médio de espera do disco',
|
|
'{#DEVNAME}: Disk read/write rates': '{#DEVNAME}: Taxas de leitura/escrita do disco',
|
|
'{#DEVNAME}: Disk utilization and queue': '{#DEVNAME}: Utilização e fila do disco',
|
|
|
|
# Disk Item Descriptions
|
|
'Rate of read operations on the disk.': 'Taxa de operações de leitura no disco.',
|
|
'Rate of write operations on the disk.': 'Taxa de operações de escrita no disco.',
|
|
'The disk is idle.': 'O disco está ocioso.',
|
|
|
|
# ValueMaps
|
|
'Disconnected': 'Desconectado',
|
|
'Connecting': 'Conectando',
|
|
'Connected': 'Conectado',
|
|
'Disconnecting': 'Desconectando',
|
|
'Hardware Not Present': 'Hardware Ausente',
|
|
'Hardware Disabled': 'Hardware Desabilitado',
|
|
'Hardware Malfunction': 'Falha de Hardware',
|
|
'Media Disconnected': 'Mídia Desconectada',
|
|
'Authenticating': 'Autenticando',
|
|
'Authentication Succeeded': 'Autenticação com Sucesso',
|
|
'Authentication Failed': 'Falha na Autenticação',
|
|
'Invalid Address': 'Endereço Inválido',
|
|
'Credentials Required': 'Credenciais Necessárias',
|
|
'Running': 'Em Execução',
|
|
'Paused': 'Pausado',
|
|
'Start pending': 'Início Pendente',
|
|
'Pause pending': 'Pausa Pendente',
|
|
'Continue pending': 'Continuação Pendente',
|
|
'Stop pending': 'Parada Pendente',
|
|
'Stopped': 'Parado',
|
|
'No such service': 'Serviço Inexistente',
|
|
'not available': 'indisponível',
|
|
'available': 'disponível',
|
|
'unknown': 'desconhecido',
|
|
# 'Up': 'Operante', # Skipping 'Up' as it might be too generic and replace things it shouldn't
|
|
}
|
|
|
|
def translate_yaml(file_path):
|
|
print(f"Loading {file_path}...")
|
|
try:
|
|
with open(file_path, 'r', encoding='utf-8') as f:
|
|
content = f.read()
|
|
except Exception as e:
|
|
print(f"Error reading file: {e}")
|
|
return
|
|
|
|
# Simple string replacement for safety and retaining structure
|
|
# This avoids YAML re-formating issues (like flow style vs block style)
|
|
count = 0
|
|
for eng, pt in TRANSLATIONS.items():
|
|
if eng in content:
|
|
# Check if it's actually in a valid context (basic check)
|
|
# We assume the English strings are unique enough
|
|
new_content = content.replace(eng, pt)
|
|
if new_content != content:
|
|
content = new_content
|
|
count += 1
|
|
# print(f"Translated: {eng[:30]}... -> {pt[:30]}...")
|
|
|
|
print(f"Applied {count} translations.")
|
|
|
|
try:
|
|
with open(file_path, 'w', encoding='utf-8') as f:
|
|
f.write(content)
|
|
print(f"Saved translated file to {file_path}")
|
|
except Exception as e:
|
|
print(f"Error writing file: {e}")
|
|
|
|
if __name__ == "__main__":
|
|
translate_yaml(TARGET_FILE)
|