Spaces:
Sleeping
Sleeping
Download app.py from evito/XLIFF_SourceTarget_Swapper: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/spaces/evito/XLIFF_SourceTarget_Swapper/resolve/main/app.py
- Command line
-
hf download hf://spaces/evito/XLIFF_SourceTarget_Swapper/app.py
-
curl -L -o app.py https://huggingface.co/spaces/evito/XLIFF_SourceTarget_Swapper/resolve/main/app.py
12.1 kB
| 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'<trans-unit[^>]*>.*?</trans-unit>' | |
| 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'<trans-unit[^>]*id="([^"]*)"', trans_unit) | |
| unit_id = id_match.group(1) if id_match else "unknown" | |
| # Extract source and target content | |
| source_pattern = r'<source[^>]*>(.*?)</source>' | |
| target_pattern = r'<target[^>]*>(.*?)</target>' | |
| 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'<source___TEMP___>{target_content}</source___TEMP___>', 1) | |
| trans_unit = trans_unit.replace(target_full, f'<target>{source_content}</target>', 1) | |
| trans_unit = trans_unit.replace('<source___TEMP___>', '<source' + source_full.split('>', 1)[0].split('<source', 1)[1] + '>', 1) | |
| trans_unit = trans_unit.replace('</source___TEMP___>', '</source>', 1) | |
| swap_count += 1 | |
| log_messages.append(f"β Swapped: {unit_id}") | |
| else: | |
| # Copy source to target | |
| trans_unit = trans_unit.replace(target_full, f'<target>{source_content}</target>', 1) | |
| copy_count += 1 | |
| log_messages.append(f"β Copied to target: {unit_id}") | |
| else: | |
| # No target element, add one | |
| trans_unit = trans_unit.replace('</trans-unit>', f'<target>{source_content}</target></trans-unit>', 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 '<trans-unit' in content): | |
| return None, "β Error", "Invalid XLIFF file! Please upload a valid XLIFF file.", "" | |
| # Process the file | |
| modified_content, swap_count, copy_count, log_messages = swap_source_target_simple(content) | |
| # Generate output filename with datetime | |
| output_filename = generate_output_filename(input_file.name) | |
| # Create output file in temporary directory with custom name | |
| temp_dir = tempfile.gettempdir() | |
| output_path = os.path.join(temp_dir, output_filename) | |
| with open(output_path, 'w', encoding='utf-8') as f: | |
| f.write(modified_content) | |
| # Prepare statistics | |
| total_operations = swap_count + copy_count | |
| stats = f""" | |
| ## π Processing Statistics | |
| - **Input File:** `{Path(input_file.name).name}` | |
| - **Output File:** `{output_filename}` | |
| - **Processing Time:** `{datetime.now().strftime("%d/%m/%Y %H:%M:%S")}` | |
| - **Total Operations:** {total_operations} | |
| - **Swaps (source β target):** {swap_count} | |
| - **Copies (source β target):** {copy_count} | |
| """ | |
| # Prepare log (limit to last 50 entries if too many) | |
| log_display = log_messages[-50:] if len(log_messages) > 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 `<source>` and `<target>` 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 | |
| <trans-unit id="example-1"> | |
| <source xml:lang="de">Hallo Welt</source> | |
| <target xml:lang="en">Hello World</target> | |
| </trans-unit> | |
| ``` | |
| **After processing:** | |
| ```xml | |
| <trans-unit id="example-1"> | |
| <source xml:lang="de">Hello World</source> | |
| <target xml:lang="en">Hallo Welt</target> | |
| </trans-unit> | |
| ``` | |
| """) | |
| # 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 | |
| ) |