Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,12 +10,24 @@ import warnings
|
|
| 10 |
# ==========================================
|
| 11 |
warnings.filterwarnings("ignore")
|
| 12 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
|
|
|
|
| 13 |
|
| 14 |
load_dotenv()
|
| 15 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
# ==========================================
|
| 18 |
-
# 2. THE KNOWLEDGE BASE
|
| 19 |
# ==========================================
|
| 20 |
NIELIT_CONTEXT = """
|
| 21 |
### ABOUT NIELIT ROPAR
|
|
@@ -29,8 +41,8 @@ Your goal is to help students with accurate campus information.
|
|
| 29 |
### ACADEMIC & FACULTY
|
| 30 |
- **Head of Training (HoD):** Mrs. Anita Budhiraja (Scientist 'E')
|
| 31 |
- **Key Faculty:** 1. Dr. Sarwan Singh (Scientist 'D')
|
| 32 |
-
|
| 33 |
-
|
| 34 |
|
| 35 |
### FEE STRUCTURE (Per Semester)
|
| 36 |
- **B.Tech:** Rs. 50,000
|
|
@@ -45,29 +57,64 @@ Your goal is to help students with accurate campus information.
|
|
| 45 |
"""
|
| 46 |
|
| 47 |
# ==========================================
|
| 48 |
-
# 3.
|
| 49 |
# ==========================================
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
"gemini-1.5-flash",
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
model = None
|
| 63 |
|
| 64 |
# ==========================================
|
| 65 |
# 4. CHAT LOGIC
|
| 66 |
# ==========================================
|
| 67 |
def format_history(gradio_history):
|
| 68 |
-
"""Converts Gradio history [[user, bot], ...] to Gemini history."""
|
| 69 |
gemini_history = []
|
| 70 |
-
# The default Gradio chat history is a list of lists: [[user_msg, bot_msg], ...]
|
| 71 |
for user_msg, bot_msg in gradio_history:
|
| 72 |
if user_msg:
|
| 73 |
gemini_history.append({"role": "user", "parts": [user_msg]})
|
|
@@ -81,16 +128,10 @@ def chat_response(message, history):
|
|
| 81 |
yield "⚠️ API Key Missing. Please check your settings."
|
| 82 |
return
|
| 83 |
|
| 84 |
-
# 1. Load past memory
|
| 85 |
formatted_history = format_history(history)
|
| 86 |
-
|
| 87 |
-
# 2. Start a chat session with memory
|
| 88 |
chat_session = model.start_chat(history=formatted_history)
|
| 89 |
-
|
| 90 |
-
# 3. Generate Response (Streamed)
|
| 91 |
response = chat_session.send_message(message, stream=True)
|
| 92 |
|
| 93 |
-
# 4. Stream the output character by character
|
| 94 |
partial_text = ""
|
| 95 |
for chunk in response:
|
| 96 |
if chunk.text:
|
|
@@ -114,8 +155,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
|
| 114 |
chatbot=gr.Chatbot(
|
| 115 |
height=500,
|
| 116 |
avatar_images=(None, bot_avatar)
|
| 117 |
-
# REMOVED: type="messages" (This was causing your crash)
|
| 118 |
),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
)
|
| 120 |
|
| 121 |
if __name__ == "__main__":
|
|
|
|
| 10 |
# ==========================================
|
| 11 |
warnings.filterwarnings("ignore")
|
| 12 |
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
load_dotenv()
|
| 16 |
api_key = os.getenv("GEMINI_API_KEY")
|
| 17 |
|
| 18 |
+
# Emergency Fallback
|
| 19 |
+
if not api_key:
|
| 20 |
+
# api_key = "PASTE_YOUR_KEY_HERE"
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
if api_key:
|
| 25 |
+
genai.configure(api_key=api_key)
|
| 26 |
+
except Exception as e:
|
| 27 |
+
print(f"⚠️ Key Error: {e}")
|
| 28 |
+
|
| 29 |
# ==========================================
|
| 30 |
+
# 2. THE KNOWLEDGE BASE (No Scraping/Noise)
|
| 31 |
# ==========================================
|
| 32 |
NIELIT_CONTEXT = """
|
| 33 |
### ABOUT NIELIT ROPAR
|
|
|
|
| 41 |
### ACADEMIC & FACULTY
|
| 42 |
- **Head of Training (HoD):** Mrs. Anita Budhiraja (Scientist 'E')
|
| 43 |
- **Key Faculty:** 1. Dr. Sarwan Singh (Scientist 'D')
|
| 44 |
+
2. Ms. Sonia Bansal (Scientist 'E')
|
| 45 |
+
3. Sh. Raminder Singh (Scientist 'E')
|
| 46 |
|
| 47 |
### FEE STRUCTURE (Per Semester)
|
| 48 |
- **B.Tech:** Rs. 50,000
|
|
|
|
| 57 |
"""
|
| 58 |
|
| 59 |
# ==========================================
|
| 60 |
+
# 3. ROBUST MODEL SELECTOR (The Fix)
|
| 61 |
# ==========================================
|
| 62 |
+
def get_working_model(system_prompt):
|
| 63 |
+
print("\n🔍 CHECKING AVAILABLE MODELS...")
|
| 64 |
+
try:
|
| 65 |
+
# Get list of ALL models your key can access
|
| 66 |
+
my_models = []
|
| 67 |
+
for m in genai.list_models():
|
| 68 |
+
if 'generateContent' in m.supported_generation_methods:
|
| 69 |
+
my_models.append(m.name)
|
| 70 |
+
|
| 71 |
+
print(f" Found: {my_models}")
|
| 72 |
+
|
| 73 |
+
# Priority list (Try these in order)
|
| 74 |
+
priority = [
|
| 75 |
"gemini-1.5-flash",
|
| 76 |
+
"gemini-1.5-pro",
|
| 77 |
+
"gemini-pro",
|
| 78 |
+
"models/gemini-1.5-flash",
|
| 79 |
+
"models/gemini-pro"
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
selected_model = None
|
| 83 |
+
|
| 84 |
+
# 1. Match Priority
|
| 85 |
+
for p in priority:
|
| 86 |
+
for m in my_models:
|
| 87 |
+
if p in m or m in p:
|
| 88 |
+
selected_model = p
|
| 89 |
+
break
|
| 90 |
+
if selected_model: break
|
| 91 |
+
|
| 92 |
+
# 2. Fallback to First Available
|
| 93 |
+
if not selected_model and my_models:
|
| 94 |
+
selected_model = my_models[0].replace("models/", "")
|
| 95 |
+
|
| 96 |
+
# 3. Final Fallback
|
| 97 |
+
if not selected_model:
|
| 98 |
+
selected_model = "gemini-pro"
|
| 99 |
+
|
| 100 |
+
print(f"✅ SELECTED MODEL: {selected_model}\n")
|
| 101 |
+
return genai.GenerativeModel(selected_model, system_instruction=system_prompt)
|
| 102 |
+
|
| 103 |
+
except Exception as e:
|
| 104 |
+
print(f"⚠️ Model List Error: {e}")
|
| 105 |
+
return genai.GenerativeModel("gemini-pro", system_instruction=system_prompt)
|
| 106 |
+
|
| 107 |
+
# Initialize the model dynamically
|
| 108 |
+
if api_key:
|
| 109 |
+
model = get_working_model(NIELIT_CONTEXT)
|
| 110 |
+
else:
|
| 111 |
model = None
|
| 112 |
|
| 113 |
# ==========================================
|
| 114 |
# 4. CHAT LOGIC
|
| 115 |
# ==========================================
|
| 116 |
def format_history(gradio_history):
|
|
|
|
| 117 |
gemini_history = []
|
|
|
|
| 118 |
for user_msg, bot_msg in gradio_history:
|
| 119 |
if user_msg:
|
| 120 |
gemini_history.append({"role": "user", "parts": [user_msg]})
|
|
|
|
| 128 |
yield "⚠️ API Key Missing. Please check your settings."
|
| 129 |
return
|
| 130 |
|
|
|
|
| 131 |
formatted_history = format_history(history)
|
|
|
|
|
|
|
| 132 |
chat_session = model.start_chat(history=formatted_history)
|
|
|
|
|
|
|
| 133 |
response = chat_session.send_message(message, stream=True)
|
| 134 |
|
|
|
|
| 135 |
partial_text = ""
|
| 136 |
for chunk in response:
|
| 137 |
if chunk.text:
|
|
|
|
| 155 |
chatbot=gr.Chatbot(
|
| 156 |
height=500,
|
| 157 |
avatar_images=(None, bot_avatar)
|
|
|
|
| 158 |
),
|
| 159 |
+
examples=[
|
| 160 |
+
"What is the Fee Structure?",
|
| 161 |
+
"Who is the Head of Training?",
|
| 162 |
+
"Does the campus have bus facility?",
|
| 163 |
+
"Where is NIELIT Ropar located?"
|
| 164 |
+
]
|
| 165 |
)
|
| 166 |
|
| 167 |
if __name__ == "__main__":
|