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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -50
app.py CHANGED
@@ -1,33 +1,38 @@
1
- import json
2
- import os
3
- import requests
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 huggingface_hub import InferenceClient
11
  from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
- # βœ… Secure API Key Input (User provides it manually)
14
- HF_API_KEY = st.sidebar.text_input("Enter your Hugging Face API Key", type="password")
15
 
16
  # βœ… Initialize Hugging Face API Client
17
- client = InferenceClient(token=HF_API_KEY) if HF_API_KEY else None
18
 
19
  # βœ… Load Local Model with Device Optimization
20
  MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.2"
21
  device = "cuda" if torch.cuda.is_available() else "cpu"
22
 
23
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
24
- model = AutoModelForCausalLM.from_pretrained(MODEL_NAME).to(device)
 
25
  pipe = pipeline("text-generation", model=model, tokenizer=tokenizer, device=0 if device == "cuda" else -1)
26
 
27
- # βœ… Streamlit UI Setup
28
- st.set_page_config(page_title="AI-Powered Timetable", layout="wide")
29
- st.markdown("<h1 style='text-align: center; color: #4CAF50;'>πŸ“… AI-Powered Timetable</h1>", unsafe_allow_html=True)
30
-
31
  # βœ… File Upload Section
32
  st.sidebar.markdown("## πŸ“‚ Upload Your Timetable Files")
33
  uploaded_master = st.sidebar.file_uploader("Upload Master Timetable", type=["xlsx"])
@@ -42,57 +47,82 @@ uploaded_files = {
42
  "Individual Timetable": uploaded_individual,
43
  }
44
 
45
- # βœ… Load Timetable Data (Directly from Uploaded File)
46
  def load_timetable(file):
47
  if not file:
48
  return None
49
- df = pd.read_excel(file)
50
- return df
 
51
 
52
- # βœ… Ask Mistral AI via API with Timetable Context
53
- def ask_mistral_api_with_timetable(query, timetable_df):
54
- if timetable_df is None:
55
- return "No timetable uploaded."
 
 
 
 
 
 
 
56
 
57
- # Convert timetable to text format
58
- timetable_text = timetable_df.to_string(index=False)
 
 
 
 
59
 
60
- prompt = f"Here is a timetable:\n\n{timetable_text}\n\nUser Query: {query}\n\nAnswer based on the timetable."
 
 
 
61
 
62
- headers = {"Authorization": f"Bearer {HF_API_KEY}"}
63
- payload = {
64
- "model": MODEL_NAME,
65
- "messages": [{"role": "user", "content": prompt}],
66
- "max_tokens": 500,
67
- }
68
 
69
- response = requests.post("https://api-inference.huggingface.co/v1/chat/completions", json=payload, headers=headers)
 
 
70
 
71
- if response.status_code == 200:
72
- return response.json()["choices"][0]["message"]["content"]
73
- else:
74
- return f"Error: {response.json()}"
 
 
 
 
 
 
 
75
 
76
- # βœ… AI Query Section (with Timetable Scanning)
77
  st.markdown("## πŸ€– Ask Mistral AI About Your Timetable")
78
- selected_file = st.selectbox("Choose a timetable file to scan:", list(uploaded_files.keys()))
79
 
80
- if uploaded_files[selected_file]:
81
- timetable_df = load_timetable(uploaded_files[selected_file])
82
- user_query = st.text_input("Type your question (e.g., 'Who is free at 10 AM on Monday?')")
83
 
84
- if st.button("Ask AI via API with Timetable"):
85
- ai_response = ask_mistral_api_with_timetable(user_query, timetable_df)
86
- st.write("🧠 **Mistral AI Suggests:**", ai_response)
87
- else:
88
- st.write("⚠️ Please upload a timetable file first.")
 
 
 
 
 
 
89
 
90
  # βœ… Display Uploaded Timetables
91
  st.markdown("## πŸ“œ View Uploaded Timetables")
92
-
93
  for name, file in uploaded_files.items():
94
  if file:
95
  df = pd.read_excel(file)
96
  st.markdown(f"### {name}")
97
  st.dataframe(df)
98
-
 
 
 
 
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")
38
  uploaded_master = st.sidebar.file_uploader("Upload Master Timetable", type=["xlsx"])
 
47
  "Individual Timetable": uploaded_individual,
48
  }
49
 
50
+ # βœ… Load Timetable Data
51
  def load_timetable(file):
52
  if not file:
53
  return None
54
+ wb = openpyxl.load_workbook(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())
96
+ sheet.cell(row=row_idx, column=5, value=faculty.strip())
97
+ except:
98
+ continue
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)