LovnishVerma commited on
Commit
f5e78b1
Β·
verified Β·
1 Parent(s): 02deea6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -24
app.py CHANGED
@@ -7,7 +7,7 @@ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
7
  if GEMINI_API_KEY:
8
  genai.configure(api_key=GEMINI_API_KEY)
9
 
10
- # 2. Detailed University Information (Persona & Knowledge Base)
11
  NIELIT_INFO = """
12
  You are the official AI Assistant for NIELIT (National Institute of Electronics & Information Technology) Deemed to be University.
13
 
@@ -39,34 +39,62 @@ GUIDELINES:
39
  3. Always encourage students to verify at https://student.nielit.gov.in for their specific admit cards.
40
  """
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def get_chatbot_response(message, history):
43
- # 1. Handle Empty Messages
44
  if not message or not message.strip():
45
  return ""
46
-
47
- # 2. Handle Greetings Locally (Zero Latency / No API Cost)
48
- greetings = ["hi", "hello", "hey", "hlo", "namaste"]
49
  if message.lower().strip() in greetings:
50
  return "Hello! πŸ‘‹ I am the NIELIT University AI Assistant. How can I help you with admissions, fees, or exam details today?"
51
 
52
- # 3. Check API Key
53
  if not GEMINI_API_KEY:
54
- return "⚠️ System Error: GEMINI_API_KEY is missing. Please check server settings."
55
 
56
  try:
57
- # 4. Initialize Model with Persona
 
 
 
58
  model = genai.GenerativeModel(
59
- model_name="gemini-1.5-flash",
60
  system_instruction=NIELIT_INFO
61
  )
62
 
63
- # 5. Format History for Gemini
64
  chat_history = []
65
  for human, assistant in history:
66
  chat_history.append({"role": "user", "parts": [human]})
67
  chat_history.append({"role": "model", "parts": [assistant]})
68
 
69
- # 6. Generate Response
70
  chat = model.start_chat(history=chat_history)
71
  response = chat.send_message(message)
72
  return response.text
@@ -74,21 +102,27 @@ def get_chatbot_response(message, history):
74
  except Exception as e:
75
  return f"❌ Connection Error: {str(e)}"
76
 
77
- # 3. Custom CSS for Professional Branding
78
  custom_css = """
79
  #header { text-align: center; background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); padding: 20px; border-radius: 10px; margin-bottom: 20px; color: white; }
80
  .message-wrap { border-radius: 10px !important; }
81
  footer { text-align: center; margin-top: 20px; color: #666; font-size: 0.9em; }
82
  """
83
 
84
- # 4. Build the Gradio UI
85
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
86
  with gr.Row(elem_id="header"):
87
  gr.HTML("<h1>πŸŽ“ NIELIT University AI Support</h1><p>Admissions β€’ Fees β€’ Exams β€’ 2026 Session</p>")
88
 
89
  with gr.Row():
90
  with gr.Column(scale=4):
91
- chatbot = gr.Chatbot(height=500, show_label=False)
 
 
 
 
 
 
92
  with gr.Row():
93
  msg = gr.Textbox(placeholder="Ask about B.Tech fees, CCC exams, or admissions...", scale=4, container=False)
94
  submit = gr.Button("Send", variant="primary", scale=1)
@@ -103,31 +137,26 @@ with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
103
  gr.Markdown("---")
104
  gr.Markdown("### πŸ”— Links\n- [Student Portal](https://student.nielit.gov.in)\n- [Official Site](https://nielit.gov.in)")
105
 
106
- # 5. Define Main Chat Function
107
  def respond(message, chat_history):
108
- if chat_history is None:
109
- chat_history = []
110
-
111
  bot_message = get_chatbot_response(message, chat_history)
112
  chat_history.append((message, bot_message))
113
  return "", chat_history
114
 
115
- # 6. Wire up Event Handlers
116
- # Pressing Enter
117
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
118
 
119
- # Clicking Send Button (EXPOSES API ENDPOINT 'chat_with_bot')
120
  submit.click(respond, [msg, chatbot], [msg, chatbot], api_name="chat_with_bot")
121
 
122
- # Clearing Chat
123
  clear.click(lambda: None, None, chatbot, queue=False)
124
 
125
- # Quick Questions
126
  q1.click(lambda: "What is the fee structure for B.Tech programs?", outputs=msg).then(respond, [msg, chatbot], [msg, chatbot])
127
  q2.click(lambda: "What are the exam dates for January 2026?", outputs=msg).then(respond, [msg, chatbot], [msg, chatbot])
128
  q3.click(lambda: "Do SC/ST students get a fee waiver?", outputs=msg).then(respond, [msg, chatbot], [msg, chatbot])
129
 
130
- gr.HTML("<footer>Powered by Gemini 1.5 Flash | Official NIELIT Deemed University Assistant</footer>")
131
 
132
  if __name__ == "__main__":
133
  demo.launch()
 
7
  if GEMINI_API_KEY:
8
  genai.configure(api_key=GEMINI_API_KEY)
9
 
10
+ # 2. Detailed University Information
11
  NIELIT_INFO = """
12
  You are the official AI Assistant for NIELIT (National Institute of Electronics & Information Technology) Deemed to be University.
13
 
 
39
  3. Always encourage students to verify at https://student.nielit.gov.in for their specific admit cards.
40
  """
