csschatbot / app.py
muhammadharis222's picture
Create app.py
661d930 verified
import os
import gradio as gr
from google import genai
# Load Gemini API key (set this in your Hugging Face Space Secrets)
API_KEY = os.environ.get("GEMINI_API_KEY")
if not API_KEY:
raise RuntimeError("Missing GEMINI_API_KEY. Set it in Space Secrets.")
client = genai.Client(api_key=API_KEY)
MODEL = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash")
def call_gemini(prompt: str) -> str:
"""Call Gemini and return model response text."""
try:
response = client.models.generate_content(model=MODEL, contents=prompt)
return getattr(response, "text", str(response))
except Exception as e:
return f"[Error calling Gemini API: {e}]"
def chat_turn(user_message: str, history: list):
"""Handle a single user chat turn (Gradio messages format)."""
if history is None:
history = []
user_message = user_message.strip()
if not user_message:
return history, history
history.append({"role": "user", "content": user_message})
reply = call_gemini(user_message)
history.append({"role": "assistant", "content": reply})
return history, history
def clear_chat():
return [], []
with gr.Blocks(
title="Muhammad Haris Chatbot",
css="""
body {background: linear-gradient(135deg, #e0f7fa, #e1bee7);}
#chatbot .user {
background-color: #0288d1 !important;
color: white !important;
border-radius: 16px !important;
padding: 10px !important;
}
#chatbot .assistant {
background-color: #ffffff !important;
border: 1px solid #ccc !important;
border-radius: 16px !important;
padding: 10px !important;
}
#title {
text-align: center;
font-size: 2em;
font-weight: bold;
color: #4a148c;
margin-bottom: 20px;
text-shadow: 1px 1px 2px #aaa;
}
#footer {
text-align: center;
font-size: 0.9em;
color: #555;
margin-top: 15px;
}
""",
) as demo:
gr.HTML('<div id="title">🤖 Muhammad Haris Chatbot</div>')
chatbot = gr.Chatbot(label="", type="messages", elem_id="chatbot")
state = gr.State([])
with gr.Row():
txt = gr.Textbox(
show_label=False,
placeholder="Type your message and press Enter...",
lines=1,
scale=9,
)
send = gr.Button("Send", scale=1)
txt.submit(fn=chat_turn, inputs=[txt, state], outputs=[chatbot, state])
send.click(fn=chat_turn, inputs=[txt, state], outputs=[chatbot, state])
gr.Button("Clear").click(fn=clear_chat, inputs=None, outputs=[chatbot, state])
gr.HTML('<div id="footer">Powered by Google Gemini · Built by Muhammad Haris</div>')
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))