CoolFace
Apppublic

arcanus/koala2

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
serverapi+yt+tit.py175 linesDownload Raw Back to root
1from flask import Flask, request, jsonify, send_from_directory2from flask_cors import CORS3import os4from werkzeug.utils import secure_filename5from app_rvc import SoniTranslate  # Importuj SoniTranslate z app_rvc.py6 7app = Flask(__name__)8CORS(app)9 10UPLOAD_FOLDER = "uploads"11OUTPUT_FOLDER = "outputs"12TRANSLATION_FOLDER = "translations"13 14# Zajištění existence složek15for folder in [UPLOAD_FOLDER, OUTPUT_FOLDER, TRANSLATION_FOLDER]:16    if not os.path.exists(folder):17        os.makedirs(folder)18 19API_KEY = "MY_SECRET_API_KEY"20 21# Endpoint pro stahování souborů22@app.route("/downloads/<path:filename>", methods=["GET"])23def download_file(filename):24    print(f"Download requested for file: {filename}")25    return send_from_directory(OUTPUT_FOLDER, filename, as_attachment=True)26 27# Endpoint pro uložení a zobrazení překladu28@app.route("/translations/<video_id>", methods=["GET", "POST"])29def manage_translation(video_id):30    translation_file = os.path.join(TRANSLATION_FOLDER, f"{video_id}.txt")31    print(f"Manage translation for video_id: {video_id}, file path: {translation_file}")32 33    if request.method == "GET":34        if os.path.exists(translation_file):35            with open(translation_file, "r", encoding="utf-8") as file:36                return jsonify({"translation": file.read()})37        return jsonify({"error": "Translation not found"}), 40438 39    if request.method == "POST":40        data = request.json.get("edited_translation")41        print(f"Saving edited translation for video_id: {video_id}")42        with open(translation_file, "w", encoding="utf-8") as file:43            file.write(data)44        return jsonify({"status": "success", "message": "Translation updated"})45 46# Endpoint pro překlad47@app.route("/translate_video", methods=["POST"])48def translate_video():49    api_key = request.headers.get("Authorization")50    if api_key != f"Bearer {API_KEY}":51        print("Invalid API key")52        return jsonify({"status": "error", "message": "Invalid API key"}), 40353 54    video_file = request.files.get("video")55    youtube_url = request.form.get("youtube_url")56    target_language = request.form.get("target_language")57 58    if not target_language:59        print("Missing target language")60        return jsonify({"status": "error", "message": "Missing target language"}), 40061 62    if not video_file and not youtube_url:63        print("Missing video or YouTube URL")64        return jsonify({"status": "error", "message": "Missing video or YouTube URL"}), 40065 66    file_path = None67    try:68        if video_file:69            filename = secure_filename(video_file.filename)70            file_path = os.path.join(UPLOAD_FOLDER, filename)71            video_file.save(file_path)72            print(f"Uploaded video saved at: {file_path}")73 74        translator = SoniTranslate(cpu_mode=False)75        result_files = translator.multilingual_media_conversion(76            media_file=file_path if video_file else None,77            link_media=youtube_url if youtube_url else "",78            target_language=target_language,79            is_gui=False,80        )81 82        print("Result files:", result_files)83 84        # Najít a uložit SRT soubor85        video_id = os.path.splitext(os.path.basename(file_path or youtube_url))[0]86        srt_file = os.path.join(OUTPUT_FOLDER, f"{video_id}__cs.srt")87        print(f"Looking for SRT file at: {srt_file}")88 89        if os.path.exists(srt_file):90            with open(srt_file, "r", encoding="utf-8") as file:91                translation = file.read()92 93            translation_file = os.path.join(TRANSLATION_FOLDER, f"{video_id}.txt")94            with open(translation_file, "w", encoding="utf-8") as file:95                file.write(translation)96 97            print(f"Translation saved at: {translation_file}")98 99        return jsonify({100            "status": "success",101            "translation_url": f"http://{request.host}/translations/{video_id}",102            "message": "Translation completed and ready for editing."103        }), 200104 105    except Exception as e:106        print(f"Error during translation: {str(e)}")107        return jsonify({"status": "error", "message": str(e)}), 500108 109#    finally:110#        if file_path and os.path.exists(file_path):111 #           os.remove(file_path)112 #           print(f"Temporary file removed: {file_path}")113 114# Nový endpoint pro dabing po úpravě titulků115@app.route("/start_dubbing/<video_id>", methods=["POST"])116def start_dubbing(video_id):117    print(f"Starting dubbing for video_id: {video_id}")118    language_code = "cs"119    translated_video_file = os.path.join(OUTPUT_FOLDER, f"{video_id}__{language_code}.mp4")120    srt_file = os.path.join(OUTPUT_FOLDER, f"{video_id}__{language_code}.srt")121    translation_file = os.path.join(TRANSLATION_FOLDER, f"{video_id}.txt")122 123    print(f"Checking files for dubbing:\nTranslated video: {translated_video_file}\nSRT file: {srt_file}\nTranslation file: {translation_file}")124 125    if not os.path.exists(translated_video_file):126        print("Translated video not found")127        return jsonify({"status": "error", "message": f"Translated video not found: {translated_video_file}"}), 404128 129    if not os.path.exists(srt_file):130        print("Subtitle file not found")131        return jsonify({"status": "error", "message": f"Subtitle file not found: {srt_file}"}), 404132 133    if not os.path.exists(translation_file):134        print("Translation file not found")135        return jsonify({"status": "error", "message": f"Translation file not found: {translation_file}"}), 404136 137    try:138        # Aktualizace titulků139        with open(translation_file, "r", encoding="utf-8") as file:140            updated_translation = file.read()141 142        with open(srt_file, "w", encoding="utf-8") as file:143            file.write(updated_translation)144        print(f"Updated subtitles saved at: {srt_file}")145 146        # Spustit dabing znovu pomocí SoniTranslate147        translator = SoniTranslate(cpu_mode=False)148        result_files = translator.multilingual_media_conversion(149            media_file=translated_video_file,150            link_media="",151            target_language="Czech (cs)",152            is_gui=False,153        )154        print("Result files from dubbing:", result_files)155 156        # Vrátit URL k nově vytvořeným souborům157        result_urls = [158            f"http://{request.host}/downloads/{os.path.basename(file)}"159            for file in result_files160        ]161 162        return jsonify({163            "status": "success",164            "result": result_urls,165            "message": "Dubbing completed successfully."166        }), 200167 168    except Exception as e:169        print(f"Error during dubbing: {str(e)}")170        return jsonify({"status": "error", "message": str(e)}), 500171 172# Spuštění aplikace173if __name__ == "__main__":174    app.run(host="0.0.0.0", port=5000, debug=True)175