Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,82 +1,50 @@
|
|
|
|
|
| 1 |
import google.generativeai as genai
|
| 2 |
-
from dotenv import load_dotenv
|
| 3 |
-
import logging
|
| 4 |
import os
|
| 5 |
-
import requests
|
| 6 |
-
from bs4 import BeautifulSoup
|
| 7 |
-
import time
|
| 8 |
from datetime import datetime
|
| 9 |
-
import gradio as gr
|
| 10 |
-
|
| 11 |
-
# ==========================================
|
| 12 |
-
# 1. SETUP & CONFIGURATION
|
| 13 |
-
# ==========================================
|
| 14 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
|
| 15 |
-
logger = logging.getLogger(__name__)
|
| 16 |
-
|
| 17 |
-
load_dotenv()
|
| 18 |
-
api_key = os.getenv("GEMINI_API_KEY")
|
| 19 |
-
|
| 20 |
-
# Emergency Fallback (If env fails)
|
| 21 |
-
if not api_key:
|
| 22 |
-
# api_key = "PASTE_YOUR_KEY_HERE"
|
| 23 |
-
pass
|
| 24 |
-
|
| 25 |
-
try:
|
| 26 |
-
genai.configure(api_key=api_key)
|
| 27 |
-
except Exception as e:
|
| 28 |
-
print(f"β οΈ Key Error: {e}")
|
| 29 |
-
|
| 30 |
-
# ==========================================
|
| 31 |
-
# 2. THE WEB SCRAPER (Working Perfectly)
|
| 32 |
-
# ==========================================
|
| 33 |
-
def fetch_nielit_live_data():
|
| 34 |
-
target_urls = [
|
| 35 |
-
"https://nielit.ac.in/",
|
| 36 |
-
"https://www.nielit.gov.in/chandigarh/index.php"
|
| 37 |
-
]
|
| 38 |
-
|
| 39 |
-
knowledge = f"### LIVE NIELIT DATA ({datetime.now().strftime('%Y-%m-%d')}) ###\n"
|
| 40 |
-
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'}
|
| 41 |
-
|
| 42 |
-
print("β‘ SCANNING WEBSITES...")
|
| 43 |
-
|
| 44 |
-
for url in target_urls:
|
| 45 |
-
try:
|
| 46 |
-
print(f" Reading: {url}...")
|
| 47 |
-
resp = requests.get(url, headers=headers, timeout=10)
|
| 48 |
-
if resp.status_code == 200:
|
| 49 |
-
soup = BeautifulSoup(resp.content, 'html.parser')
|
| 50 |
-
for bad in soup(["script", "style", "nav", "footer"]):
|
| 51 |
-
bad.extract()
|
| 52 |
-
text = ' '.join(soup.get_text(separator=' ', strip=True).split())
|
| 53 |
-
knowledge += f"\n--- SOURCE: {url} ---\n{text[:8000]}\n"
|
| 54 |
-
except:
|
| 55 |
-
pass # Skip failed sites to prevent crashes
|
| 56 |
-
|
| 57 |
-
return knowledge
|
| 58 |
-
|
| 59 |
-
# ==========================================
|
| 60 |
-
# 3. INITIALIZATION
|
| 61 |
-
# ==========================================
|
| 62 |
-
print("\nπ STARTING BOT...")
|
| 63 |
-
nielit_data = fetch_nielit_live_data()
|
| 64 |
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
"""
|
| 75 |
|
| 76 |
-
# Try loading the model
|
| 77 |
def get_available_model_name():
|
| 78 |
"""
|
| 79 |
-
Dynamically finds a working model from the user's account.
|
| 80 |
"""
|
| 81 |
try:
|
| 82 |
available_models = []
|
|
@@ -85,10 +53,9 @@ def get_available_model_name():
|
|
| 85 |
available_models.append(m.name)
|
| 86 |
|
| 87 |
if not available_models:
|
| 88 |
-
logger.error("No models found.")
|
| 89 |
return None
|
| 90 |
|
| 91 |
-
# Priority list: Try to find these specific
|
| 92 |
preferred_order = [
|
| 93 |
"models/gemini-1.5-flash",
|
| 94 |
"models/gemini-1.5-pro",
|
|
@@ -96,49 +63,176 @@ def get_available_model_name():
|
|
| 96 |
"models/gemini-1.0-pro"
|
| 97 |
]
|
| 98 |
|
| 99 |
-
#
|
| 100 |
for preferred in preferred_order:
|
| 101 |
if preferred in available_models:
|
| 102 |
-
logger.info(f"Selected Preferred Model: {preferred}")
|
| 103 |
return preferred
|
| 104 |
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
-
logger.warning(f"Preferred models missing. Falling back to: {fallback}")
|
| 108 |
-
return fallback
|
| 109 |
|
| 110 |
except Exception as e:
|
| 111 |
-
logger.error(f"Error listing models: {e}")
|
| 112 |
return None
|
| 113 |
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
|
|
|
|
|
|
| 118 |
try:
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
except Exception as e:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
#
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
-
#
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
|
|
|
| 143 |
if __name__ == "__main__":
|
| 144 |
-
demo.
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
import google.generativeai as genai
|
|
|
|
|
|
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
| 4 |
from datetime import datetime
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
# Configure Gemini API
|
| 7 |
+
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 8 |
+
if GEMINI_API_KEY:
|
| 9 |
+
genai.configure(api_key=GEMINI_API_KEY)
|
| 10 |
+
|
| 11 |
+
# NIELIT University Information
|
| 12 |
+
NIELIT_INFO = """
|
| 13 |
+
You are an AI assistant for NIELIT (National Institute of Electronics & Information Technology) Deemed to be University.
|
| 14 |
+
|
| 15 |
+
NIELIT UNIVERSITY INFORMATION:
|
| 16 |
+
- NIELIT is an autonomous scientific society under the Ministry of Electronics and Information Technology (MeitY), Government of India
|
| 17 |
+
- NIELIT has been conferred the status of "Deemed to be University" under Section 3 of the UGC Act, 1956
|
| 18 |
+
- Offers various programs in IT, Electronics, and emerging technologies
|
| 19 |
+
- Multiple centers across India including Delhi, Kolkata, Chennai, Calicut, Gorakhpur, Ajmer, Aurangabad, and more
|
| 20 |
+
- Programs offered: B.Tech, M.Tech, MCA, PhD, and various certification courses
|
| 21 |
+
- Focus areas: Artificial Intelligence, Machine Learning, Cybersecurity, IoT, Data Science, Cloud Computing, Blockchain
|
| 22 |
+
- NIELIT also conducts CCC (Course on Computer Concepts), BCC, and other IT literacy programs
|
| 23 |
+
- Conducts entrance exams for various programs
|
| 24 |
+
|
| 25 |
+
KEY COURSES:
|
| 26 |
+
1. B.Tech in Computer Science & Engineering
|
| 27 |
+
2. M.Tech in various specializations (AI, Cybersecurity, Data Science, etc.)
|
| 28 |
+
3. MCA (Master of Computer Applications)
|
| 29 |
+
4. PhD programs in Computer Science and Electronics
|
| 30 |
+
5. Certificate and Diploma courses (CCC, BCC, O Level, A Level, B Level, C Level)
|
| 31 |
+
|
| 32 |
+
ADMISSIONS:
|
| 33 |
+
- Admissions through entrance examinations
|
| 34 |
+
- Online application process
|
| 35 |
+
- Merit-based selection for various programs
|
| 36 |
+
|
| 37 |
+
When answering questions:
|
| 38 |
+
1. Be helpful, informative, and student-friendly
|
| 39 |
+
2. Provide accurate information about NIELIT programs and services
|
| 40 |
+
3. Guide students on admissions, courses, and career opportunities
|
| 41 |
+
4. If you don't know specific current details (fees, dates, etc.), suggest visiting the official NIELIT website or contacting the admission office
|
| 42 |
+
5. Be encouraging and supportive to prospective students
|
| 43 |
"""
|
| 44 |
|
|
|
|
| 45 |
def get_available_model_name():
|
| 46 |
"""
|
| 47 |
+
Dynamically finds a working Gemini model from the user's account.
|
| 48 |
"""
|
| 49 |
try:
|
| 50 |
available_models = []
|
|
|
|
| 53 |
available_models.append(m.name)
|
| 54 |
|
| 55 |
if not available_models:
|
|
|
|
| 56 |
return None
|
| 57 |
|
| 58 |
+
# Priority list: Try to find these specific models first
|
| 59 |
preferred_order = [
|
| 60 |
"models/gemini-1.5-flash",
|
| 61 |
"models/gemini-1.5-pro",
|
|
|
|
| 63 |
"models/gemini-1.0-pro"
|
| 64 |
]
|
| 65 |
|
| 66 |
+
# Check if any preferred model is available
|
| 67 |
for preferred in preferred_order:
|
| 68 |
if preferred in available_models:
|
|
|
|
| 69 |
return preferred
|
| 70 |
|
| 71 |
+
# If none of the preferred ones exist, use the first available
|
| 72 |
+
return available_models[0]
|
|
|
|
|
|
|
| 73 |
|
| 74 |
except Exception as e:
|
|
|
|
| 75 |
return None
|
| 76 |
|
| 77 |
+
def get_chatbot_response(message, history):
|
| 78 |
+
"""Generate response using Gemini API"""
|
| 79 |
+
|
| 80 |
+
if not GEMINI_API_KEY:
|
| 81 |
+
return "β οΈ Please set the GEMINI_API_KEY environment variable in Hugging Face Spaces settings."
|
| 82 |
+
|
| 83 |
try:
|
| 84 |
+
# Get the best available model
|
| 85 |
+
model_name = get_available_model_name()
|
| 86 |
+
|
| 87 |
+
if not model_name:
|
| 88 |
+
return "β No available Gemini models found for your API key.\n\nπ Please verify your API key at: https://aistudio.google.com/app/apikey\n\nMake sure you have access to Gemini models."
|
| 89 |
+
|
| 90 |
+
# Initialize the model
|
| 91 |
+
model = genai.GenerativeModel(model_name)
|
| 92 |
+
|
| 93 |
+
# Build conversation history
|
| 94 |
+
chat_history = []
|
| 95 |
+
for human, assistant in history:
|
| 96 |
+
chat_history.append({"role": "user", "parts": [human]})
|
| 97 |
+
chat_history.append({"role": "model", "parts": [assistant]})
|
| 98 |
+
|
| 99 |
+
# Start chat with history
|
| 100 |
+
chat = model.start_chat(history=chat_history)
|
| 101 |
+
|
| 102 |
+
# Create context-aware prompt
|
| 103 |
+
full_prompt = f"{NIELIT_INFO}\n\nStudent Query: {message}\n\nProvide a helpful and accurate response:"
|
| 104 |
+
|
| 105 |
+
# Get response
|
| 106 |
+
response = chat.send_message(full_prompt)
|
| 107 |
+
|
| 108 |
+
return response.text
|
| 109 |
+
|
| 110 |
except Exception as e:
|
| 111 |
+
error_msg = str(e)
|
| 112 |
+
if "API_KEY_INVALID" in error_msg or "invalid" in error_msg.lower():
|
| 113 |
+
return f"β Invalid API Key Error: {error_msg}\n\nπ Please get a valid API key from: https://aistudio.google.com/app/apikey\n\nThen set it in Hugging Face Spaces: Settings β Repository secrets β GEMINI_API_KEY"
|
| 114 |
+
return f"β Error: {error_msg}\n\nModel used: {model_name if 'model_name' in locals() else 'unknown'}\n\nIf the error persists, please verify your API key is correct."
|
| 115 |
+
|
| 116 |
+
# Custom CSS for NIELIT branding
|
| 117 |
+
custom_css = """
|
| 118 |
+
#header {
|
| 119 |
+
text-align: center;
|
| 120 |
+
background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
|
| 121 |
+
padding: 20px;
|
| 122 |
+
border-radius: 10px;
|
| 123 |
+
margin-bottom: 20px;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
#header h1 {
|
| 127 |
+
color: white;
|
| 128 |
+
margin: 0;
|
| 129 |
+
font-size: 2em;
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
#header p {
|
| 133 |
+
color: #e0e0e0;
|
| 134 |
+
margin: 5px 0 0 0;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
.message-wrap {
|
| 138 |
+
border-radius: 10px !important;
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
footer {
|
| 142 |
+
text-align: center;
|
| 143 |
+
margin-top: 20px;
|
| 144 |
+
color: #666;
|
| 145 |
+
}
|
| 146 |
+
"""
|
| 147 |
+
|
| 148 |
+
# Predefined quick questions
|
| 149 |
+
example_questions = [
|
| 150 |
+
"What programs does NIELIT University offer?",
|
| 151 |
+
"How can I apply for admission?",
|
| 152 |
+
"What is the CCC course?",
|
| 153 |
+
"Tell me about M.Tech programs",
|
| 154 |
+
"What are the career opportunities after NIELIT courses?",
|
| 155 |
+
"Information about PhD programs",
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
# Create Gradio interface
|
| 159 |
+
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
|
| 160 |
+
# Header
|
| 161 |
+
with gr.Row(elem_id="header"):
|
| 162 |
+
gr.HTML("""
|
| 163 |
+
<div>
|
| 164 |
+
<h1>π NIELIT Deemed to be University</h1>
|
| 165 |
+
<p>AI-Powered Student Assistance Chatbot</p>
|
| 166 |
+
</div>
|
| 167 |
+
""")
|
| 168 |
|
| 169 |
+
# Main content
|
| 170 |
+
with gr.Row():
|
| 171 |
+
with gr.Column(scale=4):
|
| 172 |
+
chatbot = gr.Chatbot(
|
| 173 |
+
height=500,
|
| 174 |
+
bubble_full_width=False,
|
| 175 |
+
avatar_images=(None, "https://cdn-uploads.huggingface.co/production/uploads/6474405f90330355db146c76/dOtPhPMj5nk3SEceM_3Iq.png"),
|
| 176 |
+
show_label=False
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
with gr.Row():
|
| 180 |
+
msg = gr.Textbox(
|
| 181 |
+
placeholder="Ask me anything about NIELIT University, programs, admissions...",
|
| 182 |
+
show_label=False,
|
| 183 |
+
scale=4,
|
| 184 |
+
container=False
|
| 185 |
+
)
|
| 186 |
+
submit = gr.Button("Send", variant="primary", scale=1)
|
| 187 |
+
|
| 188 |
+
clear = gr.Button("ποΈ Clear Chat")
|
| 189 |
+
|
| 190 |
+
with gr.Column(scale=1):
|
| 191 |
+
gr.Markdown("### π‘ Quick Questions")
|
| 192 |
+
|
| 193 |
+
for question in example_questions:
|
| 194 |
+
btn = gr.Button(question, size="sm")
|
| 195 |
+
btn.click(
|
| 196 |
+
lambda q=question: q,
|
| 197 |
+
outputs=msg
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
gr.Markdown("---")
|
| 201 |
+
gr.Markdown("""
|
| 202 |
+
### βΉοΈ About
|
| 203 |
+
This chatbot provides information about:
|
| 204 |
+
- π Academic Programs
|
| 205 |
+
- π Admissions Process
|
| 206 |
+
- π― Course Details
|
| 207 |
+
- πΌ Career Guidance
|
| 208 |
+
- π Contact Information
|
| 209 |
+
|
| 210 |
+
### π Official Links
|
| 211 |
+
- [NIELIT Website](https://www.nielit.gov.in)
|
| 212 |
+
- [Student Portal](https://student.nielit.gov.in)
|
| 213 |
+
- [Admissions](https://nielit.gov.in/admissions)
|
| 214 |
+
""")
|
| 215 |
+
|
| 216 |
+
# Footer
|
| 217 |
+
gr.HTML("""
|
| 218 |
+
<footer>
|
| 219 |
+
<p>Powered by Google Gemini AI | Developed for NIELIT Deemed to be University</p>
|
| 220 |
+
<p style="font-size: 0.9em; color: #999;">
|
| 221 |
+
For official information, please visit <a href="https://www.nielit.gov.in" target="_blank">www.nielit.gov.in</a>
|
| 222 |
+
</p>
|
| 223 |
+
</footer>
|
| 224 |
+
""")
|
| 225 |
+
|
| 226 |
+
# Event handlers
|
| 227 |
+
def respond(message, chat_history):
|
| 228 |
+
bot_message = get_chatbot_response(message, chat_history)
|
| 229 |
+
chat_history.append((message, bot_message))
|
| 230 |
+
return "", chat_history
|
| 231 |
+
|
| 232 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 233 |
+
submit.click(respond, [msg, chatbot], [msg, chatbot])
|
| 234 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 235 |
|
| 236 |
+
# Launch the app
|
| 237 |
if __name__ == "__main__":
|
| 238 |
+
demo.launch()
|