""" Instagram AI Bot - Complete Streamlit Application Auto-reply to DMs and Comments using Llama 3.1 AI Created with ๐Ÿ’• """ import streamlit as st import time import json import random from datetime import datetime from pathlib import Path from instagram_handler import InstagramHandler from ai_engine import AIEngine from bot_engine import BotEngine from config import DEFAULT_SYSTEM_PROMPT, BOT_CONFIG, MODEL_CONFIG # ============================================================ # PAGE CONFIGURATION # ============================================================ st.set_page_config( page_title="InstaBot AI ๐Ÿค–๐Ÿ’•", page_icon="๐Ÿค–", layout="centered", initial_sidebar_state="collapsed", ) # ============================================================ # CUSTOM CSS (same as Section 1 - keeping it complete) # ============================================================ st.markdown(""" """, unsafe_allow_html=True) # ============================================================ # SESSION STATE INITIALIZATION # ============================================================ def init_session_state(): defaults = { "ig_handler": None, "ai_engine": None, "bot_engine": None, "logged_in": False, "login_error": "", "show_2fa": False, "show_challenge": False, "login_username": "", "profile_info": {}, "system_prompt": "", "auto_dm_enabled": False, "auto_comment_enabled": False, "bot_running": False, "activity_log": [], "total_dms_replied": 0, "total_comments_replied": 0, "bot_start_time": None, "model_loaded": False, "model_loading": False, "model_status": "", "current_page": "login", } for key, val in defaults.items(): if key not in st.session_state: st.session_state[key] = val init_session_state() # ============================================================ # HELPER FUNCTIONS # ============================================================ def add_log(message: str, log_type: str = "info"): timestamp = datetime.now().strftime("%H:%M:%S") emoji_map = { "success": "โœ…", "error": "โŒ", "info": "โ„น๏ธ", "warning": "โš ๏ธ", "dm": "๐Ÿ’Œ", "comment": "๐Ÿ’ฌ", "bot": "๐Ÿค–", } emoji = emoji_map.get(log_type, "๐Ÿ“") st.session_state.activity_log.insert(0, { "time": timestamp, "message": f"{emoji} {message}", "type": log_type, }) if len(st.session_state.activity_log) > 100: st.session_state.activity_log = st.session_state.activity_log[:100] def format_number(num: int) -> str: if num >= 1_000_000: return f"{num / 1_000_000:.1f}M" elif num >= 1_000: return f"{num / 1_000:.1f}K" return str(num) def get_ig_handler() -> InstagramHandler: if st.session_state.ig_handler is None: st.session_state.ig_handler = InstagramHandler() return st.session_state.ig_handler def get_ai_engine() -> AIEngine: if st.session_state.ai_engine is None: st.session_state.ai_engine = AIEngine() return st.session_state.ai_engine def get_bot_engine() -> BotEngine: if st.session_state.bot_engine is None: ig = get_ig_handler() ai = get_ai_engine() st.session_state.bot_engine = BotEngine( ig_handler=ig, ai_engine=ai, log_callback=add_log, ) return st.session_state.bot_engine def render_header(): st.markdown("""

InstaBot AI

Smart Auto-Reply for Instagram โ€ข Powered by Llama 3.1

