[Python] How do I get this progress bar to render only in the SRT File section, not the...

Discussão em 'Python' iniciado por Stack, Abril 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am doing a little side project while working through huggingface's agent course (and maybe this will be my final project that I turn in, if it is acceptable). I am not really familiar with gradio, but they seem to favor it there so I decided to use it. But I'm having a bit of an issue: the progress bar is meant to replace the contents of the SRT Translated File section, but not the Warnings section (that will be a live log). But in practice what happens is both of them are overwritten. I've tried about half a dozen different things based on AI input but none of them are working. I think this is related to the fact that the function yields both the sections, yet both need updating so I'm not sure how to do this correctly.

    def translate_srt_file(srt_file, target_language, style_guideline, technical_guideline, progress=gr.Progress()):
    temp_dir = None
    try:
    temp_dir = os.path.join(get_persistent_temp_dir(), f"tmp{os.urandom(4).hex()}")
    os.makedirs(temp_dir, exist_ok=True)

    input_path = Path(temp_dir) / "input.srt"
    output_path = Path(temp_dir) / "output.srt"

    with open(input_path, "wb") as f:
    f.write(srt_file)

    translator = create_translator(
    target_language=target_language,
    style_guideline=style_guideline,
    technical_guideline=technical_guideline
    )
    entries = translator.parse_srt(input_path)
    total_entries = len(entries)

    warning_message = "Starting translation...\n"
    progress_desc = "Initializing..."
    yield None, warning_message, gr.update(value=progress_desc)

    for i, entry in enumerate(entries, 1):
    progress_desc = f"Translating: {i}/{total_entries} entries ({int((i/total_entries)*100)}%)"
    progress(i / total_entries)
    current_warning_update = None

    try:
    context = (
    2, # Context window size
    [
    entries[max(0, i-1)]['text'],
    entries[min(total_entries-1, i+1)]['text']
    ]
    )

    entry['translation'] = translator.translation_tool(entry['text'], context=context)
    is_valid, feedback = translator.validation_tool(entry['text'], entry['translation'], context=context)

    if not is_valid:
    warning = {
    'entry': entry['number'],
    'type': 'validation',
    'message': feedback,
    'original': entry['text'],
    'translation': entry['translation']
    }
    formatted = format_warning(warning)
    warning_message += formatted
    current_warning_update = warning_message

    except Exception as e:
    error = {
    'entry': entry['number'],
    'type': 'error',
    'message': str(e),
    'original': entry['text'],
    'translation': None
    }
    formatted = format_warning(error)
    warning_message += formatted
    entry['translation'] = f"[ERROR] {entry['text']}"
    current_warning_update = warning_message

    yield None, current_warning_update if current_warning_update else gr.update(), progress_desc

    with open(output_path, 'w', encoding='utf-8') as f:
    for entry in entries:
    f.write(f"{entry['number']}\n")
    f.write(f"{entry['timecode']}\n")
    f.write(f"{entry.get('translation', entry['text'])}\n\n")

    # Final output with caching consideration
    warning_message += "\n\n✅ Translation complete!"
    progress_desc = "Translation complete!"

    yield str(output_path), warning_message, progress_desc
    if os.getenv("GRADIO_CACHING_EXAMPLES"): # For caching, keep files around and let Gradio handle them
    time.sleep(2) # Give Gradio time to cache

    except Exception as e:
    raise gr.Error(f"Translation failed: {str(e)}")
    finally:
    if not os.getenv("GRADIO_CACHING_EXAMPLES") and temp_dir and os.path.exists(temp_dir):
    try:
    import shutil
    shutil.rmtree(temp_dir)
    logger.info(f"Cleaned up temporary directory: {temp_dir}")
    except Exception as cleanup_error:
    logger.error(f"Failed to cleanup {temp_dir}: {cleanup_error}")


    # Gradio interface
    with gr.Blocks(title="SRT File Translator") as demo:
    gr.Markdown("""
    # SRT File Translator
    Upload an SRT subtitle file and customize your translation.
    """)

    with gr.Row():
    # --- Input Column ---
    with gr.Column():
    file_input = gr.File(label="Upload SRT File", type="binary")
    language_dropdown = gr.Dropdown(
    label="Target Language",
    choices=["en", "es", "fr", "de", "it", "pt", "ru", "zh", "ja", "ko"],
    value="es"
    )
    style_guideline = gr.Textbox(
    label="Style Guideline",
    value="Natural speech patterns",
    placeholder="E.g., Conversational, Formal, Casual"
    )
    technical_guideline = gr.Textbox(
    label="Technical Guideline",
    value="Use standard terminology",
    placeholder="E.g., Use industry-specific terms, Localize technical language"
    )
    submit_btn = gr.Button("Translate", variant="primary")

    # --- Output Column ---
    with gr.Column():
    file_output = gr.File(label="Translated SRT File")
    warnings_output = gr.Textbox(label="Translation Warnings", interactive=False)

    # *** Click handler outputs ***
    submit_btn.click(
    fn=translate_srt_file,
    inputs=[file_input, language_dropdown, style_guideline, technical_guideline],
    outputs=[file_output, warnings_output],
    )

    # *** Examples outputs ***
    gr.Examples(
    examples=[
    ["example.srt", "es", "Natural speech patterns", "Use standard terminology"],
    ["example.srt", "fr", "Formal and elegant", "Precise technical translations"],
    ],
    inputs=[file_input, language_dropdown, style_guideline, technical_guideline],
    outputs=[file_output, warnings_output],
    fn=translate_srt_file,
    cache_examples=True,
    )


    if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)

    Continue reading...

Compartilhe esta Página