jake2004 commited on
Commit
eaf3015
Β·
verified Β·
1 Parent(s): d36678d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -71
app.py CHANGED
@@ -1,6 +1,5 @@
1
  import json
2
  import requests
3
- import os
4
  import streamlit as st
5
  import pandas as pd
6
  import openpyxl
@@ -28,17 +27,24 @@ uploaded_files = {
28
  "Individual Timetable": st.sidebar.file_uploader("Upload Individual Timetable", type=["xlsx", "docx"]),
29
  }
30
 
31
- # βœ… Load Timetable Data (Excel & DOCX)
32
- def load_timetable(file):
33
- if not file:
34
- return None
35
- if file.name.endswith(".xlsx"):
36
- wb = openpyxl.load_workbook(file)
37
- sheet = wb.active
38
- return [row for row in sheet.iter_rows(values_only=True)]
39
- elif file.name.endswith(".docx"):
40
- doc = Document(file)
41
- return [para.text for para in doc.paragraphs]
 
 
 
 
 
 
 
42
 
43
  # βœ… Ask TinyLlama AI via API
44
  def ask_tinyllama_api(query):
@@ -46,8 +52,15 @@ def ask_tinyllama_api(query):
46
  return "Error: Please enter your API key."
47
 
48
  url = "https://api-inference.huggingface.co/v1/chat/completions"
49
- headers = {"Authorization": f"Bearer {hf_api_key}", "Content-Type": "application/json"}
50
- payload = {"model": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "messages": [{"role": "user", "content": query}], "max_tokens": 500}
 
 
 
 
 
 
 
51
 
52
  response = requests.post(url, headers=headers, json=payload)
53
  if response.status_code == 200:
@@ -55,44 +68,28 @@ def ask_tinyllama_api(query):
55
  else:
56
  return f"API Error: {response.status_code} - {response.text}"
57
 
58
- # βœ… Auto-Schedule Missing Slots (Excel & DOCX)
59
  def auto_schedule(file):
60
  if not file:
61
  return "No timetable uploaded."
62
 
63
- if file.name.endswith(".xlsx"):
64
- wb = openpyxl.load_workbook(file)
65
- sheet = wb.active
66
-
67
- empty_slots = []
68
- for row_idx, row in enumerate(sheet.iter_rows(min_row=2, values_only=True), start=2):
69
- if None in row or "" in row:
70
- empty_slots.append(row_idx)
71
-
72
- for row_idx in empty_slots:
73
- query = f"Suggest a subject and faculty for the empty slot in row {row_idx}."
74
- suggestion = ask_tinyllama_api(query)
75
-
76
- try:
77
- subject, faculty = suggestion.split(", Faculty: ")
78
- sheet.cell(row=row_idx, column=4, value=subject.strip())
79
- sheet.cell(row=row_idx, column=5, value=faculty.strip())
80
- except:
81
- continue
82
-
83
- return f"Auto-scheduling completed for {len(empty_slots)} slots."
84
-
85
- elif file.name.endswith(".docx"):
86
- doc = Document(file)
87
- new_doc = Document()
88
- for para in doc.paragraphs:
89
- if "EMPTY SLOT" in para.text:
90
- query = "Suggest a subject and faculty for this slot."
91
- suggestion = ask_tinyllama_api(query)
92
- new_doc.add_paragraph(suggestion)
93
- else:
94
- new_doc.add_paragraph(para.text)
95
- return new_doc
96
 
97
  # βœ… AI Query Section
98
  st.markdown("## πŸ€– Ask TinyLlama AI About Your Timetable")
@@ -107,37 +104,31 @@ st.markdown("## πŸ“… Auto-Schedule Missing Timetable Slots")
107
  selected_file = st.selectbox("Choose a timetable file to auto-fill missing slots:", list(uploaded_files.keys()))
108
 
109
  if st.button("Auto-Schedule"):