""", unsafe_allow_html=True) # ============================================================ # LOGIN PAGE # ============================================================ def render_login_page(): render_header() st.markdown('
', unsafe_allow_html=True) st.markdown('
๐Ÿ” Instagram Login
', unsafe_allow_html=True) st.markdown("""
๐Ÿ’ก Tera login info sirf is device pe save hoga. Hum kuch store nahi karte server pe.
""", unsafe_allow_html=True) username = st.text_input("Username", placeholder="Instagram username", key="login_user_input", label_visibility="collapsed") password = st.text_input("Password", type="password", placeholder="Password", key="login_pass_input", label_visibility="collapsed") st.markdown("
", unsafe_allow_html=True) # 2FA Section if st.session_state.show_2fa: st.markdown('
', unsafe_allow_html=True) st.markdown('
๐Ÿ” Two-Factor Auth
', unsafe_allow_html=True) st.markdown('
Authenticator app ya SMS se 2FA code daalo.
', unsafe_allow_html=True) tfa_code = st.text_input("2FA Code", placeholder="6-digit code", max_chars=6, key="tfa_input", label_visibility="collapsed") if st.button("โœ… Verify Code", key="verify_2fa"): if tfa_code: handler = get_ig_handler() with st.spinner("Verifying... โณ"): result = handler.complete_two_factor(tfa_code) if result["success"]: st.session_state.logged_in = True st.session_state.show_2fa = False st.session_state.current_page = "dashboard" add_log(f"Logged in as @{username}", "success") st.rerun() else: st.error(result.get("error", "Failed")) st.markdown("
", unsafe_allow_html=True) # Challenge Section if st.session_state.show_challenge: st.markdown('
', unsafe_allow_html=True) st.markdown('
โš ๏ธ Security Challenge
', unsafe_allow_html=True) st.markdown('
Email/phone pe aaya verification code daalo.
', unsafe_allow_html=True) ch_code = st.text_input("Security Code", placeholder="Code", max_chars=6, key="challenge_input", label_visibility="collapsed") if st.button("โœ… Verify", key="verify_challenge"): if ch_code: handler = get_ig_handler() with st.spinner("Verifying... โณ"): result = handler.complete_challenge(ch_code) if result["success"]: st.session_state.logged_in = True st.session_state.show_challenge = False st.session_state.current_page = "dashboard" add_log(f"Logged in as @{username}", "success") st.rerun() else: st.error(result.get("error", "Failed")) st.markdown("
", unsafe_allow_html=True) # Login Button if st.button("๐Ÿš€ Login to Instagram", key="login_btn"): if not username or not password: st.error("Username aur password dono daalo! ๐Ÿ˜ค") else: handler = get_ig_handler() with st.spinner("Logging in... โณ"): result = handler.login(username, password) if result.get("success"): st.session_state.logged_in = True st.session_state.current_page = "dashboard" st.session_state.login_username = username st.session_state.login_error = "" add_log(f"Logged in as @{username}", "success") st.balloons() st.rerun() elif result.get("two_factor"): st.session_state.show_2fa = True st.rerun() elif result.get("challenge"): st.session_state.show_challenge = True st.rerun() else: st.session_state.login_error = result.get("error", "Login failed") st.error(result.get("error", "Login failed")) if st.session_state.login_error and not st.session_state.show_2fa and not st.session_state.show_challenge: st.markdown(f'
{st.session_state.login_error}
', unsafe_allow_html=True) st.markdown("""

๐Ÿ”’ Credentials sirf login ke liye use hote hain. Kuch store nahi hota.

""", unsafe_allow_html=True) # ============================================================ # DASHBOARD PAGE # ============================================================ def render_dashboard(): handler = get_ig_handler() ai = get_ai_engine() bot = get_bot_engine() if not handler.is_logged_in: st.session_state.logged_in = False st.session_state.current_page = "login" st.rerun() return if not st.session_state.profile_info: with st.spinner("Loading profile... โœจ"): st.session_state.profile_info = handler.get_profile_info() profile = st.session_state.profile_info # Sync bot stats if bot.is_running: stats = bot.get_stats() st.session_state.total_dms_replied = stats["total_dms_replied"] st.session_state.total_comments_replied = stats["total_comments_replied"] st.session_state.bot_running = True # ---- TOP BAR ---- col1, col2, col3 = st.columns([1, 2, 1]) with col1: if st.button("โš™๏ธ", key="settings_btn", help="Settings"): st.session_state.current_page = "settings" st.rerun() with col2: st.markdown('

InstaBot AI ๐Ÿค–

', unsafe_allow_html=True) with col3: if st.button("๐Ÿ“‹", key="logs_btn", help="Logs"): st.session_state.current_page = "logs" st.rerun() # ---- PROFILE CARD ---- username_display = profile.get("username", handler.username) fullname_display = profile.get("full_name", "User") first_letter = fullname_display[0].upper() if fullname_display else "U" bot_status = st.session_state.bot_running st.markdown(f"""
{first_letter}

{fullname_display}

@{username_display}

{'๐ŸŸข Bot ON' if bot_status else '๐Ÿ”ด Bot OFF'}
{format_number(profile.get('follower_count', 0))} Followers
{format_number(profile.get('following_count', 0))} Following
{format_number(profile.get('media_count', 0))} Posts
""", unsafe_allow_html=True) # ---- AI MODEL STATUS ---- ai_status = ai.get_status() if ai_status["model_loaded"]: model_badge = '๐Ÿง  AI Ready' elif ai_status["fallback_mode"]: model_badge = 'โšก Smart Fallback' else: model_badge = 'โŒ Not Loaded' st.markdown(f"""

