import xml.etree.ElementTree as ET import copy import re import gradio as gr from pathlib import Path import tempfile import os from datetime import datetime def swap_source_target_simple(content): """ Swaps source and target content in XLIFF string. Returns modified content and statistics. Args: content: XLIFF file content as string Returns: tuple: (modified_content, swap_count, copy_count, log_messages) """ trans_unit_pattern = r']*>.*?' swap_count = 0 copy_count = 0 log_messages = [] def process_trans_unit(match): nonlocal swap_count, copy_count, log_messages trans_unit = match.group(0) # Extract trans-unit id for logging id_match = re.search(r']*id="([^"]*)"', trans_unit) unit_id = id_match.group(1) if id_match else "unknown" # Extract source and target content source_pattern = r']*>(.*?)' target_pattern = r']*>(.*?)' source_match = re.search(source_pattern, trans_unit, re.DOTALL) target_match = re.search(target_pattern, trans_unit, re.DOTALL) if source_match: source_full = source_match.group(0) source_content = source_match.group(1) if target_match: target_full = target_match.group(0) target_content = target_match.group(1) # Check if target is empty if target_content.strip(): # Swap trans_unit = trans_unit.replace(source_full, f'{target_content}', 1) trans_unit = trans_unit.replace(target_full, f'{source_content}', 1) trans_unit = trans_unit.replace('', '', 1)[0].split('', 1) trans_unit = trans_unit.replace('', '', 1) swap_count += 1 log_messages.append(f"āœ“ Swapped: {unit_id}") else: # Copy source to target trans_unit = trans_unit.replace(target_full, f'{source_content}', 1) copy_count += 1 log_messages.append(f"→ Copied to target: {unit_id}") else: # No target element, add one trans_unit = trans_unit.replace('', f'{source_content}', 1) copy_count += 1 log_messages.append(f"+ Created target: {unit_id}") return trans_unit # Process all trans-units modified_content = re.sub(trans_unit_pattern, process_trans_unit, content, flags=re.DOTALL) return modified_content, swap_count, copy_count, log_messages def generate_output_filename(input_filepath): """ Generate output filename with format: inputname_output_DDMMYYYYHHMM.ext Args: input_filepath: Path to input file Returns: str: Generated output filename """ # Get the input file path object input_path = Path(input_filepath) # Extract filename without extension base_name = input_path.stem # Get file extension extension = input_path.suffix # Get current datetime in DDMMYYYYHHMM format now = datetime.now() datetime_str = now.strftime("%d%m%Y%H%M") # Construct output filename output_filename = f"{base_name}_output_{datetime_str}{extension}" return output_filename def process_xliff_file(input_file): """ Main function to process XLIFF file for Gradio interface. Args: input_file: File object from Gradio Returns: tuple: (output_file_path, statistics_text, log_text, success_message) """ try: if input_file is None: return None, "āŒ Error", "No file uploaded!", "" # Read input file with open(input_file.name, 'r', encoding='utf-8') as f: content = f.read() # Validate it's an XLIFF file if not ('xliff' in content.lower() and ' 50 else log_messages if len(log_messages) > 50: log_text = f"Showing last 50 of {len(log_messages)} operations:\n\n" + "\n".join(log_display) else: log_text = "\n".join(log_display) success_msg = f"āœ… **Success!** Processed {total_operations} translation units.\n\nšŸ“ **Output:** `{output_filename}`" return output_path, stats, log_text, success_msg except Exception as e: error_msg = f"Error processing file: {str(e)}" import traceback detailed_error = traceback.format_exc() return None, "āŒ Error", f"{error_msg}\n\nDetails:\n{detailed_error}", "" # Create Gradio Interface def create_interface(): with gr.Blocks(title="XLIFF Source/Target Swapper", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # šŸ”„ XLIFF Source/Target Swapper Upload your XLIFF file to swap `` and `` content in all translation units. ### Features: - āœ… Swaps source ↔ target when both have content - āœ… Copies source → target when target is empty - āœ… Preserves all XML formatting and nested tags - āœ… Maintains attributes and structure - āœ… Auto-generated filename with timestamp """) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### šŸ“¤ Upload") input_file = gr.File( label="Upload XLIFF File", file_types=[".xliff", ".xml"], type="filepath" ) process_btn = gr.Button("šŸ”„ Process File", variant="primary", size="lg") gr.Markdown(""" ### šŸ“– Instructions: 1. Upload your XLIFF file (.xliff or .xml) 2. Click "Process File" button 3. Review the statistics and log 4. Download the processed file ### šŸ“ Output Naming: Output files are named as: `filename_output_DDMMYYYYHHMM.xliff` Example: - Input: `translation.xliff` - Output: `translation_output_2501202415​30.xliff` """) with gr.Column(scale=1): gr.Markdown("### šŸ“„ Download") success_msg = gr.Markdown("") output_file = gr.File(label="Download Processed File") stats_output = gr.Markdown("") with gr.Row(): with gr.Column(): gr.Markdown("### šŸ“‹ Processing Log") log_output = gr.Textbox( label="Detailed Log", lines=15, max_lines=20, interactive=False, show_copy_button=True ) # Example files section gr.Markdown(""" --- ### šŸ’” Example XLIFF Structure **Before processing:** ```xml Hallo Welt Hello World ``` **After processing:** ```xml Hello World Hallo Welt ``` """) # Button click event process_btn.click( fn=process_xliff_file, inputs=[input_file], outputs=[output_file, stats_output, log_output, success_msg] ) return demo # Alternative: Simpler single-column layout def create_simple_interface(): with gr.Blocks(title="XLIFF Swapper", theme=gr.themes.Base()) as demo: gr.Markdown(""" # šŸ”„ XLIFF Source/Target Swapper Swap or copy content between source and target tags in XLIFF files. **Output Format:** `filename_output_DDMMYYYYHHMM.xliff` """) input_file = gr.File( label="šŸ“¤ Upload XLIFF File", file_types=[".xliff", ".xml"], type="filepath" ) process_btn = gr.Button("šŸ”„ Process File", variant="primary", size="lg") success_msg = gr.Markdown("") stats_output = gr.Markdown("") output_file = gr.File(label="šŸ“„ Download Processed File") log_output = gr.Textbox( label="šŸ“‹ Processing Log", lines=10, interactive=False, show_copy_button=True ) gr.Markdown(""" --- ### šŸ“ Filename Convention Your output file will be automatically named with timestamp: | Input File | Output File | |------------|-------------| | `document.xliff` | `document_output_2501202415​30.xliff` | | `translation.xml` | `translation_output_2501202415​45.xml` | Format: `DDMMYYYYHHMM` (Day-Month-Year-Hour-Minute) """) process_btn.click( fn=process_xliff_file, inputs=[input_file], outputs=[output_file, stats_output, log_output, success_msg] ) return demo # Test function for filename generation def test_filename_generation(): """Test the filename generation function""" test_files = [ "document.xliff", "translation.xml", "/path/to/file.xliff", "my_file_v2.xliff" ] print("Testing filename generation:") print("=" * 60) for test_file in test_files: output = generate_output_filename(test_file) print(f"Input: {test_file}") print(f"Output: {output}") print("-" * 60) # Launch the application if __name__ == "__main__": # Optional: Test filename generation # test_filename_generation() # Choose interface style demo = create_interface() # Detailed layout # demo = create_simple_interface() # Simpler layout # Launch with options demo.launch( share=False, # Set to True to create public link server_name="0.0.0.0", # Allow external access server_port=7860, # Default Gradio port show_error=True, debug=True )