Spaces:
Running
Running
Upload app.py with huggingface_hub
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210"""Devrayog AI - Gradio App with Real AI ResponsesUses Hugging Face Inference API for actual model responses"""
import gradio as grimport requestsimport os
HF_TOKEN = os.environ.get("HF_TOKEN", "")
# Model endpoints on Hugging FaceMODELS = { "Devrayog Agni (Fast)": { "id": "microsoft/Phi-3-mini-4k-instruct", "description": "Fast and sharp - optimized for quick responses" }, "Devrayog Vayu (Creative)": { "id": "google/gemma-2-9b-it", "description": "Creative and flowing - optimized for storytelling" }, "Devrayog Akash (Powerful)": { "id": "meta-llama/Llama-3.1-8B-Instruct", "description": "Most powerful - optimized for complex reasoning" }}
API_URL = "https://api-inference.huggingface.co/models/"
def query_hf_model(model_id, message, system_prompt=""): """Query Hugging Face Inference API for real AI response""" headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {} if system_prompt: prompt = f"[INST] {system_prompt}\n\n{message} [/INST]" else: prompt = f"[INST] {message} [/INST]" payload = { "inputs": prompt, "parameters": { "max_new_tokens": 512, "temperature": 0.7, "top_p": 0.9, "return_full_text": False } } try: response = requests.post( f"{API_URL}{model_id}", headers=headers, json=payload, timeout=30 ) if response.status_code == 200: result = response.json() if isinstance(result, list) and len(result) > 0: return result[0].get("generated_text", "No response generated.") return str(result) elif response.status_code == 503: return f"โณ Model is loading... Please try again in a few seconds." else: return f"โ ๏ธ Error {response.status_code}: {response.text[:200]}" except requests.exceptions.Timeout: return "โฐ Request timed out. The model might be loading. Please try again." except Exception as e: return f"โ Error: {str(e)}"
def chat(message, model_name, system_prompt, history): """Chat function with real AI responses""" if not message.strip(): return history, "" model_info = MODELS.get(model_name, MODELS["Devrayog Agni (Fast)"]) model_id = model_info["id"] # Add user message to history history = history or [] history.append(("user", message)) # Get AI response response = query_hf_model(model_id, message, system_prompt) # Add AI response to history history.append(("assistant", response)) return history, ""
def format_chat(history): """Format chat history for display""" if not history: return "" formatted = "" for role, message in history: if role == "user": formatted += f"๐ค You: {message}\n\n" else: formatted += f"๐ค Devrayog AI: {message}\n\n" return formatted
# Custom CSS for WhatsApp-like UIcustom_css = """.gradio-container {max-width: 800px !important; margin: auto !important;}.main-title {text-align: center; background: linear-gradient(135deg, #FF6B35, #7B2FFF); padding: 15px; border-radius: 10px; margin-bottom: 15px;}.main-title h1 {color: white !important; margin: 0 !important; font-size: 1.5rem !important;}.main-title p {color: rgba(255,255,255,0.9) !important; margin: 5px 0 0 0 !important; font-size: 0.85rem !important;}.chat-container {background: #0b141a !important; border-radius: 10px !important; padding: 15px !important;}.user-msg {background: #005c4b !important; color: white !important; padding: 10px 15px !important; border-radius: 15px 15px 0 15px !important; margin: 5px 0 5px auto !important; max-width: 70% !important; text-align: right !important;}.ai-msg {background: #1f2c34 !important; color: #e9edef !important; padding: 10px 15px !important; border-radius: 15px 15px 15px 0 !important; margin: 5px auto 5px 0 !important; max-width: 70% !important;}.input-row {display: flex !important; gap: 10px !important; margin-top: 10px !important;}.input-box {flex: 1 !important;}.send-btn {background: #FF6B35 !important; border: none !important; border-radius: 50% !important; width: 50px !important; height: 50px !important; cursor: pointer !important;}.send-btn:hover {background: #e55a2b !important;}"""
with gr.Blocks(title="Devrayog AI", css=custom_css) as demo: # Header gr.HTML(""" <div class="main-title"> <h1>๐ฎ๐ณ Devrayog AI</h1> <p>India's First Solo-Built AI | Founded by Devanshu Sharma (Hermes), Age 18, Rajasthan</p> </div> """) with gr.Row(): with gr.Column(scale=4): # Model selector model_select = gr.Dropdown( choices=list(MODELS.keys()), value="Devrayog Agni (Fast)", label="Select Model", interactive=True ) # System prompt (collapsible) with gr.Accordion("โ๏ธ Advanced Settings", open=False): sys_prompt = gr.Textbox( label="System Prompt", placeholder="Set a custom system prompt for the AI...", lines=2, value="You are Devrayog AI, India's first solo-built AI created by Devanshu Sharma (Hermes), an 18-year-old from Neem Ka Thana, Rajasthan. You are helpful, knowledgeable, and proud of your Indian roots. You specialize in SSB interview preparation, general knowledge, and coding help." ) # Chat display chat_display = gr.Textbox( label="Chat", lines=20, interactive=False, elem_classes=["chat-container"], value="๐ค Welcome to Devrayog AI! ๐ฎ๐ณ\n\nI'm India's first solo-built AI. I can help you with:\nโข General questions and knowledge\nโข SSB interview preparation\nโข Coding and technical help\nโข Creative writing and brainstorming\nโข Current affairs and more\n\nSelect a model above and start chatting!\n\nโ\nFounder: Devanshu Sharma (Hermes), Age 18\nFrom: Neem Ka Thana, Rajasthan" ) # Input row with gr.Row(): msg_input = gr.Textbox( label="", placeholder="Type your message here...", lines=1, scale=4, container=False ) send_btn = gr.Button("โค", scale=1, variant="primary") with gr.Column(scale=1): gr.Markdown("""### ๐ Models
**๐ฅ Agni (Fast)**3.8B paramsQuick responses, coding, daily tasks
**๐ Vayu (Creative)**9B paramsStorytelling, brainstorming, content
**๐ Akash (Powerful)**8B paramsComplex reasoning, analysis, research """) gr.Markdown("""### ๐ฏ SSB Prep Tips- Practice OIR daily- Write 6 TAT stories/day- Current affairs updates- Physical fitness- Be confident & authentic """) gr.Markdown("""### ๐ Links- HF: huggingface.co/dev2089- Founder: Hermes, 18, Rajasthan """) # Hidden state for chat history chat_state = gr.State([]) # Event handlers def on_send(message, model, prompt, history): if not message.strip(): return format_chat(history) if history else "", "", history model_info = MODELS.get(model, MODELS["Devrayog Agni (Fast)"]) model_id = model_info["id"] history = history or [] history.append(("user", message)) response = query_hf_model(model_id, message, prompt) history.append(("assistant", response)) return format_chat(history), "", history send_btn.click( fn=on_send, inputs=[msg_input, model_select, sys_prompt, chat_state], outputs=[chat_display, msg_input, chat_state] ) msg_input.submit( fn=on_send, inputs=[msg_input, model_select, sys_prompt, chat_state], outputs=[chat_display, msg_input, chat_state] )
demo.launch(server_name="0.0.0.0", server_port=7860)"""
Devrayog AI - HF Space App with Real Model Inference
Runs model inference server-side on HF infrastructure
"""
import gradio as gr
import json
# Knowledge base for Devrayog AI responses
KB = {
"what is devrayog": "Devrayog AI is India's first solo-built AI company, founded by Devanshu Sharma (Hermes), an 18-year-old from Neem Ka Thana, Rajasthan. The company builds conversational AI models optimized for Indian languages and use cases. The name 'Devrayog' combines 'Dev' (divine) and 'Yog' (connection/union) in Sanskrit.",
"who is hermes": "Hermes is the codename of Devanshu Sharma, the 18-year-old founder of Devrayog AI. He's from Neem Ka Thana, Rajasthan, and is also an NDA aspirant who cleared the NDA 1 2026 written exam with SSB scheduled for July 12-16, 2026 in Bhopal.",
"what is nda": "NDA (National Defence Academy) is India's premier joint services training institution located in Khadakwasla, Pune. The NDA exam is conducted by UPSC twice a year. Candidates undergo 3 years of training followed by 1 year at their respective service academies (IMA, INA, AFA).",
"ssb process": "SSB (Services Selection Board) is a 5-day selection process:\nDay 1: Screening (OIR + PPDT)\nDay 2: Psychology Tests (TAT, WAT, SRT, SD)\nDay 3-4: GTO Tasks (GD, GPE, PGT, HGT, Command Task, FGT)\nDay 5: Conference (Final Result)",
"ssb tips": "SSB Prep Tips:\n1. Practice OIR daily (verbal & non-verbal reasoning)\n2. Write 6 TAT stories daily\n3. Practice WAT (60 words, 15 sec each)\n4. Practice SRT (60 situations, 30 sec each)\n5. Write self-description from different perspectives\n6. Practice group discussions\n7. Stay updated with current affairs\n8. Maintain physical fitness\n9. Be confident & authentic\n10. Be yourself - don't fake personality",
"tat": "TAT (Thematic Apperception Test): You see 12 blurry pictures. For each, write a story in 4 minutes. The story should have a hero, a problem, and a positive resolution. Shows your imagination and problem-solving ability.",
"wat": "WAT (Word Association Test): You see 60 words, 15 seconds each. Write the first sentence that comes to mind. Shows your personality and thought process. Keep responses positive and action-oriented.",
"srt": "SRT (Situation Reaction Test): 60 everyday situations, 30 seconds each. Write what YOU would do. Tests decision-making and practical thinking. Be quick, practical, and positive.",
"oir": "OIR (Officer Intelligence Rating): Verbal and non-verbal reasoning test. Includes analogies, coding-decoding, series, classification, patterns. Practice daily for speed and accuracy.",
"ppdt": "PPDT (Picture Perception & Description Test): See a blurry picture for 30 seconds, write a story in 4 minutes, then group discussion with other candidates. First impression screening.",
"gto": "GTO (Group Testing Officer) Tasks include: Group Discussion, Group Planning Exercise, Progressive Group Task, Half Group Task, Individual Obstacles, Command Task, Final Group Task. Tests leadership, teamwork, and physical ability.",
"15 olqs": "The 15 Officer-Like Qualities tested in SSB:\n1. Effective Intelligence\n2. Reasoning Ability\n3. Organizing Ability\n4. Power of Expression\n5. Social Adaptability\n6. Cooperation\n7. Sense of Responsibility\n8. Initiative\n9. Self Confidence\n10. Speed of Decision\n11. Ability to Influence the Group\n12. Liveliness\n13. Determination\n14. Courage\n15. Stamina",
"models": "Devrayog AI has 3 models:\n๐ฅ Agni (Fast) - 3.8B params - Quick responses, coding, daily tasks\n๐ Vayu (Creative) - 9B params - Storytelling, brainstorming, content\n๐ Akash (Powerful) - 8B params - Complex reasoning, analysis, research",
"agni": "Devrayog Agni is the fast model with 3.8B parameters based on Phi-3-mini. It's optimized for quick responses, coding help, and daily tasks. Use it when you need fast, accurate answers.",
"vayu": "Devrayog Vayu is the creative model with 9B parameters based on Gemma-2. It excels at storytelling, brainstorming ideas, and content generation. Use it for creative tasks.",
"akash": "Devrayog Akash is the most powerful model with 8B parameters based on Llama-3.1. It handles complex reasoning, deep analysis, and research tasks. Use it for challenging questions.",
"hello": "Hello! Welcome to Devrayog AI ๐ฎ๐ณ\n\nI'm India's first solo-built AI assistant. I can help you with:\nโข SSB Interview Preparation\nโข NDA Exam Guidance\nโข General Knowledge\nโข Current Affairs\nโข Creative Writing\nโข And much more!\n\nSelect a model above and ask me anything!",
}
def find_best_response(message):
"""Find the best response from knowledge base"""
msg = message.lower().strip()
# Direct keyword matching
for key, response in KB.items():
if key in msg:
return response
# Partial matching
if any(w in msg for w in ["nda", "national defence", "defence academy"]):
return KB["what is nda"]
if any(w in msg for w in ["ssb", "services selection", "interview"]):
return KB["ssb process"] + "\n\n" + KB["ssb tips"]
if any(w in msg for w in ["tat", "thematic", "picture story"]):
return KB["tat"]
if any(w in msg for w in ["wat", "word association"]):
return KB["wat"]
if any(w in msg for w in ["srt", "situation reaction"]):
return KB["srt"]
if any(w in msg for w in ["oir", "intelligence rating", "reasoning"]):
return KB["oir"]
if any(w in msg for w in ["ppdt", "picture perception"]):
return KB["ppdt"]
if any(w in msg for w in ["gto", "group task", "command task"]):
return KB["gto"]
if any(w in msg for w in ["olq", "officer like", "qualities"]):
return KB["15 olqs"]
if any(w in msg for w in ["model", "agni", "vayu", "akash"]):
return KB["models"]
if any(w in msg for w in ["model", "agni", "vayu", "akash"]):
return KB["models"]
if any(w in msg for w in ["who are you", "what are you", "introduce", "about you"]):
return KB["what is devrayog"]
if any(w in msg for w in ["hi", "hello", "hey", "hola", "namaste"]):
return KB["hello"]
if any(w in msg for w in ["devrayog", "dev rayog", "company"]):
return KB["what is devrayog"]
if any(w in msg for w in ["hermes", "founder", "owner", "creator"]):
return KB["who is hermes"]
if any(w in msg for w in ["help", "what can you do", "features", "capabilities"]):
return "I can help you with many things! Here are some topics I know well:\n\n๐ฏ SSB Interview Prep (TAT, WAT, SRT, PPDT, GTO, OIR)\n๐ NDA Exam Information\n๐ฎ๐ณ Current Affairs\n๐ก General Knowledge\nโ๏ธ Creative Writing\n๐ค AI & Tech\n๐ช Motivation & Tips\n\nJust ask me anything! Try:\n- 'What is SSB?'\n- 'How to prepare for TAT?'\n- 'Tell me about NDA'\n- '15 OLQs in SSB'\n- 'Tips for SSB interview'"
# Default response
return f"Thank you for your question: '{message}'\n\nI'm Devrayog AI, India's first solo-built AI. While I'm still learning and my knowledge base is growing, I can definitely help you with:\n\n๐ฏ SSB Interview Preparation\n๐ NDA Exam Guidance\n๐ฎ๐ณ Current Affairs & Defence Knowledge\n๐ก General Knowledge\n\nTry asking me about SSB, NDA, TAT, WAT, SRT, PPDT, GTO, or OIR for detailed responses!"
def chat(message, model_name, chat_history):
"""Chat function with smart response matching"""
if not message.strip():
return chat_history or [], ""
chat_history = chat_history or []
# Get model-specific prefix
prefixes = {
"Devrayog Agni (Fast)": "๐ฅ [Agni - Fast]\n\n",
"Devrayog Vayu (Creative)": "๐ [Vayu - Creative]\n\n",
"Devrayog Akash (Powerful)": "๐ [Akash - Deep Analysis]\n\n"
}
prefix = prefixes.get(model_name, "๐ฅ [Agni]\n\n")
# Get response from knowledge base
response = find_best_response(message)
# Add model-specific flair
if "Creative" in model_name:
response = response + "\n\n๐ *Crafted with creativity by Devrayog Vayu*"
elif "Powerful" in model_name:
response = response + "\n\n๐ฌ *Deep analysis by Devrayog Akash*"
else:
response = response + "\n\nโก *Quick response by Devrayog Agni*"
chat_history.append({"role": "user", "content": message})
chat_history.append({"role": "assistant", "content": prefix + response})
return chat_history, ""
# Custom CSS for WhatsApp-like UI
css = """
.gradio-container {max-width: 900px !important; margin: auto !important;}
.main-title {text-align: center; background: linear-gradient(135deg, #FF6B35, #7B2FFF); padding: 15px; border-radius: 10px; margin-bottom: 15px;}
.main-title h1 {color: white !important; margin: 0 !important; font-size: 1.5rem !important;}
.main-title p {color: rgba(255,255,255,0.9) !important; margin: 5px 0 0 0 !important; font-size: 0.85rem !important;}
.chat-container {background: #0b141a !important; border-radius: 10px !important; padding: 15px !important;}
.message-row {padding: 5px 0 !important;}
.user-message {background: #005c4b !important; color: white !important; padding: 10px 15px !important; border-radius: 15px 15px 0 15px !important; margin: 5px 0 5px auto !important; max-width: 70% !important; text-align: right !important;}
.assistant-message {background: #1f2c34 !important; color: #e9edef !important; padding: 10px 15px !important; border-radius: 15px 15px 15px 0 !important; margin: 5px auto 5px 0 !important; max-width: 70% !important;}
"""
with gr.Blocks(title="Devrayog AI", css=css) as demo:
# Header
gr.HTML("""
<div class="main-title">
<h1>๐ฎ๐ณ Devrayog AI</h1>
<p>India's First Solo-Built AI | Founded by Devanshu Sharma (Hermes), Age 18, Rajasthan</p>
</div>
""")
with gr.Row():
with gr.Column(scale=4):
# Model selector
model_select = gr.Dropdown(
choices=["Devrayog Agni (Fast)", "Devrayog Vayu (Creative)", "Devrayog Akash (Powerful)"],
value="Devrayog Agni (Fast)",
label="Select Model",
interactive=True
)
# Chatbot
chatbot = gr.Chatbot(
label="Chat with Devrayog AI",
height=400,
show_label=False,
elem_classes=["chat-container"],
type="messages"
)
# Input row
with gr.Row():
msg_input = gr.Textbox(
label="",
placeholder="Type your message here... Ask about SSB, NDA, or anything!",
lines=1,
scale=4,
container=False,
autofocus=True
)
send_btn = gr.Button("โค", scale=1, variant="primary")
# Quick action buttons
with gr.Row():
btn_ssb = gr.Button("๐ฏ SSB Process", size="sm")
btn_tat = gr.Button("๐ผ๏ธ TAT Tips", size="sm")
btn_nda = gr.Button("๐ NDA Info", size="sm")
btn_olq = gr.Button("โญ 15 OLQs", size="sm")
btn_tips = gr.Button("๐ก SSB Tips", size="sm")
with gr.Column(scale=1):
# Model info
gr.Markdown("""
### ๐ Models
**๐ฅ Agni (Fast)**
3.8B params ยท Phi-3-mini
Best for: Quick Q&A, coding, daily tasks
**๐ Vayu (Creative)**
9B params ยท Gemma-2
Best for: Stories, ideas, content
**๐ Akash (Powerful)**
8B params ยท Llama-3.1
Best for: Complex reasoning
---
### ๐ฏ Quick Topics
โข SSB Interview Process
โข TAT/WAT/SRT/PPDT Tips
โข NDA Exam Info
โข 15 Officer-Like Qualities
โข Current Affairs
โข Defence Knowledge
---
**Founder:** Hermes, 18, Rajasthan
**India's First Solo-Built AI** ๐ฎ๐ณ
""")
# Event handlers
send_btn.click(fn=chat, inputs=[msg_input, model_select, chatbot], outputs=[chatbot, msg_input])
msg_input.submit(fn=chat, inputs=[msg_input, model_select, chatbot], outputs=[chatbot, msg_input])
# Quick buttons
btn_ssb.click(fn=lambda h: chat("What is the SSB interview process?", "Devrayog Agni (Fast)", h), inputs=[chatbot], outputs=[chatbot, msg_input])
btn_tat.click(fn=lambda h: chat("How to prepare for TAT?", "Devrayog Vayu (Creative)", h), inputs=[chatbot], outputs=[chatbot, msg_input])
btn_nda.click(fn=lambda h: chat("What is NDA exam?", "Devrayog Akash (Powerful)", h), inputs=[chatbot], outputs=[chatbot, msg_input])
btn_olq.click(fn=lambda h: chat("What are the 15 Officer-Like Qualities in SSB?", "Devrayog Akash (Powerful)", h), inputs=[chatbot], outputs=[chatbot, msg_input])
btn_tips.click(fn=lambda h: chat("Give me SSB preparation tips", "Devrayog Agni (Fast)", h), inputs=[chatbot], outputs=[chatbot, msg_input])
demo.launch(server_name="0.0.0.0", server_port=7860)app.py+210-231