Spaces:
Sleeping
Sleeping
File size: 6,465 Bytes
9d6ac78 0788402 39fa99f 0788402 39fa99f e3dc660 39fa99f 0788402 e3dc660 0788402 e3dc660 39fa99f e3dc660 0788402 e3dc660 0788402 e3dc660 0788402 e3dc660 0788402 e3dc660 0788402 e3dc660 0788402 e3dc660 39fa99f 0788402 e3dc660 0788402 39fa99f 0788402 39fa99f 0788402 b99f72a 0788402 b99f72a 39fa99f 0788402 b99f72a 39fa99f 0788402 39fa99f 0788402 e3dc660 0788402 e3dc660 0788402 39fa99f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
import streamlit as st
from streamlit.components.v1 import html
from pathlib import Path
import json
import time
from datetime import datetime
import re
import pandas as pd
import yaml
from io import StringIO
import openpyxl
import csv
# State initialization
if 'file_data' not in st.session_state:
st.session_state.file_data = {}
if 'file_types' not in st.session_state:
st.session_state.file_types = {}
if 'md_outline' not in st.session_state:
st.session_state.md_outline = {}
if 'rendered_content' not in st.session_state:
st.session_state.rendered_content = {}
# Supported file types and their handlers
FILE_TYPES = {
"md": "π Markdown",
"txt": "π Text",
"json": "π§ JSON",
"csv": "π CSV",
"xlsx": "π Excel",
"yaml": "βοΈ YAML",
"xml": "π XML"
}
def parse_markdown_outline(content):
"""Generate an outline from markdown content"""
lines = content.split('\n')
outline = []
for line in lines:
if line.strip().startswith('#'):
level = len(line.split()[0])
title = line.strip('#').strip()
outline.append({
'level': level,
'title': title,
'indent': ' ' * (level - 1)
})
return outline
def create_markdown_tabs(content, filename):
"""Create tabs for markdown content viewing and editing"""
tab1, tab2 = st.tabs(["π Editor", "π Preview"])
with tab1:
edited_content = st.text_area(
"Edit your markdown",
content,
height=300,
key=f"edit_{filename}"
)
if edited_content != content:
st.session_state.file_data[filename] = edited_content
st.session_state.md_outline[filename] = parse_markdown_outline(edited_content)
content = edited_content
with tab2:
st.markdown("### Preview")
st.markdown(content)
if filename in st.session_state.md_outline:
st.markdown("---")
st.markdown("### π Document Outline")
for item in st.session_state.md_outline[filename]:
st.markdown(f"{item['indent']}β’ {item['title']}")
return content
def read_file_content(uploaded_file):
"""Smart file reader with enhanced markdown handling"""
file_type = uploaded_file.name.split('.')[-1].lower()
try:
if file_type == 'md':
content = uploaded_file.getvalue().decode()
st.session_state.md_outline[uploaded_file.name] = parse_markdown_outline(content)
st.session_state.rendered_content[uploaded_file.name] = content
return content, "md"
elif file_type == 'csv':
df = pd.read_csv(uploaded_file)
return df.to_string(), "csv"
elif file_type == 'xlsx':
df = pd.read_excel(uploaded_file)
return df.to_string(), "xlsx"
elif file_type == 'json':
content = json.load(uploaded_file)
return json.dumps(content, indent=2), "json"
elif file_type == 'yaml':
content = yaml.safe_load(uploaded_file)
return yaml.dump(content), "yaml"
else: # Default text handling
return uploaded_file.getvalue().decode(), "txt"
except Exception as e:
st.error(f"π¨ Oops! Error reading {uploaded_file.name}: {str(e)}")
return None, None
def save_file_content(content, filename, file_type):
"""Smart file saver with enhanced markdown handling"""
try:
if file_type == "md":
with open(filename, 'w') as f:
f.write(content)
st.session_state.rendered_content[filename] = content
elif file_type in ["csv", "xlsx"]:
df = pd.read_csv(StringIO(content)) if file_type == "csv" else pd.read_excel(StringIO(content))
if file_type == "csv":
df.to_csv(filename, index=False)
else:
df.to_excel(filename, index=False)
elif file_type == "json":
with open(filename, 'w') as f:
json.dump(json.loads(content), f, indent=2)
elif file_type == "yaml":
with open(filename, 'w') as f:
yaml.dump(yaml.safe_load(content), f)
else: # Default text handling
with open(filename, 'w') as f:
f.write(content)
return True
except Exception as e:
st.error(f"π¨ Error saving {filename}: {str(e)}")
return False
def main():
st.title("πβ¨ Super Smart File Handler with Markdown Magic! β¨π")
uploaded_file = st.file_uploader(
"π€ Upload your file!",
type=list(FILE_TYPES.keys()),
help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()])
)
if uploaded_file:
content, file_type = read_file_content(uploaded_file)
if content is not None:
st.session_state.file_data[uploaded_file.name] = content
st.session_state.file_types[uploaded_file.name] = file_type
st.success(f"π Loaded {FILE_TYPES.get(file_type, 'π')} file: {uploaded_file.name}")
if st.session_state.file_data:
st.subheader("π Your Files")
for filename, content in st.session_state.file_data.items():
file_type = st.session_state.file_types[filename]
with st.expander(f"{FILE_TYPES.get(file_type, 'π')} {filename}"):
if file_type == "md":
content = create_markdown_tabs(content, filename)
else:
edited_content = st.text_area(
"Content",
content,
height=300,
key=f"edit_{filename}"
)
if edited_content != content:
st.session_state.file_data[filename] = edited_content
content = edited_content
if st.button(f"πΎ Save {filename}"):
if save_file_content(content, filename, file_type):
st.success(f"β¨ Saved {filename} successfully!")
if __name__ == "__main__":
main() |