๐Ÿฆ™ AI Engine

{ai_status.get('gpu_name', ai_status['device'].upper())} {'โ€ข ' + ai_status.get('gpu_memory_allocated', '') if ai_status.get('gpu_memory_allocated') else ''}

{model_badge}
""", unsafe_allow_html=True) # Load Model Button (if not loaded) if not ai_status["model_loaded"] and not ai_status["fallback_mode"]: st.markdown('
', unsafe_allow_html=True) if st.button("๐Ÿง  Load AI Model", key="load_model_btn"): with st.spinner("Loading Llama 3.1 8B... This may take 2-5 minutes โณ๐Ÿฆ™"): result = ai.load_model() if result["success"]: st.session_state.model_loaded = True add_log(result["message"], "success") st.success(result["message"]) st.rerun() else: st.error(result.get("message", "Failed to load model")) st.markdown('
', unsafe_allow_html=True) # ---- BOT STATS ---- st.markdown(f"""
๐Ÿ“Š Bot Stats
{st.session_state.total_dms_replied} DMs Replied
{st.session_state.total_comments_replied} Comments
{len(st.session_state.activity_log)} Actions
""", unsafe_allow_html=True) # ---- QUICK CONTROLS ---- st.markdown('
', unsafe_allow_html=True) st.markdown('
โšก Quick Controls
', unsafe_allow_html=True) col1, col2 = st.columns(2) with col1: auto_dm = st.checkbox("๐Ÿ’Œ Auto DM", value=st.session_state.auto_dm_enabled, key="q_dm") st.session_state.auto_dm_enabled = auto_dm with col2: auto_comment = st.checkbox("๐Ÿ’ฌ Auto Comment", value=st.session_state.auto_comment_enabled, key="q_comment") st.session_state.auto_comment_enabled = auto_comment st.markdown("
", unsafe_allow_html=True) # ---- PROMPT PREVIEW ---- current_prompt = st.session_state.system_prompt or DEFAULT_SYSTEM_PROMPT prompt_preview = current_prompt[:80] + "..." if len(current_prompt) > 80 else current_prompt prompt_label = "Custom" if st.session_state.system_prompt else "Default" st.markdown(f"""
๐Ÿง  AI Prompt ({prompt_label})
{prompt_preview}

โš™๏ธ Settings mein jaake change karo

""", unsafe_allow_html=True) # ---- START / STOP BOT ---- st.markdown("
", unsafe_allow_html=True) if not st.session_state.bot_running: if st.button("๐Ÿš€ Start Bot", key="start_bot"): if not st.session_state.auto_dm_enabled and not st.session_state.auto_comment_enabled: st.error("Pehle koi feature enable karo! DM ya Comment ๐Ÿ˜ค") else: bot = get_bot_engine() # Load AI model if not loaded if not ai.is_loaded and not ai.use_fallback: with st.spinner("Loading AI model first... โณ"): ai.load_model() result = bot.start( auto_dm=st.session_state.auto_dm_enabled, auto_comment=st.session_state.auto_comment_enabled, system_prompt=st.session_state.system_prompt, ) if result["success"]: st.session_state.bot_running = True st.session_state.bot_start_time = datetime.now() st.success(result["message"]) st.rerun() else: st.error(result["message"]) else: # Running status if st.session_state.bot_start_time: uptime = datetime.now() - st.session_state.bot_start_time hours, remainder = divmod(int(uptime.total_seconds()), 3600) minutes, seconds = divmod(remainder, 60) st.markdown(f"""
๐ŸŸข Bot is running! Uptime: {hours}h {minutes}m {seconds}s
Checking every 2-3 minutes โ€ข 30-60s delay between actions
""", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) if st.button("โน๏ธ Stop Bot", key="stop_bot"): bot = get_bot_engine() result = bot.stop() st.session_state.bot_running = False st.session_state.bot_start_time = None st.info(result["message"]) st.rerun() st.markdown('
', unsafe_allow_html=True) # ---- TEST AI REPLY ---- with st.expander("๐Ÿงช Test AI Reply"): test_msg = st.text_input("Test message:", placeholder="hi kaise ho?", key="test_msg") test_type = st.selectbox("Type:", ["dm", "comment"], key="test_type") if st.button("Generate Reply", key="test_gen"): if test_msg: with st.spinner("Generating... ๐Ÿง "): result = ai.generate_reply( message=test_msg, system_prompt=st.session_state.system_prompt, message_type=test_type, ) st.markdown(f"""
Reply: {result['reply']}
Method: {result['method']}
""", unsafe_allow_html=True) # ---- RECENT ACTIVITY ---- if st.session_state.activity_log: st.markdown('
', unsafe_allow_html=True) st.markdown('
๐Ÿ“œ Recent Activity
', unsafe_allow_html=True) log_html = '
' for log in st.session_state.activity_log[:5]: tc = {"success": "log-success", "error": "log-error", "info": "log-info", "warning": "log-warning", "dm": "log-success", "comment": "log-info", "bot": "log-warning"}.get(log['type'], 'log-info') log_html += f'
[{log["time"]}]{log["message"]}
' log_html += '
' st.markdown(log_html, unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # ---- LOGOUT ---- st.markdown("
", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) if st.button("๐Ÿšช Logout", key="logout_btn"): bot = get_bot_engine() if bot.is_running: bot.stop() handler.logout() for key in list(st.session_state.keys()): del st.session_state[key] st.rerun() st.markdown('
', unsafe_allow_html=True) # ---- AUTO REFRESH (when bot running) ---- if st.session_state.bot_running: time.sleep(0.1) st.markdown(""" """, unsafe_allow_html=True) # ============================================================ # SETTINGS PAGE # ============================================================ def render_settings(): if st.button("โ† Back", key="back_settings"): st.session_state.current_page = "dashboard" st.rerun() st.markdown("""

