Ruhiin / app.py
Ruhivig65's picture
Upload 9 files
f88e716 verified
Raw History Blame Contribute Delete
39.5 kB
"""
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("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
* { font-family: 'Inter', sans-serif !important; }
.stApp {
background: linear-gradient(135deg, #0E0E1A 0%, #1A1A2E 50%, #16213E 100%);
min-height: 100vh;
}
#MainMenu, footer, header { visibility: hidden; }
.block-container {
padding-top: 1rem !important;
padding-bottom: 2rem !important;
max-width: 500px !important;
}
.app-header { text-align: center; padding: 1.5rem 0 1rem 0; }
.app-logo { font-size: 3rem; margin-bottom: 0.3rem; }
.app-title {
font-size: 1.8rem; font-weight: 800;
background: linear-gradient(135deg, #E1306C, #F77737, #FCAF45);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text; margin: 0; letter-spacing: -0.5px;
}
.app-subtitle { color: #8E8EA0; font-size: 0.85rem; margin-top: 0.3rem; font-weight: 400; }
.card {
background: rgba(26, 26, 46, 0.8); border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 16px; padding: 1.8rem; margin: 1rem 0;
backdrop-filter: blur(20px); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}
.card-glow {
background: rgba(26, 26, 46, 0.9); border: 1px solid rgba(225, 48, 108, 0.2);
border-radius: 16px; padding: 1.8rem; margin: 1rem 0;
backdrop-filter: blur(20px); box-shadow: 0 8px 32px rgba(225, 48, 108, 0.1);
}
.card-title {
font-size: 1.1rem; font-weight: 700; color: #FAFAFA;
margin-bottom: 1.2rem; display: flex; align-items: center; gap: 0.5rem;
}
.stTextInput > div > div > input {
background: rgba(15, 15, 25, 0.8) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
border-radius: 12px !important; color: #FAFAFA !important;
padding: 0.8rem 1rem !important; font-size: 0.95rem !important;
transition: all 0.3s ease !important;
}
.stTextInput > div > div > input:focus {
border-color: #E1306C !important;
box-shadow: 0 0 0 2px rgba(225, 48, 108, 0.2) !important;
}
.stTextArea > div > div > textarea {
background: rgba(15, 15, 25, 0.8) !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
border-radius: 12px !important; color: #FAFAFA !important;
padding: 0.8rem 1rem !important; font-size: 0.9rem !important;
min-height: 120px !important; transition: all 0.3s ease !important;
}
.stTextArea > div > div > textarea:focus {
border-color: #E1306C !important;
box-shadow: 0 0 0 2px rgba(225, 48, 108, 0.2) !important;
}
.stButton > button {
width: 100% !important;
background: linear-gradient(135deg, #E1306C, #C13584, #833AB4) !important;
color: white !important; border: none !important; border-radius: 12px !important;
padding: 0.8rem 1.5rem !important; font-size: 1rem !important;
font-weight: 600 !important; letter-spacing: 0.3px !important;
transition: all 0.3s ease !important; cursor: pointer !important;
box-shadow: 0 4px 15px rgba(225, 48, 108, 0.3) !important;
}
.stButton > button:hover {
transform: translateY(-2px) !important;
box-shadow: 0 6px 25px rgba(225, 48, 108, 0.5) !important;
}
.secondary-btn .stButton > button {
background: rgba(255, 255, 255, 0.08) !important;
border: 1px solid rgba(255, 255, 255, 0.15) !important;
box-shadow: none !important;
}
.secondary-btn .stButton > button:hover {
background: rgba(255, 255, 255, 0.12) !important;
}
.danger-btn .stButton > button {
background: linear-gradient(135deg, #dc3545, #c82333) !important;
box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3) !important;
}
.success-btn .stButton > button {
background: linear-gradient(135deg, #28a745, #20c997) !important;
box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3) !important;
}
.status-badge {
display: inline-flex; align-items: center; gap: 0.4rem;
padding: 0.35rem 0.8rem; border-radius: 20px; font-size: 0.8rem; font-weight: 600;
}
.status-online {
background: rgba(40, 167, 69, 0.15); color: #51CF66;
border: 1px solid rgba(40, 167, 69, 0.3);
}
.status-offline {
background: rgba(220, 53, 69, 0.15); color: #FF6B6B;
border: 1px solid rgba(220, 53, 69, 0.3);
}
.profile-section {
display: flex; align-items: center; gap: 1rem; padding: 1rem;
background: rgba(15, 15, 25, 0.5); border-radius: 12px; margin-bottom: 1rem;
}
.profile-avatar {
width: 55px; height: 55px; border-radius: 50%;
background: linear-gradient(135deg, #E1306C, #F77737);
display: flex; align-items: center; justify-content: center;
font-size: 1.5rem; flex-shrink: 0;
}
.profile-name { font-size: 1.05rem; font-weight: 700; color: #FAFAFA; margin: 0; }
.profile-username { font-size: 0.85rem; color: #8E8EA0; margin: 0; }
.stats-row {
display: flex; justify-content: space-around; padding: 1rem 0;
margin: 0.8rem 0; border-top: 1px solid rgba(255, 255, 255, 0.06);
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
.stat-item { text-align: center; }
.stat-number { font-size: 1.3rem; font-weight: 700; color: #FAFAFA; display: block; }
.stat-label { font-size: 0.7rem; color: #8E8EA0; text-transform: uppercase; letter-spacing: 0.5px; }
.log-container {
background: rgba(10, 10, 18, 0.9); border: 1px solid rgba(255, 255, 255, 0.05);
border-radius: 12px; padding: 1rem; max-height: 300px; overflow-y: auto;
font-family: 'JetBrains Mono', monospace !important; font-size: 0.78rem; line-height: 1.6;
}
.log-entry { padding: 0.3rem 0; border-bottom: 1px solid rgba(255, 255, 255, 0.03); }
.log-time { color: #555; margin-right: 0.5rem; }
.log-success { color: #51CF66; }
.log-error { color: #FF6B6B; }
.log-info { color: #74C0FC; }
.log-warning { color: #FFD43B; }
.feature-card {
background: rgba(15, 15, 25, 0.5); border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 12px; padding: 1rem 1.2rem; margin: 0.6rem 0;
}
.custom-divider {
height: 1px;
background: linear-gradient(90deg, transparent, rgba(225, 48, 108, 0.3), transparent);
margin: 1.5rem 0;
}
.alert-box {
padding: 0.8rem 1rem; border-radius: 10px; font-size: 0.85rem;
margin: 0.8rem 0; line-height: 1.5;
}
.alert-info {
background: rgba(58, 134, 255, 0.1); border: 1px solid rgba(58, 134, 255, 0.2);
color: #74C0FC;
}
.alert-warning {
background: rgba(255, 193, 7, 0.1); border: 1px solid rgba(255, 193, 7, 0.2);
color: #FFD43B;
}
.alert-success {
background: rgba(40, 167, 69, 0.1); border: 1px solid rgba(40, 167, 69, 0.2);
color: #51CF66;
}
.alert-error {
background: rgba(220, 53, 69, 0.1); border: 1px solid rgba(220, 53, 69, 0.2);
color: #FF6B6B;
}
.ai-status-card {
background: rgba(15, 15, 25, 0.5); border: 1px solid rgba(131, 58, 180, 0.2);
border-radius: 12px; padding: 1rem; margin: 0.5rem 0;
}
@keyframes pulse {
0%, 100% { opacity: 1; }
50% { opacity: 0.5; }
}
.pulse { animation: pulse 2s ease-in-out infinite; }
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.animate-in { animation: fadeIn 0.5s ease forwards; }
@media (max-width: 768px) {
.block-container { padding-left: 1rem !important; padding-right: 1rem !important; }
.app-title { font-size: 1.5rem; }
.card, .card-glow { padding: 1.3rem; margin: 0.8rem 0; }
.stat-number { font-size: 1.1rem; }
}
::-webkit-scrollbar { width: 4px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: rgba(225, 48, 108, 0.3); border-radius: 4px; }
.stTabs [data-baseweb="tab-list"] {
gap: 0px; background: rgba(15, 15, 25, 0.5); border-radius: 12px; padding: 4px;
}
.stTabs [data-baseweb="tab"] { border-radius: 10px; color: #8E8EA0; font-weight: 600; font-size: 0.85rem; }
.stTabs [aria-selected="true"] { background: linear-gradient(135deg, #E1306C, #833AB4) !important; color: white !important; }
</style>
""", 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("""
<div class="app-header animate-in">
<div class="app-logo">๐Ÿค–โœจ</div>
<h1 class="app-title">InstaBot AI</h1>
<p class="app-subtitle">Smart Auto-Reply for Instagram โ€ข Powered by Llama 3.1</p>
</div>
""", unsafe_allow_html=True)
# ============================================================
# LOGIN PAGE
# ============================================================
def render_login_page():
render_header()
st.markdown('<div class="card-glow animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐Ÿ” Instagram Login</div>', unsafe_allow_html=True)
st.markdown("""
<div class="alert-box alert-info">
๐Ÿ’ก Tera login info sirf is device pe save hoga. Hum kuch store nahi karte server pe.
</div>
""", 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("</div>", unsafe_allow_html=True)
# 2FA Section
if st.session_state.show_2fa:
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐Ÿ” Two-Factor Auth</div>', unsafe_allow_html=True)
st.markdown('<div class="alert-box alert-warning">Authenticator app ya SMS se 2FA code daalo.</div>', 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("</div>", unsafe_allow_html=True)
# Challenge Section
if st.session_state.show_challenge:
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">โš ๏ธ Security Challenge</div>', unsafe_allow_html=True)
st.markdown('<div class="alert-box alert-warning">Email/phone pe aaya verification code daalo.</div>', 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("</div>", 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'<div class="alert-box alert-error">{st.session_state.login_error}</div>', unsafe_allow_html=True)
st.markdown("""
<div class="custom-divider"></div>
<div style="text-align: center;">
<p style="color: #555; font-size: 0.75rem;">
๐Ÿ”’ Credentials sirf login ke liye use hote hain. Kuch store nahi hota.
</p>
</div>
""", 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('<p style="text-align: center; font-size: 1.1rem; font-weight: 700; background: linear-gradient(135deg, #E1306C, #F77737); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin: 0.5rem 0;">InstaBot AI ๐Ÿค–</p>', 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"""
<div class="card animate-in">
<div class="profile-section">
<div class="profile-avatar">{first_letter}</div>
<div style="flex: 1;">
<p class="profile-name">{fullname_display}</p>
<p class="profile-username">@{username_display}</p>
</div>
<span class="status-badge {'status-online' if bot_status else 'status-offline'}">
{'๐ŸŸข Bot ON' if bot_status else '๐Ÿ”ด Bot OFF'}
</span>
</div>
<div class="stats-row">
<div class="stat-item">
<span class="stat-number">{format_number(profile.get('follower_count', 0))}</span>
<span class="stat-label">Followers</span>
</div>
<div class="stat-item">
<span class="stat-number">{format_number(profile.get('following_count', 0))}</span>
<span class="stat-label">Following</span>
</div>
<div class="stat-item">
<span class="stat-number">{format_number(profile.get('media_count', 0))}</span>
<span class="stat-label">Posts</span>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# ---- AI MODEL STATUS ----
ai_status = ai.get_status()
if ai_status["model_loaded"]:
model_badge = '<span class="status-badge status-online">๐Ÿง  AI Ready</span>'
elif ai_status["fallback_mode"]:
model_badge = '<span class="status-badge" style="background: rgba(255,193,7,0.15); color: #FFD43B; border: 1px solid rgba(255,193,7,0.3);">โšก Smart Fallback</span>'
else:
model_badge = '<span class="status-badge status-offline">โŒ Not Loaded</span>'
st.markdown(f"""
<div class="ai-status-card">
<div style="display: flex; align-items: center; justify-content: space-between;">
<div>
<p style="font-size: 0.9rem; font-weight: 600; color: #FAFAFA; margin: 0;">๐Ÿฆ™ AI Engine</p>
<p style="font-size: 0.75rem; color: #8E8EA0; margin: 0.2rem 0 0 0;">
{ai_status.get('gpu_name', ai_status['device'].upper())}
{'โ€ข ' + ai_status.get('gpu_memory_allocated', '') if ai_status.get('gpu_memory_allocated') else ''}
</p>
</div>
{model_badge}
</div>
</div>
""", unsafe_allow_html=True)
# Load Model Button (if not loaded)
if not ai_status["model_loaded"] and not ai_status["fallback_mode"]:
st.markdown('<div class="success-btn">', 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('</div>', unsafe_allow_html=True)
# ---- BOT STATS ----
st.markdown(f"""
<div class="card animate-in">
<div class="card-title">๐Ÿ“Š Bot Stats</div>
<div class="stats-row">
<div class="stat-item">
<span class="stat-number">{st.session_state.total_dms_replied}</span>
<span class="stat-label">DMs Replied</span>
</div>
<div class="stat-item">
<span class="stat-number">{st.session_state.total_comments_replied}</span>
<span class="stat-label">Comments</span>
</div>
<div class="stat-item">
<span class="stat-number">{len(st.session_state.activity_log)}</span>
<span class="stat-label">Actions</span>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# ---- QUICK CONTROLS ----
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">โšก Quick Controls</div>', 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("</div>", 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"""
<div class="card animate-in">
<div class="card-title">๐Ÿง  AI Prompt ({prompt_label})</div>
<div style="background: rgba(10,10,18,0.6); border-radius: 8px; padding: 0.8rem;
font-size: 0.82rem; color: #8E8EA0; line-height: 1.5;">
{prompt_preview}
</div>
<p style="font-size: 0.75rem; color: #555; margin-top: 0.5rem; text-align: right;">
โš™๏ธ Settings mein jaake change karo
</p>
</div>
""", unsafe_allow_html=True)
# ---- START / STOP BOT ----
st.markdown("<br>", 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"""
<div class="alert-box alert-success">
<span class="pulse">๐ŸŸข</span> Bot is running!
Uptime: {hours}h {minutes}m {seconds}s
<br><span style="font-size: 0.78rem; color: #8E8EA0;">
Checking every 2-3 minutes โ€ข 30-60s delay between actions</span>
</div>
""", unsafe_allow_html=True)
st.markdown('<div class="danger-btn">', 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('</div>', 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"""
<div class="alert-box alert-success">
<strong>Reply:</strong> {result['reply']}<br>
<span style="font-size: 0.75rem; color: #8E8EA0;">Method: {result['method']}</span>
</div>
""", unsafe_allow_html=True)
# ---- RECENT ACTIVITY ----
if st.session_state.activity_log:
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐Ÿ“œ Recent Activity</div>', unsafe_allow_html=True)
log_html = '<div class="log-container">'
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'<div class="log-entry"><span class="log-time">[{log["time"]}]</span><span class="{tc}">{log["message"]}</span></div>'
log_html += '</div>'
st.markdown(log_html, unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)
# ---- LOGOUT ----
st.markdown("<br>", unsafe_allow_html=True)
st.markdown('<div class="secondary-btn">', 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('</div>', unsafe_allow_html=True)
# ---- AUTO REFRESH (when bot running) ----
if st.session_state.bot_running:
time.sleep(0.1)
st.markdown("""
<script>
setTimeout(function() { window.location.reload(); }, 30000);
</script>
""", 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("""
<div class="app-header">
<h1 class="app-title" style="font-size: 1.5rem;">โš™๏ธ Settings</h1>
<p class="app-subtitle">Bot ko customize karo apne hisab se</p>
</div>
""", unsafe_allow_html=True)
# ---- AI PROMPT ----
st.markdown('<div class="card-glow animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐Ÿง  AI Personality Prompt</div>', unsafe_allow_html=True)
st.markdown("""
<div class="alert-box alert-info">
๐Ÿ’ก 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!
</div>
""", unsafe_allow_html=True)
st.markdown('<div class="secondary-btn">', 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('</div>', 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("</div>", unsafe_allow_html=True)
# ---- FEATURES ----
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐ŸŽ›๏ธ Features</div>', unsafe_allow_html=True)
st.markdown('<div class="feature-card"><span style="font-size:1.3rem;">๐Ÿ’Œ</span> <span style="color:#FAFAFA; font-weight:600;">Auto DM Reply</span></div>', 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('<div class="feature-card"><span style="font-size:1.3rem;">๐Ÿ’ฌ</span> <span style="color:#FAFAFA; font-weight:600;">Auto Comment Reply</span></div>', 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("</div>", unsafe_allow_html=True)
# ---- AI MODEL INFO ----
ai = get_ai_engine()
ai_status = ai.get_status()
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐Ÿฆ™ AI Model Info</div>', unsafe_allow_html=True)
st.markdown(f"""
<div style="font-size: 0.85rem; color: #8E8EA0; line-height: 2;">
๐Ÿ“ฆ Model: <strong style="color: #FAFAFA;">{MODEL_CONFIG['model_name'].split('/')[-1]}</strong><br>
๐Ÿ’ป Device: <strong style="color: #FAFAFA;">{ai_status['device'].upper()}</strong><br>
๐Ÿ”ง Quantization: <strong style="color: #FAFAFA;">4-bit (NF4)</strong><br>
๐Ÿ“Š Status: <strong style="color: {'#51CF66' if ai_status['model_loaded'] else '#FFD43B' if ai_status['fallback_mode'] else '#FF6B6B'};">
{'โœ… Loaded' if ai_status['model_loaded'] else 'โšก Fallback Mode' if ai_status['fallback_mode'] else 'โŒ Not Loaded'}</strong><br>
{'๐ŸŽฎ GPU: <strong style="color: #FAFAFA;">' + ai_status.get('gpu_name', 'N/A') + '</strong><br>' if ai_status.get('gpu_name') else ''}
{'๐Ÿ’พ VRAM Used: <strong style="color: #FAFAFA;">' + ai_status.get('gpu_memory_allocated', 'N/A') + '</strong>' if ai_status.get('gpu_memory_allocated') else ''}
</div>
""", unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)
# ---- SAFETY SETTINGS ----
st.markdown('<div class="card animate-in">', unsafe_allow_html=True)
st.markdown('<div class="card-title">๐Ÿ›ก๏ธ Safety (Anti-Ban)</div>', unsafe_allow_html=True)
st.markdown(f"""
<div style="font-size: 0.85rem; color: #8E8EA0; line-height: 2;">
โฑ๏ธ Action delay: <strong style="color: #FAFAFA;">{BOT_CONFIG['action_delay_min']}-{BOT_CONFIG['action_delay_max']}s</strong><br>
๐Ÿ”„ Check interval: <strong style="color: #FAFAFA;">{BOT_CONFIG['check_interval_min']//60}-{BOT_CONFIG['check_interval_max']//60} min</strong><br>
๐Ÿ“Š Max actions/hour: <strong style="color: #FAFAFA;">{BOT_CONFIG['max_actions_per_hour']}</strong><br>
๐Ÿ”’ Session expiry: <strong style="color: #FAFAFA;">{BOT_CONFIG['session_expiry_days']} days</strong>
</div>
""", unsafe_allow_html=True)
st.markdown("</div>", unsafe_allow_html=True)
# ---- SAVE ----
st.markdown("<br>", 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("""
<div class="app-header">
<h1 class="app-title" style="font-size: 1.5rem;">๐Ÿ“‹ Activity Logs</h1>
<p class="app-subtitle">Bot ki saari activity yahan hai</p>
</div>
""", unsafe_allow_html=True)
if not st.session_state.activity_log:
st.markdown("""
<div class="card animate-in" style="text-align: center; padding: 2rem;">
<p style="font-size: 2rem;">๐Ÿ“ญ</p>
<p style="color: #8E8EA0;">Koi activity nahi hui abhi tak. Bot start karo!</p>
</div>
""", 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('<p style="color: #8E8EA0; text-align: center; padding: 1rem;">Kuch nahi hai yahan ๐Ÿ“ญ</p>', unsafe_allow_html=True)
return
log_html = '<div class="log-container" style="max-height: 500px;">'
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'<div class="log-entry"><span class="log-time">[{log["time"]}]</span><span class="{tc}">{log["message"]}</span></div>'
log_html += '</div>'
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("<br>", unsafe_allow_html=True)
st.markdown('<div class="secondary-btn">', unsafe_allow_html=True)
if st.button("๐Ÿ—‘๏ธ Clear All Logs", key="clear_logs"):
st.session_state.activity_log = []
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
st.markdown(f'<p style="text-align: center; color: #555; font-size: 0.75rem; margin-top: 0.5rem;">Total: {len(st.session_state.activity_log)} entries โ€ข Max 100</p>', 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("""
<div style="text-align: center; padding: 2rem 0 1rem 0;">
<p style="color: #333; font-size: 0.7rem;">
Made with ๐Ÿ’• โ€ข InstaBot AI v1.0 โ€ข Powered by Llama 3.1 ๐Ÿฆ™
</p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()