CoolFace
Apppublic

Sameerquadri/hinglishbot

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
bot.py185 linesDownload Raw Back to root
1import os2import time3import logging4from telegram import Update5from telegram.ext import ApplicationBuilder, ContextTypes, MessageHandler, filters6import yt_dlp7from moviepy import VideoFileClip8import google.generativeai as genai9from threading import Thread10from http.server import HTTPServer, BaseHTTPRequestHandler11 12# --- 1. CONFIGURATION & VALIDATION ---13TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")14GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") 15TEMP_FOLDER = "temp_data"16 17# Hard Fail: Crash immediately if keys are missing18if not TELEGRAM_TOKEN:19    raise RuntimeError("❌ TELEGRAM_TOKEN is not set in environment variables")20if not GEMINI_API_KEY:21    raise RuntimeError("❌ GEMINI_API_KEY is not set in environment variables")22 23# Ensure temp folder exists24if not os.path.exists(TEMP_FOLDER):25    os.makedirs(TEMP_FOLDER)26 27# Configure Gemini28genai.configure(api_key=GEMINI_API_KEY)29 30# Setup Logging31logging.basicConfig(32    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',33    level=logging.INFO34)35 36# --- 2. FAKE WEB SERVER (REQUIRED FOR UPTIMEROBOT) ---37class SimpleHandler(BaseHTTPRequestHandler):38    def do_GET(self):39        self.send_response(200)40        self.end_headers()41        self.wfile.write(b"Bot is alive!")42 43def start_web_server():44    port = int(os.environ.get("PORT", 7860))45    server = HTTPServer(('0.0.0.0', port), SimpleHandler)46    server.serve_forever()47 48# --- 3. PROMPT ---49HINGLISH_INSTRUCTIONS = """50Translate the following English script into modern, conversational Hinglish.51Follow these rules strictly:52Preserve the original HOOK — same curiosity, shock, tension, or intrigue.53Preserve the BUILDUP — same pacing, suspense, emotional rhythm, and narrative flow.54Preserve the ENDING/PUNCHLINE — same impact, payoff, CTA, or twist.55Use modern, natural Hinglish — the way people actually speak in reels.56Keep lines crisp and high-retention — avoid long, formal Hindi sentences.57Do NOT add or remove meaning. No improvising.58No literal translation — rewrite naturally while keeping intent intact.59ABSOLUTE RULE:60👉 Output ONLY the translated script.61👉 No explanation, no notes, no extra lines before or after.62"""63 64# --- 4. AI PROCESSING ---65async def process_with_gemini(audio_path):66    """Uploads audio to Gemini, Transcribes, then Translates to Hinglish."""67    try:68        myfile = genai.upload_file(audio_path)69        70        while myfile.state.name == "PROCESSING":71            time.sleep(1)72            myfile = genai.get_file(myfile.name)73 74        model = genai.GenerativeModel("gemini-1.5-flash")75        76        full_prompt = (77            "Task 1: Listen to the attached audio and transcribe it exactly into English.\n"78            "Task 2: Take that English transcription and apply the following instructions to create a Hinglish version:\n\n"79            f"{HINGLISH_INSTRUCTIONS}\n\n"80            "FINAL OUTPUT FORMAT (Strictly follow this):\n"81            "📝 **Original Script:**\n"82            "[Insert English Transcript Here]\n\n"83            "🇮🇳 **Hinglish Script:**\n"84            "[Insert Hinglish Translation Here]"85        )86        87        result = model.generate_content([myfile, full_prompt])88        myfile.delete() 89        return result.text90    except Exception as e:91        return f"AI Error: {str(e)}"92 93# --- 5. MEDIA PROCESSING ---94async def process_media(update: Update, context: ContextTypes.DEFAULT_TYPE, video_path: str):95    status_msg = await update.message.reply_text("🎧 Extracting audio & AI Processing...")96    audio_path = os.path.join(TEMP_FOLDER, "temp_audio.mp3")97    98    try:99        video_clip = VideoFileClip(video_path)100        video_clip.audio.write_audiofile(audio_path, logger=None)101        video_clip.close()102 103        response_text = await process_with_gemini(audio_path)104 105        await status_msg.edit_text("📤 Uploading Video...")106        with open(video_path, 'rb') as v:107            await context.bot.send_video(108                chat_id=update.effective_chat.id,109                video=v,110                caption="🎬 **Original Video**",111                parse_mode="Markdown"112            )113            114        if len(response_text) > 4000:115            for x in range(0, len(response_text), 4000):116                await context.bot.send_message(117                    chat_id=update.effective_chat.id, 118                    text=response_text[x:x+4000], 119                    parse_mode="Markdown"120                )121        else:122            await context.bot.send_message(123                chat_id=update.effective_chat.id, 124                text=response_text, 125                parse_mode="Markdown"126            )127        128        await status_msg.delete()129 130    except Exception as e:131        await status_msg.edit_text(f"❌ Error: {str(e)}")132        logging.error(e)133    finally:134        if os.path.exists(audio_path): os.remove(audio_path)135        if os.path.exists(video_path): os.remove(video_path)136 137# --- 6. HANDLERS ---138async def handle_link(update: Update, context: ContextTypes.DEFAULT_TYPE):139    url = update.message.text140    if not any(x in url for x in ["instagram.com", "youtube.com", "youtu.be"]):141        return142 143    status_msg = await update.message.reply_text("⬇️ Attempting to download...")144    145    try:146        ydl_opts = {'outtmpl': f'{TEMP_FOLDER}/%(id)s.%(ext)s', 'format': 'best[ext=mp4]', 'quiet': True}147        with yt_dlp.YoutubeDL(ydl_opts) as ydl:148            info = ydl.extract_info(url, download=True)149            video_path = ydl.prepare_filename(info)150        151        await status_msg.delete()152        await process_media(update, context, video_path)153    except Exception as e:154        await status_msg.edit_text(155            f"❌ **Download Failed (Likely Instagram Block).**\n"156            f"👉 **Please forward the video file here directly.**", 157            parse_mode="Markdown"158        )159 160async def handle_video(update: Update, context: ContextTypes.DEFAULT_TYPE):161    video = update.message.video162    if video.file_size > 20 * 1024 * 1024:163        await update.message.reply_text("❌ File > 20MB. Telegram Bot Limit.")164        return165 166    status_msg = await update.message.reply_text("📥 Received video. Downloading...")167    video_file = await context.bot.get_file(video.file_id)168    video_path = os.path.join(TEMP_FOLDER, "downloaded_video.mp4")169    170    await video_file.download_to_drive(video_path)171    await status_msg.delete()172    await process_media(update, context, video_path)173 174# --- 7. EXECUTION ---175if __name__ == '__main__':176    # Start Keep-Alive Server (Crucial for UptimeRobot)177    Thread(target=start_web_server, daemon=True).start()178    179    # Start Bot180    app = ApplicationBuilder().token(TELEGRAM_TOKEN).build()181    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_link))182    app.add_handler(MessageHandler(filters.VIDEO, handle_video))183    184    print("✅ Bot is Running...")185    app.run_polling()