jake2004 commited on
Commit
e88f414
Β·
verified Β·
1 Parent(s): 19959fd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -150
app.py CHANGED
@@ -1,153 +1,111 @@
1
- import streamlit as st
2
- import pandas as pd
3
  import openpyxl
4
- import docx
 
5
  from io import BytesIO
6
- from reportlab.pdfgen import canvas
7
  from reportlab.lib.pagesizes import letter
8
- from huggingface_hub import InferenceClient
9
-
10
- # πŸ”‘ Get Hugging Face API Key from User
11
- API_KEY = st.text_input("Enter your Hugging Face API Key:", type="password")
12
-
13
- if API_KEY:
14
- # Load Hugging Face TinyLlama Model
15
- @st.cache_resource
16
- def load_huggingface_client():
17
- return InferenceClient(model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", token=API_KEY)
18
-
19
- client = load_huggingface_client()
20
-
21
- # Function to generate AI text suggestions
22
- def generate_suggestion(prompt):
23
- response = client.text_generation(prompt, max_new_tokens=100)
24
- return response.strip()
25
-
26
- # Function to load Word document
27
- def load_docx(file):
28
- doc = docx.Document(file)
29
- return "\n".join([para.text for para in doc.paragraphs])
30
-
31
- # Function to save Word document
32
- def save_docx(text):
33
- output = BytesIO()
34
- doc = docx.Document()
35
- for line in text.split("\n"):
36
- doc.add_paragraph(line)
37
- doc.save(output)
38
- return output
39
-
40
- # Function to load Excel file
41
- def load_excel(file):
42
- return pd.ExcelFile(file)
43
-
44
- # Function to edit Excel with full tools
45
- def edit_excel(df, file_key):
46
- st.write(f"### Editing Excel: {file_key}")
47
-
48
- # Editable DataFrame
49
- edited_df = st.data_editor(df, num_rows="dynamic", use_container_width=True)
50
-
51
- # Apply Formatting Options
52
- col_to_format = st.selectbox(f"Select Column to Format in {file_key}:", df.columns, key=f"col_{file_key}")
53
- if st.button(f"Apply Bold Format - {file_key}", key=f"btn_{file_key}"):
54
- edited_df[col_to_format] = edited_df[col_to_format].apply(lambda x: f"**{x}**")
55
-
56
- return edited_df
57
-
58
- # Function to generate PDF
59
- def save_pdf(text):
60
- output = BytesIO()
61
- c = canvas.Canvas(output, pagesize=letter)
62
- c.setFont("Helvetica", 12)
63
- y_position = 750
64
- for line in text.split("\n"):
65
- c.drawString(100, y_position, line)
66
- y_position -= 20
67
- c.save()
68
- return output
69
-
70
- # 🏠 Streamlit UI
71
- st.title("πŸ“‚ RAG + TinyLlama NLP File Manager")
72
- st.write("Upload, edit, and manage `.docx`, `.xls` files with AI-powered NLP and full Excel tools.")
73
-
74
- # πŸ“€ File Uploaders
75
- uploaded_files = {}
76
- for i in range(1, 5):
77
- uploaded_files[f"File {i}"] = st.file_uploader(f"πŸ“„ Upload File {i}", type=["docx", "xls"])
78
-
79
- # ✏️ File Editors
80
- edited_docs = {}
81
- edited_excels = {}
82
-
83
- for file_key, file in uploaded_files.items():
84
- if file:
85
- st.subheader(f"πŸ“ Editing {file_key}: {file.name}")
86
-
87
- if file.name.endswith(".docx"):
88
- text = load_docx(file)
89
- edited_text = st.text_area(f"Edit {file.name}:", text, height=300)
90
-
91
- # AI Text Suggestion
92
- if st.button(f"✨ Generate AI Suggestion for {file.name}", key=f"suggest_{file_key}"):
93
- suggestion = generate_suggestion(edited_text)
94
- st.text_area("πŸ€– AI Suggestion:", suggestion, height=200)
95
-
96
- edited_docs[file.name] = edited_text
97
-
98
- elif file.name.endswith(".xls"):
99
- xls = load_excel(file)
100
- sheet_name = st.selectbox(f"πŸ“Š Select Sheet in {file.name}:", xls.sheet_names, key=f"sheet_{file_key}")
101
- df = pd.read_excel(xls, sheet_name=sheet_name)
102
- edited_df = edit_excel(df, file_key)
103
- edited_excels[file.name] = edited_df
104
-
105
- # πŸ“₯ Download Buttons
106
- for file_name, text in edited_docs.items():
107
- st.download_button(
108
- label=f"πŸ“₯ Download {file_name}",
109
- data=save_docx(text).getvalue(),
110
- file_name=file_name,
111
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
112
- )
113
-
114
- # PDF Download Option
115
- st.download_button(
116
- label=f"πŸ“₯ Download {file_name} as PDF",
117
- data=save_pdf(text).getvalue(),
118
- file_name=f"{file_name}.pdf",
119
- mime="application/pdf"
120
- )
121
-
122
- for file_name, df in edited_excels.items():
123
- output = BytesIO()
124
- with pd.ExcelWriter(output, engine="openpyxl") as writer:
125
- df.to_excel(writer, index=False, sheet_name="EditedSheet")
126
- writer.close()
127
-
128
- st.download_button(
129
- label=f"πŸ“₯ Download {file_name}",
130
- data=output.getvalue(),
131
- file_name=file_name,
132
- mime="application/octet-stream" # FIXED MIME TYPE
133
- )
134
-
135
- # πŸ—¨οΈ Chat with TinyLlama about Timetable Conflicts
136
- st.subheader("πŸ—“οΈ Timetable Conflict Checker")
137
- query = st.text_input("Ask about conflicts in the uploaded Timetables:")
138
-
139
- if query:
140
- conflict_info = "No conflicts detected." # Default response
141
- for file_key, file in uploaded_files.items():
142
- if file and file.name.endswith(".xls"):
143
- xls = load_excel(file)
144
- for sheet in xls.sheet_names:
145
- df = pd.read_excel(xls, sheet_name=sheet)
146
- if "Monday" in df.columns: # Adjust this based on column headers
147
- monday_data = df["Monday"].dropna().astype(str).tolist()
148
- response = generate_suggestion(f"Analyze this schedule: {monday_data}. Find conflicts.")
149
- if "conflict" in response.lower():
150
- conflict_info = response
151
-
152
- st.write("πŸ“’ **Conflict Analysis:**")
153
- st.write(conflict_info)
 
1
+ import json
2
+ import requests
3
  import openpyxl
4
+ import pandas as pd
5
+ import streamlit as st
6
  from io import BytesIO
 
7
  from reportlab.lib.pagesizes import letter
8
+ from reportlab.pdfgen import canvas
9
+
10
+ # βœ… Streamlit UI Setup
11
+ st.set_page_config(page_title="AI-Powered Timetable", layout="wide")
12
+ st.markdown("<h1 style='text-align: center; color: #4CAF50;'>πŸ“… AI-Powered Timetable</h1>", unsafe_allow_html=True)
13
+
14
+ # βœ… API Key Input
15
+ st.sidebar.markdown("## πŸ”‘ Enter Hugging Face API Key")
16
+ hf_api_key = st.sidebar.text_input("API Key", type="password")
17
+
18
+ # βœ… File Upload Section
19
+ st.sidebar.markdown("## πŸ“‚ Upload Your Timetable Files")
20
+ uploaded_file = st.sidebar.file_uploader("Upload Timetable", type=["xlsx"])
21
+
22
+ # βœ… Load Timetable Data
23
+ def load_timetable(file):
24
+ if file:
25
+ df = pd.read_excel(file)
26
+ return df
27
+ return None
28
+
29
+ df = load_timetable(uploaded_file)
30
+
31
+ # βœ… Ask TinyLlama API
32
+ def ask_tinyllama_api(query):
33
+ if not hf_api_key:
34
+ return "Error: Please enter your API key."
35
+
36
+ url = "https://api-inference.huggingface.co/v1/chat/completions"
37
+ headers = {"Authorization": f"Bearer {hf_api_key}", "Content-Type": "application/json"}
38
+ payload = {
39
+ "model": "TinyLlama/TinyLlama-1.1B-Chat-v1.0",
40
+ "messages": [{"role": "user", "content": query}],
41
+ "max_tokens": 500
42
+ }
43
+
44
+ response = requests.post(url, headers=headers, json=payload)
45
+ if response.status_code == 200:
46
+ return response.json()["choices"][0]["message"]["content"]
47
+ else:
48
+ return f"API Error: {response.status_code} - {response.text}"
49
+
50
+ # βœ… Auto-Schedule Missing Slots
51
+ def auto_schedule(df):
52
+ if df is None:
53
+ return "No timetable uploaded."
54
+
55
+ empty_slots = df[df.isnull().any(axis=1)].index.tolist()
56
+ for idx in empty_slots:
57
+ query = f"Suggest a subject and faculty for the empty slot in row {idx+2}."
58
+ suggestion = ask_tinyllama_api(query)
59
+ try:
60
+ subject, faculty = suggestion.split(", Faculty: ")
61
+ df.at[idx, "Subject"] = subject.strip()
62
+ df.at[idx, "Faculty"] = faculty.strip()
63
+ except:
64
+ continue
65
+
66
+ return f"Auto-scheduling completed for {len(empty_slots)} slots."
67
+
68
+ # βœ… Convert DataFrame to PDF
69
+ def convert_to_pdf(df):
70
+ buffer = BytesIO()
71
+ pdf = canvas.Canvas(buffer, pagesize=letter)
72
+ pdf.setFont("Helvetica", 10)
73
+
74
+ pdf.drawString(30, 750, "AI-Powered Timetable")
75
+
76
+ y_position = 730
77
+ for i, row in df.iterrows():
78
+ pdf.drawString(30, y_position, str(row.values))
79
+ y_position -= 20
80
+ if y_position < 50:
81
+ pdf.showPage()
82
+ pdf.setFont("Helvetica", 10)
83
+ y_position = 750
84
+
85
+ pdf.save()
86
+ buffer.seek(0)
87
+ return buffer
88
+
89
+ # βœ… Display and Edit Timetable
90
+ if df is not None:
91
+ st.markdown("## πŸ“ Edit Your Timetable")
92
+ edited_df = st.data_editor(df, key="editable_table")
93
+
94
+ # βœ… Auto-Schedule Button
95
+ if st.button("Auto-Schedule Missing Slots"):
96
+ result = auto_schedule(edited_df)
97
+ st.write("βœ…", result)
98
+
99
+ # βœ… Download as PDF
100
+ if st.button("Download as PDF"):
101
+ pdf_buffer = convert_to_pdf(edited_df)
102
+ st.download_button("πŸ“₯ Download Timetable PDF", pdf_buffer, file_name="timetable.pdf", mime="application/pdf")
103
+
104
+ # βœ… AI Query Section
105
+ st.markdown("## πŸ€– Ask TinyLlama About Your Timetable")
106
+ user_query = st.text_input("Type your question here (e.g., 'Who is free at 10 AM on Monday?')")
107
+
108
+ if st.button("Ask AI via API"):
109
+ ai_response = ask_tinyllama_api(user_query)
110
+ st.write("🧠 **TinyLlama Suggests:**", ai_response)
111
+