jake2004 commited on
Commit
f4fbd3f
Β·
verified Β·
1 Parent(s): 0fc8113

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -54
app.py CHANGED
@@ -1,37 +1,24 @@
1
- import streamlit as st
2
  import requests
3
- import torch
4
- from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
5
- from huggingface_hub import InferenceClient, login
6
  import pandas as pd
7
  import openpyxl
 
 
 
 
8
 
9
  # βœ… Streamlit UI Setup
10
  st.set_page_config(page_title="AI-Powered Timetable", layout="wide")
11
- st.markdown("<h1 style='text-align: center; color: #4CAF50;'>πŸ“… AI-Powered Timetable</h1>", unsafe_allow_html=True)
12
-
13
- # βœ… User Input for API Key
14
- st.sidebar.markdown("## πŸ”‘ Enter Your Hugging Face API Key")
15
- HF_API_KEY = st.sidebar.text_input("API Key", type="password")
16
-
17
- if not HF_API_KEY:
18
- st.warning("Please enter your Hugging Face API key to proceed.")
19
- st.stop()
20
 
21
- # βœ… Authenticate with Hugging Face (No Need for CLI Login)
22
- login(token=HF_API_KEY, add_to_git_credential=False)
23
-
24
- # βœ… Initialize Hugging Face API Client
25
- client = InferenceClient(token=HF_API_KEY)
26
-
27
- # βœ… Load Local Model with Device Optimization
28
- MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.2"
29
- device = "cuda" if torch.cuda.is_available() else "cpu"
30
-
31
- # βœ… Load Model & Tokenizer with API Authentication
32
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=HF_API_KEY)
33
- model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, token=HF_API_KEY).to(device)
34
- pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if device == "cuda" else -1)
35
 
36
  # βœ… File Upload Section
37
  st.sidebar.markdown("## πŸ“‚ Upload Your Timetable Files")
@@ -47,7 +34,7 @@ uploaded_files = {
47
  "Individual Timetable": uploaded_individual,
48
  }
49
 
50
- # βœ… Load Timetable Data
51
  def load_timetable(file):
52
  if not file:
53
  return None
@@ -55,41 +42,45 @@ def load_timetable(file):
55
  sheet = wb.active
56
  return [row for row in sheet.iter_rows(values_only=True)]
57
 
58
- # βœ… Query Mistral AI via API
59
- def ask_mistral_api(query):
60
- headers = {"Authorization": f"Bearer {HF_API_KEY}"}
61
- url = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
62
- payload = {"inputs": query, "max_new_tokens": 500}
63
-
 
 
 
 
 
 
 
 
 
 
64
  response = requests.post(url, headers=headers, json=payload)
65
  if response.status_code == 200:
66
- return response.json()[0]["generated_text"]
67
  else:
68
- return f"Error: {response.json()}"
69
 
70
- # βœ… Query Mistral AI Locally
71
- def ask_mistral_local(query):
72
- inputs = tokenizer(query, return_tensors="pt").to(device)
73
- outputs = model.generate(**inputs, max_new_tokens=200)
74
- response = tokenizer.decode(outputs[0], skip_special_tokens=True)
75
- return response
76
-
77
- # βœ… Auto-Schedule Missing Timetable Slots
78
  def auto_schedule(file):
79
  if not file:
80
  return "No timetable uploaded."
81
 
82
  wb = openpyxl.load_workbook(file)
83
  sheet = wb.active
84
- empty_slots = []
85
 
 
86
  for row_idx, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
87
  if None in row or "" in row:
88
  empty_slots.append(row_idx)
89
 
90
  for row_idx in empty_slots:
91
  query = f"Suggest a subject and faculty for the empty slot in row {row_idx}."
92
- suggestion = ask_mistral_local(query)
 
93
  try:
94
  subject, faculty = suggestion.split(", Faculty: ")
95
  sheet.cell(row=row_idx, column=4, value=subject.strip())
@@ -99,30 +90,132 @@ def auto_schedule(file):
99
 
100
  return f"Auto-scheduling completed for {len(empty_slots)} slots."
101
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  # βœ… AI Query Section
103
- st.markdown("## πŸ€– Ask Mistral AI About Your Timetable")
104
  user_query = st.text_input("Type your question here (e.g., 'Who is free at 10 AM on Monday?')")
105
 
106
  if st.button("Ask AI via API"):
107
- ai_response = ask_mistral_api(user_query)
108
- st.write("🧠 **Mistral AI Suggests:**", ai_response)
109
-
110
- if st.button("Ask AI via Local Model"):
111
- ai_response = ask_mistral_local(user_query)
112
- st.write("🧠 **Mistral AI Suggests:**", ai_response)
113
 
