Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -15,7 +15,6 @@ import glob
|
|
15 |
import os
|
16 |
import zipfile
|
17 |
|
18 |
-
# File type definitions
|
19 |
FILE_TYPES = {
|
20 |
"md": "π Markdown",
|
21 |
"txt": "π Text",
|
@@ -23,20 +22,26 @@ FILE_TYPES = {
|
|
23 |
"csv": "π CSV",
|
24 |
"xlsx": "π Excel",
|
25 |
"yaml": "βοΈ YAML",
|
26 |
-
"xml": "π XML"
|
|
|
|
|
|
|
27 |
}
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
|
|
33 |
if key not in st.session_state:
|
34 |
-
|
35 |
-
|
36 |
-
|
|
|
|
|
|
|
37 |
|
38 |
def create_zip_of_files(files):
|
39 |
-
"""Create a zip file containing all files"""
|
40 |
zip_buffer = BytesIO()
|
41 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
42 |
for file in files:
|
@@ -45,12 +50,11 @@ def create_zip_of_files(files):
|
|
45 |
return zip_buffer.getvalue()
|
46 |
|
47 |
def get_download_link(file_path):
|
48 |
-
|
49 |
-
if isinstance(file_path, bytes): # For zip files
|
50 |
b64 = base64.b64encode(file_path).decode()
|
51 |
href = f'data:application/zip;base64,{b64}'
|
52 |
filename = 'all_files.zip'
|
53 |
-
else:
|
54 |
with open(file_path, 'r', encoding='utf-8') as f:
|
55 |
content = f.read()
|
56 |
b64 = base64.b64encode(content.encode()).decode()
|
@@ -59,26 +63,26 @@ def get_download_link(file_path):
|
|
59 |
return f'<a href="{href}" download="{filename}">{filename}</a>'
|
60 |
|
61 |
def load_file(filepath):
|
62 |
-
"""Load file content"""
|
63 |
with open(filepath, 'r', encoding='utf-8') as f:
|
64 |
return f.read()
|
65 |
|
66 |
def encode_content(content):
|
67 |
-
"""Encode content to base64"""
|
68 |
return base64.b64encode(content.encode()).decode()
|
69 |
|
70 |
def decode_content(encoded_content):
|
71 |
-
"""Decode content from base64"""
|
72 |
return base64.b64decode(encoded_content.encode()).decode()
|
73 |
|
74 |
def parse_markdown_outline(content):
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
|
|
|
|
|
|
|
|
79 |
|
80 |
def combine_markdown_files():
|
81 |
-
"""Combine markdown files into a single document"""
|
82 |
all_files = glob.glob("*.md")
|
83 |
combined = []
|
84 |
for filepath in sorted(all_files):
|
@@ -87,8 +91,23 @@ def combine_markdown_files():
|
|
87 |
combined.append(f"# {filepath}\n\n{content}\n\n---\n\n")
|
88 |
return "".join(combined)
|
89 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
90 |
def display_file_manager():
|
91 |
-
"""Display file management sidebar with guaranteed unique button keys."""
|
92 |
st.sidebar.title("π File Management")
|
93 |
all_files = glob.glob("*.md")
|
94 |
all_files.sort(reverse=True)
|
@@ -97,7 +116,7 @@ def display_file_manager():
|
|
97 |
with col1:
|
98 |
if st.button("π Delete All", key="delete_all_files_button"):
|
99 |
for file in all_files:
|
100 |
-
if file != "README.md":
|
101 |
os.remove(file)
|
102 |
st.rerun()
|
103 |
with col2:
|
@@ -107,7 +126,6 @@ def display_file_manager():
|
|
107 |
|
108 |
st.sidebar.markdown("---")
|
109 |
|
110 |
-
# Create unique keys using file attributes
|
111 |
for idx, file in enumerate(all_files):
|
112 |
file_stat = os.stat(file)
|
113 |
unique_id = f"{idx}_{file_stat.st_size}_{file_stat.st_mtime}"
|
@@ -129,12 +147,10 @@ def display_file_manager():
|
|
129 |
st.rerun()
|
130 |
|
131 |
def create_markdown_tabs(content, filename):
|
132 |
-
"""Create tabs for markdown content viewing and editing"""
|
133 |
tab1, tab2 = st.tabs(["π Editor", "π Preview"])
|
134 |
|
135 |
with tab1:
|
136 |
-
edited_content = st.text_area("Edit your markdown", content, height=300,
|
137 |
-
key=f"edit_{filename}")
|
138 |
if edited_content != content:
|
139 |
st.session_state.file_data[filename] = edited_content
|
140 |
content = edited_content
|
@@ -150,7 +166,6 @@ def create_markdown_tabs(content, filename):
|
|
150 |
return content
|
151 |
|
152 |
def read_file_content(uploaded_file):
|
153 |
-
"""Smart file reader with enhanced markdown handling"""
|
154 |
file_type = uploaded_file.name.split('.')[-1].lower()
|
155 |
try:
|
156 |
if file_type == 'md':
|
@@ -159,27 +174,32 @@ def read_file_content(uploaded_file):
|
|
159 |
f.write(content)
|
160 |
return content, "md"
|
161 |
elif file_type in ['csv', 'xlsx']:
|
162 |
-
|
|
|
|
|
|
|
163 |
return df.to_string(), file_type
|
164 |
elif file_type == 'json':
|
165 |
return json.dumps(json.load(uploaded_file), indent=2), "json"
|
166 |
elif file_type == 'yaml':
|
167 |
return yaml.dump(yaml.safe_load(uploaded_file)), "yaml"
|
|
|
|
|
|
|
|
|
168 |
else:
|
169 |
-
|
|
|
170 |
except Exception as e:
|
171 |
st.error(f"π¨ Error reading {uploaded_file.name}: {str(e)}")
|
172 |
return None, None
|
173 |
|
174 |
def main():
|
175 |
st.set_page_config(page_title="Markdown Handler", layout="wide")
|
176 |
-
|
177 |
-
# Display file manager in sidebar
|
178 |
display_file_manager()
|
179 |
|
180 |
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
|
181 |
|
182 |
-
# Add tabs for different views
|
183 |
upload_tab, book_tab = st.tabs(["π€ File Upload", "π Book View"])
|
184 |
|
185 |
with upload_tab:
|
@@ -187,7 +207,7 @@ def main():
|
|
187 |
|
188 |
with col1:
|
189 |
single_uploaded_file = st.file_uploader(
|
190 |
-
"π€ Upload single file",
|
191 |
type=list(FILE_TYPES.keys()),
|
192 |
help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()]),
|
193 |
key="single_uploader"
|
@@ -198,24 +218,24 @@ def main():
|
|
198 |
"π Upload multiple files",
|
199 |
type=list(FILE_TYPES.keys()),
|
200 |
accept_multiple_files=True,
|
201 |
-
help="Upload multiple files to view as a book",
|
202 |
key="multiple_uploader"
|
203 |
)
|
204 |
|
205 |
-
# Process uploads
|
206 |
if single_uploaded_file:
|
207 |
content, file_type = read_file_content(single_uploaded_file)
|
208 |
-
if content is not None:
|
209 |
st.success(f"π Loaded {FILE_TYPES.get(file_type, 'π')} file: {single_uploaded_file.name}")
|
|
|
|
|
210 |
|
211 |
if multiple_uploaded_files:
|
212 |
for uploaded_file in multiple_uploaded_files:
|
213 |
content, file_type = read_file_content(uploaded_file)
|
214 |
-
if content is not None:
|
215 |
st.success(f"π Loaded {uploaded_file.name}")
|
216 |
st.rerun()
|
217 |
|
218 |
-
# Show current file if selected
|
219 |
if st.session_state.current_file and st.session_state.file_content:
|
220 |
st.markdown("---")
|
221 |
create_markdown_tabs(st.session_state.file_content, st.session_state.current_file)
|
@@ -227,6 +247,13 @@ def main():
|
|
227 |
st.markdown(combined_content, unsafe_allow_html=True)
|
228 |
else:
|
229 |
st.info("Upload some markdown files to see them combined here!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
230 |
|
231 |
if __name__ == "__main__":
|
232 |
-
main()
|
|
|
15 |
import os
|
16 |
import zipfile
|
17 |
|
|
|
18 |
FILE_TYPES = {
|
19 |
"md": "π Markdown",
|
20 |
"txt": "π Text",
|
|
|
22 |
"csv": "π CSV",
|
23 |
"xlsx": "π Excel",
|
24 |
"yaml": "βοΈ YAML",
|
25 |
+
"xml": "π XML",
|
26 |
+
"mp4": "π¬ MP4",
|
27 |
+
"webm": "π¬ WEBM",
|
28 |
+
"ogg": "π¬ OGG"
|
29 |
}
|
30 |
|
31 |
+
for key in [
|
32 |
+
'file_data', 'file_types', 'md_outline', 'rendered_content', 'file_history',
|
33 |
+
'md_versions', 'md_files_history', 'combined_markdown', 'current_file',
|
34 |
+
'file_content'
|
35 |
+
]:
|
36 |
if key not in st.session_state:
|
37 |
+
if key in ['file_data', 'file_types', 'md_outline', 'rendered_content', 'md_versions']:
|
38 |
+
st.session_state[key] = {}
|
39 |
+
elif key in ['file_history', 'md_files_history']:
|
40 |
+
st.session_state[key] = []
|
41 |
+
else:
|
42 |
+
st.session_state[key] = ""
|
43 |
|
44 |
def create_zip_of_files(files):
|
|
|
45 |
zip_buffer = BytesIO()
|
46 |
with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
|
47 |
for file in files:
|
|
|
50 |
return zip_buffer.getvalue()
|
51 |
|
52 |
def get_download_link(file_path):
|
53 |
+
if isinstance(file_path, bytes):
|
|
|
54 |
b64 = base64.b64encode(file_path).decode()
|
55 |
href = f'data:application/zip;base64,{b64}'
|
56 |
filename = 'all_files.zip'
|
57 |
+
else:
|
58 |
with open(file_path, 'r', encoding='utf-8') as f:
|
59 |
content = f.read()
|
60 |
b64 = base64.b64encode(content.encode()).decode()
|
|
|
63 |
return f'<a href="{href}" download="{filename}">{filename}</a>'
|
64 |
|
65 |
def load_file(filepath):
|
|
|
66 |
with open(filepath, 'r', encoding='utf-8') as f:
|
67 |
return f.read()
|
68 |
|
69 |
def encode_content(content):
|
|
|
70 |
return base64.b64encode(content.encode()).decode()
|
71 |
|
72 |
def decode_content(encoded_content):
|
|
|
73 |
return base64.b64decode(encoded_content.encode()).decode()
|
74 |
|
75 |
def parse_markdown_outline(content):
|
76 |
+
return [
|
77 |
+
{
|
78 |
+
'level': len(line.split()[0]),
|
79 |
+
'title': line.strip('#').strip(),
|
80 |
+
'indent': ' ' * (len(line.split()[0]) - 1)
|
81 |
+
}
|
82 |
+
for line in content.split('\n') if line.strip().startswith('#')
|
83 |
+
]
|
84 |
|
85 |
def combine_markdown_files():
|
|
|
86 |
all_files = glob.glob("*.md")
|
87 |
combined = []
|
88 |
for filepath in sorted(all_files):
|
|
|
91 |
combined.append(f"# {filepath}\n\n{content}\n\n---\n\n")
|
92 |
return "".join(combined)
|
93 |
|
94 |
+
def combine_video_files():
|
95 |
+
video_files = [f for f in glob.glob("*") if f.split(".")[-1].lower() in ["mp4", "webm", "ogg"]]
|
96 |
+
video_html = []
|
97 |
+
for vf in video_files:
|
98 |
+
with open(vf, "rb") as f:
|
99 |
+
b64_video = base64.b64encode(f.read()).decode("utf-8")
|
100 |
+
ext = vf.split(".")[-1].lower()
|
101 |
+
mime_type = "video/mp4" if ext == "mp4" else f"video/{ext}"
|
102 |
+
video_html.append(f"""
|
103 |
+
<video width="640" height="480" controls autoplay muted loop>
|
104 |
+
<source src="data:{mime_type};base64,{b64_video}" type="{mime_type}">
|
105 |
+
</video>
|
106 |
+
<br><hr>
|
107 |
+
""")
|
108 |
+
return "".join(video_html)
|
109 |
+
|
110 |
def display_file_manager():
|
|
|
111 |
st.sidebar.title("π File Management")
|
112 |
all_files = glob.glob("*.md")
|
113 |
all_files.sort(reverse=True)
|
|
|
116 |
with col1:
|
117 |
if st.button("π Delete All", key="delete_all_files_button"):
|
118 |
for file in all_files:
|
119 |
+
if file != "README.md":
|
120 |
os.remove(file)
|
121 |
st.rerun()
|
122 |
with col2:
|
|
|
126 |
|
127 |
st.sidebar.markdown("---")
|
128 |
|
|
|
129 |
for idx, file in enumerate(all_files):
|
130 |
file_stat = os.stat(file)
|
131 |
unique_id = f"{idx}_{file_stat.st_size}_{file_stat.st_mtime}"
|
|
|
147 |
st.rerun()
|
148 |
|
149 |
def create_markdown_tabs(content, filename):
|
|
|
150 |
tab1, tab2 = st.tabs(["π Editor", "π Preview"])
|
151 |
|
152 |
with tab1:
|
153 |
+
edited_content = st.text_area("Edit your markdown", content, height=300, key=f"edit_{filename}")
|
|
|
154 |
if edited_content != content:
|
155 |
st.session_state.file_data[filename] = edited_content
|
156 |
content = edited_content
|
|
|
166 |
return content
|
167 |
|
168 |
def read_file_content(uploaded_file):
|
|
|
169 |
file_type = uploaded_file.name.split('.')[-1].lower()
|
170 |
try:
|
171 |
if file_type == 'md':
|
|
|
174 |
f.write(content)
|
175 |
return content, "md"
|
176 |
elif file_type in ['csv', 'xlsx']:
|
177 |
+
if file_type == 'csv':
|
178 |
+
df = pd.read_csv(uploaded_file)
|
179 |
+
else:
|
180 |
+
df = pd.read_excel(uploaded_file)
|
181 |
return df.to_string(), file_type
|
182 |
elif file_type == 'json':
|
183 |
return json.dumps(json.load(uploaded_file), indent=2), "json"
|
184 |
elif file_type == 'yaml':
|
185 |
return yaml.dump(yaml.safe_load(uploaded_file)), "yaml"
|
186 |
+
elif file_type in ['mp4', 'webm', 'ogg']:
|
187 |
+
with open(uploaded_file.name, 'wb') as f:
|
188 |
+
f.write(uploaded_file.getvalue())
|
189 |
+
return None, file_type
|
190 |
else:
|
191 |
+
content = uploaded_file.getvalue().decode()
|
192 |
+
return content, "txt"
|
193 |
except Exception as e:
|
194 |
st.error(f"π¨ Error reading {uploaded_file.name}: {str(e)}")
|
195 |
return None, None
|
196 |
|
197 |
def main():
|
198 |
st.set_page_config(page_title="Markdown Handler", layout="wide")
|
|
|
|
|
199 |
display_file_manager()
|
200 |
|
201 |
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
|
202 |
|
|
|
203 |
upload_tab, book_tab = st.tabs(["π€ File Upload", "π Book View"])
|
204 |
|
205 |
with upload_tab:
|
|
|
207 |
|
208 |
with col1:
|
209 |
single_uploaded_file = st.file_uploader(
|
210 |
+
"π€ Upload single file",
|
211 |
type=list(FILE_TYPES.keys()),
|
212 |
help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()]),
|
213 |
key="single_uploader"
|
|
|
218 |
"π Upload multiple files",
|
219 |
type=list(FILE_TYPES.keys()),
|
220 |
accept_multiple_files=True,
|
221 |
+
help="Upload multiple files to view as a book or video playlist",
|
222 |
key="multiple_uploader"
|
223 |
)
|
224 |
|
|
|
225 |
if single_uploaded_file:
|
226 |
content, file_type = read_file_content(single_uploaded_file)
|
227 |
+
if content is not None and file_type != "txt":
|
228 |
st.success(f"π Loaded {FILE_TYPES.get(file_type, 'π')} file: {single_uploaded_file.name}")
|
229 |
+
elif content is not None:
|
230 |
+
st.success(f"π Loaded file: {single_uploaded_file.name}")
|
231 |
|
232 |
if multiple_uploaded_files:
|
233 |
for uploaded_file in multiple_uploaded_files:
|
234 |
content, file_type = read_file_content(uploaded_file)
|
235 |
+
if content is not None or file_type in ['mp4','webm','ogg']:
|
236 |
st.success(f"π Loaded {uploaded_file.name}")
|
237 |
st.rerun()
|
238 |
|
|
|
239 |
if st.session_state.current_file and st.session_state.file_content:
|
240 |
st.markdown("---")
|
241 |
create_markdown_tabs(st.session_state.file_content, st.session_state.current_file)
|
|
|
247 |
st.markdown(combined_content, unsafe_allow_html=True)
|
248 |
else:
|
249 |
st.info("Upload some markdown files to see them combined here!")
|
250 |
+
|
251 |
+
st.markdown("## π Video Gallery")
|
252 |
+
video_playlist = combine_video_files()
|
253 |
+
if video_playlist:
|
254 |
+
st.markdown(video_playlist, unsafe_allow_html=True)
|
255 |
+
else:
|
256 |
+
st.info("No videos found. Upload MP4, WEBM, or OGG files to see them here!")
|
257 |
|
258 |
if __name__ == "__main__":
|
259 |
+
main()
|