awacke1 commited on
Commit
0788402
Β·
verified Β·
1 Parent(s): 39fa99f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -47
app.py CHANGED
@@ -1,71 +1,172 @@
1
  import streamlit as st
 
2
  from pathlib import Path
3
  import json
 
 
 
 
 
 
 
 
 
4
 
5
- # πŸ¦„ Magical state initialization
6
  if 'file_data' not in st.session_state:
7
  st.session_state.file_data = {}
 
 
 
 
8
 
9
- def save_to_file(data, filename):
10
- """🌈 Rainbow file saver - spreading joy through data persistence!"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  try:
12
- with open(filename, 'w') as f:
13
- json.dump(data, f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  return True
15
  except Exception as e:
16
- st.error(f"Oopsie! πŸ™ˆ Couldn't save to {filename}: {str(e)}")
17
  return False
18
 
19
- def load_from_file(filename):
20
- """πŸŽ€ Pretty file loader - bringing your data back with style!"""
21
- try:
22
- with open(filename, 'r') as f:
23
- return json.load(f)
24
- except FileNotFoundError:
25
- st.info(f"✨ New adventure! No previous data found in {filename}")
26
- return {}
27
- except json.JSONDecodeError:
28
- st.warning(f"🎭 Hmm, the file {filename} contains invalid JSON. Starting fresh!")
29
- return {}
30
 
31
  def main():
32
- st.title("πŸŽ‰ Super Fun File Handler!")
33
 
34
- # 🎨 Pretty file upload section
35
- uploaded_file = st.file_uploader("Upload your happy little file!", type=['txt', 'json'])
 
 
 
 
36
 
37
  if uploaded_file:
38
- # πŸŽͺ Process the uploaded file with circus-level excitement!
39
- content = uploaded_file.getvalue().decode()
40
- st.session_state.file_data[uploaded_file.name] = content
41
- st.success(f"🌟 Woohoo! Successfully loaded {uploaded_file.name}")
 
 
 
 
 
 
42
 
43
- # 🎠 Display our magical collection of files
44
  if st.session_state.file_data:
45
- st.subheader("πŸ—‚οΈ Your Wonderful Files:")
46
  for filename, content in st.session_state.file_data.items():
47
- with st.expander(f"πŸ“ {filename}"):
48
- st.text_area("Content", content, height=150, key=filename)
 
 
 
 
 
 
49
 
50
- if st.button(f"πŸ’Ύ Save changes to {filename}"):
51
- updated_content = st.session_state[filename]
52
- if save_to_file(updated_content, filename):
53
- st.success(f"πŸŽ‰ Yay! Saved {filename} successfully!")
54
-
55
- # πŸŽͺ System prompt section
56
- st.subheader("πŸ€– Super Smart System Prompt Generator")
57
- if st.session_state.file_data:
58
- selected_files = st.multiselect(
59
- "Select files for your prompt",
60
- list(st.session_state.file_data.keys())
61
- )
62
-
63
- if selected_files:
64
- prompt = "Here are the contents of the selected files:\n\n"
65
- for file in selected_files:
66
- prompt += f"File: {file}\n```\n{st.session_state.file_data[file]}\n```\n\n"
67
-
68
- st.text_area("Generated Prompt", prompt, height=300)
69
 
70
  if __name__ == "__main__":
71
  main()
 
1
  import streamlit as st
2
+ from streamlit.components.v1 import html
3
  from pathlib import Path
4
  import json
5
+ import time
6
+ from datetime import datetime
7
+ import re
8
+ import pandas as pd
9
+ import markdown
10
+ import yaml
11
+ from io import StringIO
12
+ import openpyxl
13
+ import csv
14
 
15
+ # πŸ¦„βœ¨ Enhanced state initialization with file type tracking!
16
  if 'file_data' not in st.session_state:
17
  st.session_state.file_data = {}
18
+ if 'file_types' not in st.session_state:
19
+ st.session_state.file_types = {} # πŸ“ Track file types for special handling
20
+ if 'md_outline' not in st.session_state:
21
+ st.session_state.md_outline = {} # πŸ“‘ Store markdown outlines
22
 
23
+ # 🎯 Supported file types and their handlers
24
+ FILE_TYPES = {
25
+ "md": "πŸ“ Markdown",
26
+ "txt": "πŸ“„ Text",
27
+ "json": "πŸ”§ JSON",
28
+ "csv": "πŸ“Š CSV",
29
+ "xlsx": "πŸ“— Excel",
30
+ "yaml": "βš™οΈ YAML",
31
+ "xml": "πŸ”— XML"
32
+ }
33
+
34
+ def parse_markdown_outline(content):
35
+ """πŸ“‘ Generate a cute outline from markdown!"""
36
+ lines = content.split('\n')
37
+ outline = []
38
+ for line in lines:
39
+ if line.strip().startswith('#'):
40
+ level = len(line.split()[0]) # Count #'s
41
+ title = line.strip('#').strip()
42
+ outline.append({
43
+ 'level': level,
44
+ 'title': title,
45
+ 'indent': ' ' * (level - 1)
46
+ })
47
+ return outline
48
+
49
+ def read_file_content(uploaded_file):
50
+ """πŸ“š Smart file reader with type detection!"""
51
+ file_type = uploaded_file.name.split('.')[-1].lower()
52
+ try:
53
+ if file_type == 'md':
54
+ content = uploaded_file.getvalue().decode()
55
+ st.session_state.md_outline[uploaded_file.name] = parse_markdown_outline(content)
56
+ return content, "md"
57
+
58
+ elif file_type == 'csv':
59
+ df = pd.read_csv(uploaded_file)
60
+ return df.to_string(), "csv"
61
+
62
+ elif file_type == 'xlsx':
63
+ df = pd.read_excel(uploaded_file)
64
+ return df.to_string(), "xlsx"
65
+
66
+ elif file_type == 'json':
67
+ content = json.load(uploaded_file)
68
+ return json.dumps(content, indent=2), "json"
69
+
70
+ elif file_type == 'yaml':
71
+ content = yaml.safe_load(uploaded_file)
72
+ return yaml.dump(content), "yaml"
73
+
74
+ else: # Default text handling
75
+ return uploaded_file.getvalue().decode(), "txt"
76
+
77
+ except Exception as e:
78
+ st.error(f"🚨 Oops! Error reading {uploaded_file.name}: {str(e)}")
79
+ return None, None
80
+
81
+ def save_file_content(content, filename, file_type):
82
+ """πŸ’Ύ Smart file saver with type handling!"""
83
  try:
84
+ if file_type == "md":
85
+ with open(filename, 'w') as f:
86
+ f.write(content)
87
+
88
+ elif file_type in ["csv", "xlsx"]:
89
+ # Convert string back to DataFrame
90
+ df = pd.read_csv(StringIO(content)) if file_type == "csv" else pd.read_excel(StringIO(content))
91
+ if file_type == "csv":
92
+ df.to_csv(filename, index=False)
93
+ else:
94
+ df.to_excel(filename, index=False)
95
+
96
+ elif file_type == "json":
97
+ with open(filename, 'w') as f:
98
+ json.dump(json.loads(content), f, indent=2)
99
+
100
+ elif file_type == "yaml":
101
+ with open(filename, 'w') as f:
102
+ yaml.dump(yaml.safe_load(content), f)
103
+
104
+ else: # Default text handling
105
+ with open(filename, 'w') as f:
106
+ f.write(content)
107
+
108
  return True
109
  except Exception as e:
110
+ st.error(f"🚨 Error saving {filename}: {str(e)}")
111
  return False
112
 
113
+ def show_markdown_preview(content):
114
+ """πŸ‘€ Show pretty markdown preview!"""
115
+ st.markdown("### πŸ‘€ Markdown Preview")
116
+ st.markdown(content)
117
+
118
+ def show_markdown_outline(filename):
119
+ """πŸ“‘ Display pretty markdown outline!"""
120
+ if filename in st.session_state.md_outline:
121
+ st.markdown("### πŸ“‘ Document Outline")
122
+ for item in st.session_state.md_outline[filename]:
123
+ st.markdown(f"{item['indent']}β€’ {item['title']}")
124
 
125
  def main():
126
+ st.title("πŸ“šβœ¨ Super Smart File Handler with Markdown Magic! βœ¨πŸ“š")
127
 
128
+ # πŸ“ Enhanced file upload with type support
129
+ uploaded_file = st.file_uploader(
130
+ "πŸ“€ Upload your file!",
131
+ type=list(FILE_TYPES.keys()),
132
+ help="Supports: " + ", ".join([f"{v} (.{k})" for k, v in FILE_TYPES.items()])
133
+ )
134
 
135
  if uploaded_file:
136
+ content, file_type = read_file_content(uploaded_file)
137
+ if content is not None:
138
+ st.session_state.file_data[uploaded_file.name] = content
139
+ st.session_state.file_types[uploaded_file.name] = file_type
140
+ st.success(f"πŸŽ‰ Loaded {FILE_TYPES.get(file_type, 'πŸ“„')} file: {uploaded_file.name}")
141
+
142
+ # πŸ“ Special handling for markdown files
143
+ if file_type == "md":
144
+ show_markdown_preview(content)
145
+ show_markdown_outline(uploaded_file.name)
146
 
147
+ # πŸ“‚ File Display and Editing
148
  if st.session_state.file_data:
149
+ st.subheader("πŸ“‚ Your Files")
150
  for filename, content in st.session_state.file_data.items():
151
+ file_type = st.session_state.file_types[filename]
152
+ with st.expander(f"{FILE_TYPES.get(file_type, 'πŸ“„')} {filename}"):
153
+ edited_content = st.text_area(
154
+ "Content",
155
+ content,
156
+ height=300,
157
+ key=f"edit_{filename}"
158
+ )
159
 
160
+ if edited_content != content:
161
+ st.session_state.file_data[filename] = edited_content
162
+ if file_type == "md":
163
+ st.session_state.md_outline[filename] = parse_markdown_outline(edited_content)
164
+ show_markdown_preview(edited_content)
165
+ show_markdown_outline(filename)
166
+
167
+ if st.button(f"πŸ’Ύ Save {filename}"):
168
+ if save_file_content(edited_content, filename, file_type):
169
+ st.success(f"✨ Saved {filename} successfully!")
 
 
 
 
 
 
 
 
 
170
 
171
  if __name__ == "__main__":
172
  main()