114
  # βœ… Auto-Schedule Feature
115
  st.markdown("## πŸ“… Auto-Schedule Missing Timetable Slots")
116
- selected_file = st.selectbox("Choose a timetable file to auto-fill missing slots:", list(uploaded_files.keys()))
 
 
117
 
118
  if st.button("Auto-Schedule"):
119
  result = auto_schedule(uploaded_files[selected_file])
120
  st.write("βœ…", result)
121
 
 
 
 
 
 
 
 
122
  # βœ… Display Uploaded Timetables
123
  st.markdown("## πŸ“œ View Uploaded Timetables")
 
124
  for name, file in uploaded_files.items():
125
  if file:
126
  df = pd.read_excel(file)
127
  st.markdown(f"### {name}")
128
  st.dataframe(df)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
  import requests
3
+ import os
4
+ import streamlit as st
 
5
  import pandas as pd
6
  import openpyxl
7
+ import torch
8
+ from reportlab.lib.pagesizes import letter
9
+ from reportlab.pdfgen import canvas
10
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
11
 
12
  # βœ… Streamlit UI Setup
13
  st.set_page_config(page_title="AI-Powered Timetable", layout="wide")
14
+ st.markdown(
15
+ "<h1 style='text-align: center; color: #4CAF50;'>πŸ“… AI-Powered Timetable</h1>",
16
+ unsafe_allow_html=True,
17
+ )
 
 
 
 
 
18
 
19
+ # βœ… API Key Input
20
+ st.sidebar.markdown("## πŸ”‘ Enter Hugging Face API Key")
21
+ hf_api_key = st.sidebar.text_input("API Key", type="password")
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  # βœ… File Upload Section
24
  st.sidebar.markdown("## πŸ“‚ Upload Your Timetable Files")
 
34
  "Individual Timetable": uploaded_individual,
35
  }
36
 
37
+ # βœ… Load Timetable Data (Directly from Uploaded File)
38
  def load_timetable(file):
39
  if not file:
40
  return None
 
42
  sheet = wb.active
43
  return [row for row in sheet.iter_rows(values_only=True)]
44
 
45
+ # βœ… Ask LLaMA-3 API via Hugging Face
46
+ def ask_llama_api(query):
47
+ if not hf_api_key:
48
+ return "Error: Please enter your API key."
49
+
50
+ url = "https://api-inference.huggingface.co/v1/chat/completions"
51
+ headers = {
52
+ "Authorization": f"Bearer {hf_api_key}",
53
+ "Content-Type": "application/json",
54
+ }
55
+ payload = {
56
+ "model": "meta-llama/Meta-Llama-3-8B",
57
+ "messages": [{"role": "user", "content": query}],
58
+ "max_tokens": 500,
59
+ }
60
+
61
  response = requests.post(url, headers=headers, json=payload)
62
  if response.status_code == 200:
63
+ return response.json()["choices"][0]["message"]["content"]
64
  else:
65
+ return f"API Error: {response.status_code} - {response.text}"
66
 
67
+ # βœ… Auto-Schedule Missing Slots
 
 
 
 
 
 
 
68
  def auto_schedule(file):
69
  if not file:
70
  return "No timetable uploaded."
71
 
72
  wb = openpyxl.load_workbook(file)
73
  sheet = wb.active
 
74
 
75
+ empty_slots = []
76
  for row_idx, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
77
  if None in row or "" in row:
78
  empty_slots.append(row_idx)
79
 
80
  for row_idx in empty_slots:
81
  query = f"Suggest a subject and faculty for the empty slot in row {row_idx}."
82
+ suggestion = ask_llama_api(query)
83
+
84
  try:
85
  subject, faculty = suggestion.split(", Faculty: ")
86
  sheet.cell(row=row_idx, column=4, value=subject.strip())
 
90
 
91
  return f"Auto-scheduling completed for {len(empty_slots)} slots."
92
 
93
+ # βœ… PDF Generation for Timetable
94
+ def generate_pdf(file, filename="generated_timetable.pdf"):
95
+ if not file:
96
+ return "No timetable uploaded."
97
+
98
+ wb = openpyxl.load_workbook(file)
99
+ sheet = wb.active
100
+
101
+ pdf_filename = os.path.join(os.getcwd(), filename)
102
+ c = canvas.Canvas(pdf_filename, pagesize=letter)
103
+ width, height = letter
104
+ y = height - 50
105
+
106
+ c.setFont("Helvetica-Bold", 14)
107
+ c.drawString(200, y, "Generated Timetable")
108
+ y -= 30
109
+
110
+ c.setFont("Helvetica", 10)
111
+ for row in sheet.iter_rows(values_only=True):
112
+ row_text = " | ".join(str(cell) if cell else "" for cell in row)
113
+ c.drawString(50, y, row_text)
114
+ y -= 20
115
+ if y < 50:
116
+ c.showPage()
117
+ c.setFont("Helvetica", 10)
118
+ y = height - 50
119
+
120
+ c.save()
121
+ return pdf_filename
122
+
123
  # βœ… AI Query Section
