File size: 3,485 Bytes
ec942ed
 
 
 
 
 
 
 
 
 
 
 
c7c9473
ec942ed
c7c9473
ec942ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7c9473
 
 
ec942ed
 
 
 
 
 
 
 
c7c9473
ec942ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6fb6791
c7c9473
ec942ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7c9473
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import gradio as gr
import random
import os
from openai import OpenAI

# --- Configuration ---
client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ.get("OPENROUTER_API_KEY"),
)

REFERER_HEADER = "https://alphaai.org.in"
TITLE_HEADER = "AlphaAI Chatbot"
MODEL_NAME = "google/gemini-2.0-flash-exp:free"
ALPHAAI_CONTEXT = os.environ.get("ALPHAAI_CONTEXT", "")

# --- CAPTCHA Logic ---
def generate_captcha():
    a, b = random.randint(1, 9), random.randint(1, 9)
    return f"What is {a} + {b}?", a + b

# Store correct answers in-memory (for stateless apps, better use secure session)
captcha_answers = {}

# --- Chatbot Backend ---
def chat_with_llm(user_input, session_id, captcha_input):
    correct_answer = captcha_answers.get(session_id)
    if correct_answer is None:
        return "CAPTCHA not initialized properly. Please reload.", generate_new_captcha(session_id)[0]

    try:
        if int(captcha_input) != correct_answer:
            return "Incorrect CAPTCHA. Try again.", generate_new_captcha(session_id)[0]
    except ValueError:
        return "Please enter a valid number for the CAPTCHA.", generate_new_captcha(session_id)[0]

    # Prepare prompt with context
    full_prompt = f"You are Alpha AI's assistant. Use the following context to answer user questions.\n\n{ALPHAAI_CONTEXT}\n\nUser: {user_input}"

    # Make OpenRouter API call
    try:
        completion = client.chat.completions.create(
            extra_headers={
                "HTTP-Referer": REFERER_HEADER,
                "X-Title": TITLE_HEADER,
            },
            model=MODEL_NAME,
            messages=[{"role": "system", "content": ALPHAAI_CONTEXT}, {"role": "user", "content": user_input}]
        )
        response = completion.choices[0].message.content
        return response, generate_new_captcha(session_id)[0]
    except Exception as e:
        return f"Error: {str(e)}", generate_new_captcha(session_id)[0]


def generate_new_captcha(session_id):
    captcha_q, captcha_ans = generate_captcha()
    captcha_answers[session_id] = captcha_ans
    return captcha_q, captcha_ans


# --- Gradio UI ---
def start_session():
    session_id = str(random.randint(100000, 999999))
    captcha_q, _ = generate_new_captcha(session_id)
    return session_id, captcha_q

with gr.Blocks(theme=gr.themes.Base(primary_hue="blue", secondary_hue="gray", font=["Inter", "sans-serif"])) as demo:
    gr.Markdown("# 🤖 Alpha AI Assistant with CAPTCHA")
    gr.Markdown("Welcome to Alpha AI’s intelligent assistant. Please solve the CAPTCHA to continue.")

    with gr.Row():
        chatbot = gr.Chatbot()

    with gr.Row():
        user_input = gr.Textbox(label="Your Message")
        captcha_input = gr.Textbox(label="CAPTCHA Answer")

    with gr.Row():
        session_id = gr.Textbox(visible=False)
        captcha_display = gr.Textbox(label="CAPTCHA", interactive=False)
        submit_btn = gr.Button("Submit")

    def handle_submit(user_msg, sid, cap_input):
        response, new_captcha_q = chat_with_llm(user_msg, sid, cap_input)
        return [(user_msg, response)], sid, new_captcha_q

    def init_session():
        sid, cap_q = start_session()
        return sid, cap_q

    submit_btn.click(handle_submit, inputs=[user_input, session_id, captcha_input], outputs=[chatbot, session_id, captcha_display])
    demo.load(init_session, inputs=[], outputs=[session_id, captcha_display])

# Launch (required for Hugging Face Space)
demo.launch()