โš™๏ธ Settings

Bot ko customize karo apne hisab se

""", unsafe_allow_html=True) # ---- AI PROMPT ---- st.markdown('
', unsafe_allow_html=True) st.markdown('
๐Ÿง  AI Personality Prompt
', unsafe_allow_html=True) st.markdown("""
๐Ÿ’ก AI ko batao kaisi baat kare. Kuch nahi likhogi toh default use hoga (cute ladki jo Hinglish mein baat karti hai). Apna khud ka prompt bhi likh sakti ho!
""", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) if st.button("๐Ÿ“‹ Default Prompt Load Karo", key="load_default"): st.session_state.system_prompt = DEFAULT_SYSTEM_PROMPT st.rerun() st.markdown('
', unsafe_allow_html=True) prompt_input = st.text_area( "Prompt", value=st.session_state.system_prompt or "", placeholder="Custom prompt yahan likho...\n\nJaise: 'Tu ek cool ladki hai jo Hinglish mein baat karti hai...'\n\nKhali chhodogi toh default prompt chalega ๐Ÿ˜Š", height=200, key="prompt_area", label_visibility="collapsed", ) st.markdown("
", unsafe_allow_html=True) # ---- FEATURES ---- st.markdown('
', unsafe_allow_html=True) st.markdown('
๐ŸŽ›๏ธ Features
', unsafe_allow_html=True) st.markdown('
๐Ÿ’Œ Auto DM Reply
', unsafe_allow_html=True) auto_dm = st.checkbox("Enable DM Reply", value=st.session_state.auto_dm_enabled, key="s_dm", label_visibility="collapsed") st.markdown('
๐Ÿ’ฌ Auto Comment Reply
', unsafe_allow_html=True) auto_comment = st.checkbox("Enable Comment Reply", value=st.session_state.auto_comment_enabled, key="s_comment", label_visibility="collapsed") st.markdown("
", unsafe_allow_html=True) # ---- AI MODEL INFO ---- ai = get_ai_engine() ai_status = ai.get_status() st.markdown('
', unsafe_allow_html=True) st.markdown('
๐Ÿฆ™ AI Model Info
', unsafe_allow_html=True) st.markdown(f"""
๐Ÿ“ฆ Model: {MODEL_CONFIG['model_name'].split('/')[-1]}
๐Ÿ’ป Device: {ai_status['device'].upper()}
๐Ÿ”ง Quantization: 4-bit (NF4)
๐Ÿ“Š Status: {'โœ… Loaded' if ai_status['model_loaded'] else 'โšก Fallback Mode' if ai_status['fallback_mode'] else 'โŒ Not Loaded'}
{'๐ŸŽฎ GPU: ' + ai_status.get('gpu_name', 'N/A') + '
' if ai_status.get('gpu_name') else ''} {'๐Ÿ’พ VRAM Used: ' + ai_status.get('gpu_memory_allocated', 'N/A') + '' if ai_status.get('gpu_memory_allocated') else ''}
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # ---- SAFETY SETTINGS ---- st.markdown('
', unsafe_allow_html=True) st.markdown('
๐Ÿ›ก๏ธ Safety (Anti-Ban)
', unsafe_allow_html=True) st.markdown(f"""
โฑ๏ธ Action delay: {BOT_CONFIG['action_delay_min']}-{BOT_CONFIG['action_delay_max']}s
๐Ÿ”„ Check interval: {BOT_CONFIG['check_interval_min']//60}-{BOT_CONFIG['check_interval_max']//60} min
๐Ÿ“Š Max actions/hour: {BOT_CONFIG['max_actions_per_hour']}
๐Ÿ”’ Session expiry: {BOT_CONFIG['session_expiry_days']} days
""", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) # ---- SAVE ---- st.markdown("
", unsafe_allow_html=True) if st.button("๐Ÿ’พ Save & Apply", key="save_settings"): st.session_state.system_prompt = prompt_input.strip() if prompt_input.strip() else "" st.session_state.auto_dm_enabled = auto_dm st.session_state.auto_comment_enabled = auto_comment # Update running bot settings bot = get_bot_engine() if bot.is_running: bot.update_settings( auto_dm=auto_dm, auto_comment=auto_comment, system_prompt=st.session_state.system_prompt, ) status = "Custom prompt saved โœ๏ธ" if st.session_state.system_prompt else "Default prompt active ๐Ÿ“‹" add_log(f"Settings saved! {status}", "success") st.success(f"Saved! {status}") time.sleep(1) st.session_state.current_page = "dashboard" st.rerun() # ============================================================ # LOGS PAGE # ============================================================ def render_logs(): if st.button("โ† Back", key="back_logs"): st.session_state.current_page = "dashboard" st.rerun() st.markdown("""

๐Ÿ“‹ Activity Logs

Bot ki saari activity yahan hai

""", unsafe_allow_html=True) if not st.session_state.activity_log: st.markdown("""

๐Ÿ“ญ

Koi activity nahi hui abhi tak. Bot start karo!

""", unsafe_allow_html=True) else: # Filter tabs tab1, tab2, tab3, tab4 = st.tabs(["๐Ÿ“‹ All", "๐Ÿ’Œ DMs", "๐Ÿ’ฌ Comments", "โŒ Errors"]) def show_logs(logs): if not logs: st.markdown('

Kuch nahi hai yahan ๐Ÿ“ญ

', unsafe_allow_html=True) return log_html = '
' for log in logs: tc = {"success": "log-success", "error": "log-error", "info": "log-info", "warning": "log-warning", "dm": "log-success", "comment": "log-info", "bot": "log-warning"}.get(log['type'], 'log-info') log_html += f'
[{log["time"]}]{log["message"]}
' log_html += '
' st.markdown(log_html, unsafe_allow_html=True) with tab1: show_logs(st.session_state.activity_log) with tab2: dm_logs = [l for l in st.session_state.activity_log if l['type'] == 'dm'] show_logs(dm_logs) with tab3: comment_logs = [l for l in st.session_state.activity_log if l['type'] == 'comment'] show_logs(comment_logs) with tab4: error_logs = [l for l in st.session_state.activity_log if l['type'] == 'error'] show_logs(error_logs) st.markdown("
", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) if st.button("๐Ÿ—‘๏ธ Clear All Logs", key="clear_logs"): st.session_state.activity_log = [] st.rerun() st.markdown('
', unsafe_allow_html=True) st.markdown(f'

Total: {len(st.session_state.activity_log)} entries โ€ข Max 100

', unsafe_allow_html=True) # ============================================================ # MAIN ROUTER # ============================================================ def main(): if not st.session_state.logged_in: render_login_page() else: page = st.session_state.current_page if page == "settings": render_settings() elif page == "logs": render_logs() else: render_dashboard() st.markdown("""

Made with ๐Ÿ’• โ€ข InstaBot AI v1.0 โ€ข Powered by Llama 3.1 ๐Ÿฆ™

""", unsafe_allow_html=True) if __name__ == "__main__": main()