jake2004 commited on
Commit
e819af9
Β·
verified Β·
1 Parent(s): cbe50e4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +126 -126
app.py CHANGED
@@ -7,129 +7,129 @@ from reportlab.pdfgen import canvas
7
  from reportlab.lib.pagesizes import letter
8
  from huggingface_hub import InferenceClient
9
 
10
- # Hugging Face API Key
11
- API_KEY = "hf_xxxxxxxxxxxxxxxxxxxxxxxx" # Replace with your Hugging Face API Key
12
-
13
- # Load Hugging Face TinyLlama Model
14
- @st.cache_resource
15
- def load_huggingface_client():
16
- return InferenceClient(model="TinyLlama/TinyLlama-1.1B-Chat-v1.0", token=API_KEY)
17
-
18
- client = load_huggingface_client()
19
-
20
- # Function to generate AI text suggestions using TinyLlama
21
- def generate_suggestion(prompt):
22
- response = client.text_generation(prompt, max_new_tokens=100)
23
- return response.strip()
24
-
25
- # Function to load Word document
26
- def load_docx(file):
27
- doc = docx.Document(file)
28
- return "\n".join([para.text for para in doc.paragraphs])
29
-
30
- # Function to save Word document
31
- def save_docx(text):
32
- output = BytesIO()
33
- doc = docx.Document()
34
- for line in text.split("\n"):
35
- doc.add_paragraph(line)
36
- doc.save(output)
37
- return output
38
-
39
- # Function to load Excel file
40
- def load_excel(file):
41
- return pd.ExcelFile(file)
42
-
43
- # Function to edit Excel file with full tool support
44
- def edit_excel(df):
45
- st.write("### Excel Editor with Full Editing Tools")
46
-
47
- # Display DataFrame and allow modifications
48
- edited_df = st.data_editor(df, num_rows="dynamic", use_container_width=True)
49
-
50
- # Provide additional Excel formatting options
51
- col_to_format = st.selectbox("Select Column to Format:", df.columns)
52
- if st.button("Apply Bold Format"):
53
- edited_df[col_to_format] = edited_df[col_to_format].apply(lambda x: f"**{x}**")
54
-
55
- return edited_df
56
-
57
- # Function to generate PDF
58
- def save_pdf(text):
59
- output = BytesIO()
60
- c = canvas.Canvas(output, pagesize=letter)
61
- c.setFont("Helvetica", 12)
62
- y_position = 750
63
- for line in text.split("\n"):
64
- c.drawString(100, y_position, line)
65
- y_position -= 20
66
- c.save()
67
- return output
68
-
69
- # Streamlit UI
70
- st.title("Advanced RAG + TinyLlama NLP File Manager")
71
- st.write("Upload, edit, and manage `.docx`, `.xls` files, with full Excel tools and AI-powered NLP.")
72
-
73
- # File Uploaders
74
- uploaded_files = [None] * 4
75
- file_types = ["docx", "xls", "docx", "xls"]
76
-
77
- for i in range(4):
78
- uploaded_files[i] = st.file_uploader(f"Upload File {i+1} ({file_types[i]})", type=[file_types[i]])
79
-
80
- # File Editors
81
- edited_docs = {}
82
- edited_excels = {}
83
-
84
- for i, file in enumerate(uploaded_files):
85
- if file:
86
- st.subheader(f"Editing File {i+1}: {file.name}")
87
-
88
- if file.name.endswith(".docx"):
89
- text = load_docx(file)
90
- edited_text = st.text_area(f"Edit {file.name}:", text, height=300)
91
-
92
- # AI text suggestion
93
- if st.button(f"Generate AI Suggestion for {file.name}"):
94
- suggestion = generate_suggestion(edited_text)
95
- st.text_area("AI Suggestion:", suggestion, height=200)
96
-
97
- edited_docs[file.name] = edited_text
98
-
99
- elif file.name.endswith(".xls"):
100
- xls = load_excel(file)
101
- sheet_name = st.selectbox(f"Select Sheet in {file.name}:", xls.sheet_names)
102
- df = pd.read_excel(xls, sheet_name=sheet_name)
103
- edited_df = edit_excel(df)
104
- edited_excels[file.name] = edited_df
105
-
106
- # Download Buttons
107
- for file_name, text in edited_docs.items():
108
- st.download_button(
109
- label=f"Download {file_name}",
110
- data=save_docx(text).getvalue(),
111
- file_name=file_name,
112
- mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
113
- )
114
-
115
- # PDF download option
116
- st.download_button(
117
- label=f"Download {file_name} as PDF",
118
- data=save_pdf(text).getvalue(),
119
- file_name=f"{file_name}.pdf",
120
- mime="application/pdf"
121
- )
122
-
123
- for file_name, df in edited_excels.items():
124
- output = BytesIO()
125
- with pd.ExcelWriter(output, engine="openpyxl") as writer:
126
- df.to_excel(writer, index=False, sheet_name="EditedSheet")
127
- writer.close()
128
-
129
- st.download_button(
130
- label=f"Download {file_name}",
131
- data=output.getvalue(),
132
- file_name=file_name,
133
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
134
- )
135
-
 
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):
46
+ st.write("### Excel Editor with Full Editing Tools")
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("Select Column to Format:", df.columns)
53
+ if st.button("Apply Bold Format"):
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 = [None] * 4
76
+ file_types = ["docx", "xls", "docx", "xls"]
77
+
78
+ for i in range(4):
79
+ uploaded_files[i] = st.file_uploader(f"πŸ“„ Upload File {i+1} ({file_types[i]})", type=[file_types[i]])
80
+
81
+ # ✏️ File Editors
82
+ edited_docs = {}
83
+ edited_excels = {}
84
+
85
+ for i, file in enumerate(uploaded_files):
86
+ if file:
87
+ st.subheader(f"πŸ“ Editing File {i+1}: {file.name}")
88
+
89
+ if file.name.endswith(".docx"):
90
+ text = load_docx(file)
91
+ edited_text = st.text_area(f"Edit {file.name}:", text, height=300)
92
+
93
+ # AI Text Suggestion
94
+ if st.button(f"✨ Generate AI Suggestion for {file.name}"):
95
+ suggestion = generate_suggestion(edited_text)
96
+ st.text_area("πŸ€– AI Suggestion:", suggestion, height=200)
97
+
98
+ edited_docs[file.name] = edited_text
99
+
100
+ elif file.name.endswith(".xls"):
101
+ xls = load_excel(file)
102
+ sheet_name = st.selectbox(f"πŸ“Š Select Sheet in {file.name}:", xls.sheet_names)
103
+ df = pd.read_excel(xls, sheet_name=sheet_name)
104
+ edited_df = edit_excel(df)
105
+ edited_excels[file.name] = edited_df
106
+
107
+ # πŸ“₯ Download Buttons
108
+ for file_name, text in edited_docs.items():
109
+ st.download_button(
110
+ label=f"πŸ“₯ Download {file_name}",
111
+ data=save_docx(text).getvalue(),
112
+ file_name=file_name,
113
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
114
+ )
115
+
116
+ # PDF Download Option
117
+ st.download_button(
118
+ label=f"πŸ“₯ Download {file_name} as PDF",
119
+ data=save_pdf(text).getvalue(),
120
+ file_name=f"{file_name}.pdf",
121
+ mime="application/pdf"
122
+ )
123
+
124
+ for file_name, df in edited_excels.items():
125
+ output = BytesIO()
126
+ with pd.ExcelWriter(output, engine="openpyxl") as writer:
127
+ df.to_excel(writer, index=False, sheet_name="EditedSheet")
128
+ writer.close()
129
+
130
+ st.download_button(
131
+ label=f"πŸ“₯ Download {file_name}",
132
+ data=output.getvalue(),
133
+ file_name=file_name,
134
+ mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
135
+ )