110
- result = auto_schedule(uploaded_files[selected_file])
111
- if isinstance(result, Document): # DOCX file
112
- output = BytesIO()
113
- result.save(output)
114
- output.seek(0)
115
- st.download_button("πŸ“₯ Download Updated DOCX", output, file_name="updated_timetable.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
116
  else:
117
- st.write("βœ…", result)
118
 
119
- # βœ… Display Uploaded Timetables
120
  st.markdown("## πŸ“œ View & Edit Uploaded Timetables")
121
 
122
  for name, file in uploaded_files.items():
123
  if file:
124
  if file.name.endswith(".xlsx"):
125
- df = pd.read_excel(file)
126
  edited_df = st.data_editor(df, num_rows="dynamic")
127
- st.download_button("πŸ“₯ Download Edited Excel", edited_df.to_csv(index=False).encode(), file_name=f"{name}.csv", mime="text/csv")
 
 
128
  elif file.name.endswith(".docx"):
129
- doc = Document(file)
130
- doc_text = "\n".join([para.text for para in doc.paragraphs])
131
- edited_text = st.text_area(f"Edit {name}:", doc_text)
132
- new_doc = Document()
133
- for line in edited_text.split("\n"):
134
- new_doc.add_paragraph(line)
135
- output = BytesIO()
136
- new_doc.save(output)
137
- output.seek(0)
138
- st.download_button("πŸ“₯ Download Edited DOCX", output, file_name=f"{name}.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
139
-
140
- # βœ… PDF Export Feature
141
  st.markdown("## πŸ“„ Export to PDF")
142
  if st.button("Export to PDF"):
143
  pdf_output = BytesIO()
@@ -151,4 +142,4 @@ if st.button("Export to PDF"):
151
  c.save()
152
  pdf_output.seek(0)
153
  st.download_button("πŸ“₯ Download PDF", pdf_output, file_name="timetable.pdf", mime="application/pdf")
154
-
 
1
  import json
2
  import requests
 
3
  import streamlit as st
4
  import pandas as pd
5
  import openpyxl
 
27
  "Individual Timetable": st.sidebar.file_uploader("Upload Individual Timetable", type=["xlsx", "docx"]),
28
  }
29
 
30
+ # βœ… Load XLSX File
31
+ def load_xlsx(file):
32
+ return pd.read_excel(file)
33
+
34
+ # βœ… Load DOCX File
35
+ def load_docx(file):
36
+ doc = Document(file)
37
+ return "\n".join([para.text for para in doc.paragraphs])
38
+
39
+ # βœ… Save DOCX File
40
+ def save_docx(text):
41
+ doc = Document()
42
+ for line in text.split("\n"):
43
+ doc.add_paragraph(line)
44
+ output = BytesIO()
45
+ doc.save(output)
46
+ output.seek(0)
47
+ return output
48
 
49
  # βœ… Ask TinyLlama AI via API
50
  def ask_tinyllama_api(query):
 
52
  return "Error: Please enter your API key."
53
 
54
  url = "https://api-inference.huggingface.co/v1/chat/completions"
55
+ headers = {
56
+ "Authorization": f"Bearer {hf_api_key}",
57
+ "Content-Type": "application/json"
58
+ }
59
+ payload = {
60
+ "model": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
61
+ "messages": [{"role": "user", "content": query}],
62
+ "max_tokens": 500
63
+ }
64
 
65
  response = requests.post(url, headers=headers, json=payload)
66
  if response.status_code == 200:
 
68
  else:
69
  return f"API Error: {response.status_code} - {response.text}"
70
 
71
+ # βœ… Auto-Schedule Missing Slots in Excel
72
  def auto_schedule(file):
73
  if not file:
74
  return "No timetable uploaded."
75
 
76
+ df = pd.read_excel(file)
77
+ empty_slots = df[df.isnull().any(axis=1)]
78
+
79
+ for index, row in empty_slots.iterrows():
80
+ query = f"Suggest a subject and faculty for an empty slot on {row.get('Day', 'Unknown')} at {row.get('Time', 'Unknown')}."
81
+ suggestion = ask_tinyllama_api(query)
82
+ try:
83
+ subject, faculty = suggestion.split(", Faculty: ")
84
+ df.loc[index, "Subject"] = subject.strip()
85
+ df.loc[index, "Faculty"] = faculty.strip()
86
+ except:
87
+ continue
88
+
89
+ output = BytesIO()
90
+ df.to_excel(output, index=False, engine='openpyxl')
91
+ output.seek(0)
92
+ return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  # βœ… AI Query Section
95
  st.markdown("## πŸ€– Ask TinyLlama AI About Your Timetable")
 
104
  selected_file = st.selectbox("Choose a timetable file to auto-fill missing slots:", list(uploaded_files.keys()))
105
 
106
  if st.button("Auto-Schedule"):
107
+ if uploaded_files[selected_file]:
108
+ scheduled_file = auto_schedule(uploaded_files[selected_file])
109
+ st.download_button("πŸ“₯ Download Auto-Scheduled Timetable", scheduled_file, file_name=f"{selected_file}_auto.xlsx", mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
 
 
 
110
  else:
111
+ st.write("⚠️ Please upload a file first.")
112
 
113
+ # βœ… Display & Edit Uploaded Timetables (DOCX + XLSX)
114
  st.markdown("## πŸ“œ View & Edit Uploaded Timetables")
115
 
116
  for name, file in uploaded_files.items():
117
  if file:
118
  if file.name.endswith(".xlsx"):
119
+ df = load_xlsx(file)
120
  edited_df = st.data_editor(df, num_rows="dynamic")
121
+ csv_output = edited_df.to_csv(index=False).encode()
122
+ st.download_button("πŸ“₯ Download Edited Excel", csv_output, file_name=f"{name}.csv", mime="text/csv")
123
+
124
  elif file.name.endswith(".docx"):
125
+ doc_text = load_docx(file)
126
+ edited_text = st.text_area(f"πŸ“„ Edit {name}:", doc_text, height=400)
127
+ if st.button(f"πŸ’Ύ Save & Download {name}"):
128
+ docx_output = save_docx(edited_text)
129
+ st.download_button("πŸ“₯ Download Edited DOCX", docx_output, file_name=f"{name}.docx", mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
130
+
131
+ # βœ… Export to PDF
 
 
 
 
 
132
  st.markdown("## πŸ“„ Export to PDF")
133
  if st.button("Export to PDF"):
134
  pdf_output = BytesIO()
 
142
  c.save()
143
  pdf_output.seek(0)
144
  st.download_button("πŸ“₯ Download PDF", pdf_output, file_name="timetable.pdf", mime="application/pdf")
145
+