broadfield-dev commited on
Commit
5181a56
Β·
verified Β·
1 Parent(s): 41f843c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -72
app.py CHANGED
@@ -1,84 +1,60 @@
1
- # We import the Translator class to handle translations and the LANGUAGES dictionary
2
- # to get the full name of a language from its code (e.g., 'en' -> 'english').
3
- from googletrans import Translator, LANGUAGES
 
 
 
 
4
 
5
- def detailed_translate(text_to_translate: str, dest_lang: str):
6
- """
7
- Translates a piece of text and prints a detailed report of the process.
8
-
9
- Args:
10
- text_to_translate (str): The text you want to translate.
11
- dest_lang (str): The language code to translate into (e.g., 'es', 'fr').
12
- """
13
- if not text_to_translate.strip():
14
- print("Error: Input text cannot be empty.")
15
- return
16
-
17
- print("\nπŸ”„ Processing your translation request...")
18
 
 
 
19
  try:
20
- # 1. Create a Translator object
21
- translator = Translator()
22
-
23
- # 2. Perform the translation. The translate() method returns a result object
24
- # that contains all the details we need.
25
- translation_result = translator.translate(text_to_translate, dest=dest_lang)
26
-
27
- # 3. Extract details from the result object
28
- original_text = translation_result.origin
29
- translated_text = translation_result.text
30
- detected_lang_code = translation_result.src
31
- target_lang_code = translation_result.dest
32
-
33
- # 4. Get the full, human-readable language names from the codes
34
- # We use .get() with a default value in case the code isn't found
35
- detected_lang_name = LANGUAGES.get(detected_lang_code, "Unknown").title()
36
- target_lang_name = LANGUAGES.get(target_lang_code, "Unknown").title()
37
-
38
-
39
- # 5. Print the detailed report
40
- print("\n" + "="*15 + " Translation Details " + "="*15)
41
 
42
- print(f"\nπŸ“„ Original Transcript:")
43
- print(f" \"{original_text}\"")
44
 
45
- print(f"\nπŸ” Detected Language:")
46
- print(f" {detected_lang_name} (code: {detected_lang_code})")
 
 
 
 
 
 
 
 
47
 
48
- print(f"\n🎯 Target Language:")
49
- print(f" {target_lang_name} (code: {target_lang_code})")
50
 
51
- print(f"\n✨ Translated Text:")
52
- print(f" \"{translated_text}\"")
 
 
53
 
54
- print("\n" + "="*49)
55
 
56
  except Exception as e:
57
- print(f"\n❌ An error occurred during translation.")
58
- print(f" Error details: {e}")
59
- print(" Please check your internet connection and ensure the language code is valid.")
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
-
62
- # --- Main part of the script that runs when you execute it ---
63
  if __name__ == "__main__":
64
- print("--- Welcome to the Detailed Translator! ---")
65
- print("You can type 'quit' or 'exit' at any time to close the program.")
66
-
67
- while True:
68
- # Get input from the user
69
- text_input = input("\nEnter the text you want to translate: ")
70
-
71
- # Check if the user wants to exit
72
- if text_input.lower() in ['quit', 'exit']:
73
- print("πŸ‘‹ Goodbye!")
74
- break
75
-
76
- target_lang_input = input("Enter the target language (e.g., 'es' for Spanish, 'fr' for French, 'ja' for Japanese): ").lower()
77
-
78
- # Check if the user wants to exit
79
- if target_lang_input.lower() in ['quit', 'exit']:
80
- print("πŸ‘‹ Goodbye!")
81
- break
82
-
83
- # Call our detailed translation function
84
- detailed_translate(text_input, target_lang_input)
 
1
+ import gradio as gr
2
+ import subprocess
3
+ import os
4
+ import shutil
5
+ import uuid
6
+ from transformers import pipeline
7
+ from gtts import gTTS
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ def translate_video(file_path):
11
+
12
  try:
13
+ audio_path = os.path.join(file_path, "audio.wav")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ if not os.path.exists(audio_path):
16
+ raise FileNotFoundError("Audio extraction failed. yt-dlp did not produce a .wav file.")
17
 
18
+ # 3. Translate the audio using the whisper-tiny model
19
+ translator = pipeline(
20
+ "automatic-speech-recognition",
21
+ model="openai/whisper-tiny",
22
+ device="cpu"
23
+ )
24
+
25
+ translation = translator(audio_path, return_timestamps=True, generate_kwargs={"task": "translate"})
26
+
27
+ translated_text = translation["text"]
28
 
29
+ if not translated_text:
30
+ return "No speech was detected in the video.", None, video_path
31
 
32
+ # 4. Convert translated text to speech using gTTS
33
+ tts = gTTS(translated_text.strip(), lang='en')
34
+ translated_audio_path = os.path.join(temp_dir, "translated_audio.mp3")
35
+ tts.save(translated_audio_path)
36
 
37
+ return translated_text, translated_audio_path, video_path
38
 
39
  except Exception as e:
40
+ gr.Warning(f"An unexpected error occurred: {str(e)}")
41
+ return f"An error occurred: {str(e)}", None, None
42
+
43
+ # Create the Gradio interface
44
+ iface = gr.Interface(
45
+ fn=translate_video,
46
+ inputs=gr.Video(label="Upload your video to translate"),
47
+ outputs=[
48
+ gr.Textbox(label="Translated Text", interactive=False),
49
+ gr.Audio(label="Translated Audio"),
50
+ gr.Video(label="Original Video"),
51
+ ],
52
+ title="Twitter/X Video Translator",
53
+ description="Enter a link to a Twitter/X video to translate its audio to English. Handles videos longer than 30 seconds.",
54
+ allow_flagging="never",
55
+ )
56
 
 
 
57
  if __name__ == "__main__":
58
+ if not os.path.exists("downloads"):
59
+ os.makedirs("downloads")
60
+ iface.launch()