File size: 12,140 Bytes
7c0caa4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
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
    )