41
 
42
+ # --- ROBUST MODEL SELECTOR (Prevents 404 Errors) ---
43
+ def get_working_model():
44
+ """Finds a model that actually exists for your key"""
45
+ try:
46
+ # Get all available models
47
+ available = [m.name for m in genai.list_models() if 'generateContent' in m.supported_generation_methods]
48
+
49
+ # Priority list (Fastest -> Best -> Fallback)
50
+ priorities = [
51
+ "models/gemini-1.5-flash",
52
+ "models/gemini-1.5-pro",
53
+ "models/gemini-1.0-pro",
54
+ "models/gemini-pro"
55
+ ]
56
+
57
+ # Pick the first priority that exists in your available list
58
+ for model in priorities:
59
+ if model in available:
60
+ return model
61
+
62
+ # If no priority match, just take the first available one
63
+ return available[0] if available else "models/gemini-pro"
64
+
65
+ except Exception:
66
+ # Emergency fallback
67
+ return "gemini-pro"
68
+
69
  def get_chatbot_response(message, history):
70
+ # 1. Handle Empty/Greeting locally (Zero Latency)
71
  if not message or not message.strip():
72
  return ""
73
+
74
+ greetings = ["hi", "hello", "hey", "hlo", "namaste", "hola"]
 
75
  if message.lower().strip() in greetings:
76
  return "Hello! πŸ‘‹ I am the NIELIT University AI Assistant. How can I help you with admissions, fees, or exam details today?"
77
 
 
78
  if not GEMINI_API_KEY:
79
+ return "⚠️ System Error: GEMINI_API_KEY is missing."
80
 
81
  try:
82
+ # 2. Get a working model dynamically
83
+ model_name = get_working_model()
84
+
85
+ # 3. Initialize
86
  model = genai.GenerativeModel(
87
+ model_name=model_name,
88
  system_instruction=NIELIT_INFO
89
  )
90
 
91
+ # 4. Format History
92
  chat_history = []
93
  for human, assistant in history:
94
  chat_history.append({"role": "user", "parts": [human]})
95
  chat_history.append({"role": "model", "parts": [assistant]})
96
 
97
+ # 5. Generate
98
  chat = model.start_chat(history=chat_history)
99
  response = chat.send_message(message)
100
  return response.text
 
102
  except Exception as e:
103
  return f"❌ Connection Error: {str(e)}"
104
 
105
+ # 3. Custom CSS
106
  custom_css = """
107
  #header { text-align: center; background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%); padding: 20px; border-radius: 10px; margin-bottom: 20px; color: white; }
108
  .message-wrap { border-radius: 10px !important; }
109
  footer { text-align: center; margin-top: 20px; color: #666; font-size: 0.9em; }
110
  """
111
 
112
+ # 4. UI Layout
113
  with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
114
  with gr.Row(elem_id="header"):
115
  gr.HTML("<h1>πŸŽ“ NIELIT University AI Support</h1><p>Admissions β€’ Fees β€’ Exams β€’ 2026 Session</p>")
116
 
117
  with gr.Row():
118
  with gr.Column(scale=4):
119
+ # --- AVATAR CONFIGURATION HERE ---
120
+ # (None, "bot.png") means: User gets default icon, Bot gets "bot.png"
121
+ chatbot = gr.Chatbot(
122
+ height=500,
123
+ show_label=False,
124
+ avatar_images=(None, "https://cdn-uploads.huggingface.co/production/uploads/6474405f90330355db146c76/dOtPhPMj5nk3SEceM_3Iq.png")
125
+ )
126
  with gr.Row():
127
  msg = gr.Textbox(placeholder="Ask about B.Tech fees, CCC exams, or admissions...", scale=4, container=False)
128
  submit = gr.Button("Send", variant="primary", scale=1)
 
137
  gr.Markdown("---")
138
  gr.Markdown("### πŸ”— Links\n- [Student Portal](https://student.nielit.gov.in)\n- [Official Site](https://nielit.gov.in)")
139
 
140
+ # 5. Logic
141
  def respond(message, chat_history):
142
+ if chat_history is None: chat_history = []
 
 
143
  bot_message = get_chatbot_response(message, chat_history)
144
  chat_history.append((message, bot_message))
145
  return "", chat_history
146
 
 
 
147
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
148
 
149
+ # *** API ENDPOINT EXPOSED HERE ***
150
  submit.click(respond, [msg, chatbot], [msg, chatbot], api_name="chat_with_bot")
151
 
 
152
  clear.click(lambda: None, None, chatbot, queue=False)
153
 
154
+ # Quick Links
155
  q1.click(lambda: "What is the fee structure for B.Tech programs?", outputs=msg).then(respond, [msg, chatbot], [msg, chatbot])
156
  q2.click(lambda: "What are the exam dates for January 2026?", outputs=msg).then(respond, [msg, chatbot], [msg, chatbot])
157
  q3.click(lambda: "Do SC/ST students get a fee waiver?", outputs=msg).then(respond, [msg, chatbot], [msg, chatbot])
158
 
159
+ gr.HTML("<footer>Powered by Google Gemini | Official NIELIT Deemed University Assistant</footer>")
160
 
161
  if __name__ == "__main__":
162
  demo.launch()