124
+ st.markdown("## πŸ€– Ask LLaMA-3 AI About Your Timetable")
125
  user_query = st.text_input("Type your question here (e.g., 'Who is free at 10 AM on Monday?')")
126
 
127
  if st.button("Ask AI via API"):
128
+ ai_response = ask_llama_api(user_query)
129
+ st.write("🧠 **LLaMA-3 AI Suggests:**", ai_response)
 
 
 
 
130
 
131
  # βœ… Auto-Schedule Feature
132
  st.markdown("## πŸ“… Auto-Schedule Missing Timetable Slots")
133
+ selected_file = st.selectbox(
134
+ "Choose a timetable file to auto-fill missing slots:", list(uploaded_files.keys())
135
+ )
136
 
137
  if st.button("Auto-Schedule"):
138
  result = auto_schedule(uploaded_files[selected_file])
139
  st.write("βœ…", result)
140
 
141
+ # βœ… Generate PDF
142
+ st.markdown("## πŸ“„ Generate PDF of Timetable")
143
+ if st.button("Download PDF"):
144
+ pdf_path = generate_pdf(uploaded_files[selected_file])
145
+ with open(pdf_path, "rb") as pdf_file:
146
+ st.download_button("Download Timetable PDF", pdf_file, file_name="timetable.pdf")
147
+
148
  # βœ… Display Uploaded Timetables
149
  st.markdown("## πŸ“œ View Uploaded Timetables")
150
+
151
  for name, file in uploaded_files.items():
152
  if file:
153
  df = pd.read_excel(file)
154
  st.markdown(f"### {name}")
155
  st.dataframe(df)
156
+
157
+ # βœ… Inject JavaScript for Real-Time Chat
158
+ st.markdown(
159
+ """
160
+ <script>
161
+ async function fetchChatResponse() {
162
+ const apiKey = document.getElementById("hf-api-key").value;
163
+ const userInput = document.getElementById("user-input").value;
164
+ if (!apiKey) {
165
+ alert("Please enter your Hugging Face API key.");
166
+ return;
167
+ }
168
+
169
+ try {
170
+ const response = await fetch("https://api-inference.huggingface.co/v1/chat/completions", {
171
+ method: "POST",
172
+ headers: {
173
+ "Authorization": `Bearer ${apiKey}`,
174
+ "Content-Type": "application/json"
175
+ },
176
+ body: JSON.stringify({
177
+ model: "meta-llama/Meta-Llama-3-8B",
178
+ messages: [{ role: "user", content: userInput }],
179
+ max_tokens: 500
180
+ })
181
+ });
182
+
183
+ if (!response.ok) {
184
+ throw new Error(`API Error: ${response.statusText}`);
185
+ }
186
+
187
+ const data = await response.json();
188
+ const botMessage = data.choices[0].message.content;
189
+
190
+ document.getElementById("chat-box").innerHTML +=
191
+ `<div class='bot-message'><strong>VarunGPT-3:</strong> ${botMessage}</div>`;
192
+
193
+ } catch (error) {
194
+ console.error("Error fetching chat response:", error);
195
+ document.getElementById("chat-box").innerHTML +=
196
+ `<div class='bot-message'><strong>Error:</strong> Unable to fetch response.</div>`;
197
+ }
198
+ }
199
+ </script>
200
+ """,
201
+ unsafe_allow_html=True,
202
+ )
203
+
204
+ # βœ… Chat UI with User Input for API Key
205
+ st.markdown(
206
+ """
207
+ <div style="text-align: center;">
208
+ <input id="hf-api-key" type="password" placeholder="Enter Hugging Face API Key"
209
+ style="width: 50%; padding: 8px; margin-bottom: 10px;"/>
210
+ <br/>
211
+ <input id="user-input" type="text" placeholder="Type your message..."
212
+ style="width: 50%; padding: 8px;"/>
213
+ <button onclick="fetchChatResponse()"
214
+ style="padding: 10px 20px; background-color: #4CAF50; color: white; border: none; cursor:pointer;">
215
+ Ask AI
216
+ </button>
217
+ <div id="chat-box" style="margin-top: 20px; text-align: left;"></div>
218
+ </div>
219
+ """,
220
+ unsafe_allow_html=True,
221
+ )