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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import datetime
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from groq import Groq
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import M2M100ForConditionalGeneration, M2M100Tokenizer
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
# ✅ Set API Key
|
| 10 |
+
os.environ["GROQ_API_KEY"] = "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" # Replace with your API key
|
| 11 |
+
# GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
|
| 12 |
+
|
| 13 |
+
client = Groq(api_key=os.environ["GROQ_API_KEY"])
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# ✅ Load M2M-100 Model
|
| 17 |
+
model_name = "facebook/m2m100_418M"
|
| 18 |
+
tokenizer = M2M100Tokenizer.from_pretrained(model_name)
|
| 19 |
+
model = M2M100ForConditionalGeneration.from_pretrained(model_name)
|
| 20 |
+
|
| 21 |
+
# ✅ Function to Get Response from Groq API
|
| 22 |
+
def get_groq_response(prompt):
|
| 23 |
+
print("🤖 Generating Response...")
|
| 24 |
+
client = Groq(api_key=os.environ["GROQ_API_KEY"])
|
| 25 |
+
chat_completion = client.chat.completions.create(
|
| 26 |
+
messages=[{"role": "user", "content": prompt}],
|
| 27 |
+
model="llama-3.3-70b-versatile"
|
| 28 |
+
)
|
| 29 |
+
return chat_completion.choices[0].message.content
|
| 30 |
+
|
| 31 |
+
def generate_script(topic, duration):
|
| 32 |
+
try:
|
| 33 |
+
words_per_minute = 130 # Approximate speaking rate
|
| 34 |
+
target_words = duration * words_per_minute
|
| 35 |
+
|
| 36 |
+
response = client.chat.completions.create(
|
| 37 |
+
messages=[
|
| 38 |
+
{"role": "user", "content": f"Generate a plain, well-structured educational script about {topic} in English with approximately {target_words} words. Do not include stage directions, sound cues, or visual elements—only the spoken content."}
|
| 39 |
+
],
|
| 40 |
+
model="llama-3.3-70b-versatile"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
english_script = response.choices[0].message.content
|
| 45 |
+
return english_script
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"❌ Error in script generation: {str(e)}")
|
| 48 |
+
return ""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def translate_to_urdu(english_script):
|
| 52 |
+
try:
|
| 53 |
+
tokenizer.src_lang = "en"
|
| 54 |
+
inputs = tokenizer(english_script, return_tensors="pt", truncation=True, max_length=1024).to(model.device)
|
| 55 |
+
|
| 56 |
+
translated_tokens = model.generate(
|
| 57 |
+
**inputs,
|
| 58 |
+
max_length=1024,
|
| 59 |
+
no_repeat_ngram_size=2, # Reduce repetition checks (faster)
|
| 60 |
+
forced_bos_token_id=tokenizer.get_lang_id("ur"),
|
| 61 |
+
num_beams=2 # Faster than beam search with high values
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
urdu_script = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
|
| 65 |
+
return urdu_script
|
| 66 |
+
|
| 67 |
+
except Exception as e:
|
| 68 |
+
return f"❌ Error in translation: {str(e)}"
|
| 69 |
+
|
| 70 |
+
# # ✅ Function to Translate English Script to Urdu
|
| 71 |
+
# def translate_to_urdu(english_script):
|
| 72 |
+
# try:
|
| 73 |
+
# tokenizer.src_lang = "en"
|
| 74 |
+
# inputs = tokenizer(english_script, return_tensors="pt", truncation=True, max_length=1024).to(model.device)
|
| 75 |
+
|
| 76 |
+
# translated_tokens = model.generate(
|
| 77 |
+
# **inputs,
|
| 78 |
+
# max_length=1024,
|
| 79 |
+
# no_repeat_ngram_size=2, # Reduce repetition checks (faster)
|
| 80 |
+
# forced_bos_token_id=tokenizer.lang_code_to_id["ur"], # Fix for language ID error
|
| 81 |
+
# num_beams=2 # Faster translation
|
| 82 |
+
# )
|
| 83 |
+
|
| 84 |
+
# urdu_script = tokenizer.decode(translated_tokens[0], skip_special_tokens=True)
|
| 85 |
+
# return urdu_script
|
| 86 |
+
# except Exception as e:
|
| 87 |
+
# return f"❌ Error in translation: {str(e)}"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ✅ Function to Save Edited Urdu Script to a File
|
| 92 |
+
def save_edited_urdu(edited_urdu_script, topic):
|
| 93 |
+
timestamp = datetime.datetime.now().strftime("%Y_%m_%d")
|
| 94 |
+
filename = f"{topic}_Urdu_Final_{timestamp}.txt"
|
| 95 |
+
|
| 96 |
+
with open(filename, "w", encoding="utf-8") as file:
|
| 97 |
+
file.write(edited_urdu_script)
|
| 98 |
+
|
| 99 |
+
return filename # Return the file name so it can be downloaded
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def save_file(content, filename):
|
| 105 |
+
with open(filename, "w", encoding="utf-8") as file:
|
| 106 |
+
file.write(content)
|
| 107 |
+
return filename
|
| 108 |
+
|
| 109 |
+
def process_request(topic, duration):
|
| 110 |
+
eng_script = generate_script(topic, duration)
|
| 111 |
+
return eng_script, ""
|
| 112 |
+
|
| 113 |
+
def process_translation(eng_script):
|
| 114 |
+
urdu_script = translate_to_urdu(eng_script)
|
| 115 |
+
return urdu_script
|
| 116 |
+
|
| 117 |
+
def download_english(eng_script, topic):
|
| 118 |
+
timestamp = datetime.datetime.now().strftime("%Y_%m_%d")
|
| 119 |
+
filename = f"{topic}_Eng_{timestamp}.txt"
|
| 120 |
+
return save_file(eng_script, filename)
|
| 121 |
+
|
| 122 |
+
def download_urdu(urdu_script, topic):
|
| 123 |
+
timestamp = datetime.datetime.now().strftime("%Y_%m_%d")
|
| 124 |
+
filename = f"{topic}_Urdu_{timestamp}.txt"
|
| 125 |
+
return save_file(urdu_script, filename)
|
| 126 |
+
|
| 127 |
+
def download_final_urdu(edited_urdu_script, topic):
|
| 128 |
+
timestamp = datetime.datetime.now().strftime("%Y_%m_%d")
|
| 129 |
+
filename = f"{topic}_Urdu_Final_{timestamp}.txt"
|
| 130 |
+
return save_file(edited_urdu_script, filename)
|
| 131 |
+
|
| 132 |
+
# ✅ Gradio UI
|
| 133 |
+
with gr.Blocks() as app:
|
| 134 |
+
gr.Markdown("# 🎬 AI-Powered Script Generator")
|
| 135 |
+
|
| 136 |
+
topic_input = gr.Textbox(label="Enter Topic")
|
| 137 |
+
duration_input = gr.Slider(minimum=1, maximum=30, step=1, label="Duration (minutes)")
|
| 138 |
+
generate_button = gr.Button("Generate English Script")
|
| 139 |
+
eng_output = gr.Textbox(label="Generated English Script", interactive=False)
|
| 140 |
+
generate_button.click(process_request, inputs=[topic_input, duration_input], outputs=[eng_output])
|
| 141 |
+
|
| 142 |
+
translate_button = gr.Button("Generate Urdu Script")
|
| 143 |
+
urdu_output = gr.Textbox(label="Translated Urdu Script (Editable)", interactive=True)
|
| 144 |
+
translate_button.click(process_translation, inputs=[eng_output], outputs=[urdu_output])
|
| 145 |
+
|
| 146 |
+
# Editable Urdu Textbox
|
| 147 |
+
gr.Markdown("### ✍ Edit Urdu Script Below")
|
| 148 |
+
editable_urdu = gr.Textbox(label="Edited Urdu Script", interactive=True)
|
| 149 |
+
# Save Edited Urdu Script
|
| 150 |
+
save_button = gr.Button("Save Edited Urdu Script")
|
| 151 |
+
|
| 152 |
+
# Update the editable Urdu box with translated script
|
| 153 |
+
translate_button.click(lambda x: x, inputs=[urdu_output], outputs=[editable_urdu])
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
download_eng_button = gr.Button("📥 Download English Script")
|
| 157 |
+
download_eng_file = gr.File()
|
| 158 |
+
|
| 159 |
+
download_urdu_button = gr.Button("📥 Download Translated Urdu Script")
|
| 160 |
+
download_urdu_file = gr.File()
|
| 161 |
+
|
| 162 |
+
# Download Edited Urdu Script
|
| 163 |
+
download_final_urdu_button = gr.Button("📥 Download Edited Urdu Script")
|
| 164 |
+
download_final_urdu_file = gr.File()
|
| 165 |
+
|
| 166 |
+
# Save the edited script
|
| 167 |
+
save_button.click(save_edited_urdu, inputs=[editable_urdu, topic_input], outputs=[download_final_urdu_file])
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
download_eng_button.click(download_english, inputs=[eng_output, topic_input], outputs=[download_eng_file])
|
| 171 |
+
download_urdu_button.click(download_urdu, inputs=[urdu_output, topic_input], outputs=[download_urdu_file])
|
| 172 |
+
download_final_urdu_button.click(download_final_urdu, inputs=[editable_urdu, topic_input], outputs=[download_final_urdu_file])
|
| 173 |
+
|
| 174 |
+
app.launch()
|