SalexAI commited on
Commit
f7150c2
·
verified ·
1 Parent(s): 62d1bab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -233
app.py CHANGED
@@ -1,239 +1,34 @@
1
- import json
2
- import gradio as gr
3
  import os
 
4
 
5
- # Store the lists data (in-memory database)
6
- lists = {}
7
 
8
- # Define a simple Gradio app for UniShare
9
- def unishare_app():
10
- # Main UI components
11
- with gr.Blocks(css="""
12
- .list-card {
13
- background: white;
14
- padding: 16px;
15
- border-radius: 10px;
16
- box-shadow: 0 2px 5px rgba(0,0,0,0.1);
17
- margin-bottom: 16px;
18
- cursor: pointer;
19
- }
20
- .list-card:hover {
21
- transform: scale(1.02);
22
- transition: transform 0.2s;
23
- }
24
- .item-grid {
25
- display: grid;
26
- grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
27
- gap: 16px;
28
- }
29
- .item-card {
30
- background: #f9f9f9;
31
- padding: 16px;
32
- border-radius: 10px;
33
- box-shadow: 0 1px 3px rgba(0,0,0,0.05);
34
- }
35
- .back-btn {
36
- margin-bottom: 16px;
37
- }
38
- """) as demo:
39
- gr.Markdown("# UniShare")
40
-
41
- # Overview page
42
- with gr.Tab("Overview"):
43
- overview_container = gr.HTML()
44
-
45
- def update_overview():
46
- html = ""
47
- if lists:
48
- for list_name, list_data in lists.items():
49
- html += f"""
50
- <div class="list-card" onclick="switchToList('{list_name}')">
51
- <h3>{list_name}</h3>
52
- <p>{len(list_data)} sections</p>
53
- </div>
54
- """
55
- else:
56
- html = "<p>No lists found. Add some data first!</p>"
57
-
58
- # Add JavaScript to handle navigation
59
- html += """
60
- <script>
61
- function switchToList(name) {
62
- // Using Gradio's built-in tab switching
63
- const tabs = document.querySelectorAll('.tabs > button');
64
- if (tabs.length > 1) {
65
- tabs[1].click(); // Click the "View List" tab
66
- // Set the list name in the dropdown
67
- const listSelect = document.getElementById('list-selector');
68
- for (let i = 0; i < listSelect.options.length; i++) {
69
- if (listSelect.options[i].value === name) {
70
- listSelect.selectedIndex = i;
71
- // Trigger change event
72
- const event = new Event('change');
73
- listSelect.dispatchEvent(event);
74
- break;
75
- }
76
- }
77
- }
78
- }
79
- </script>
80
- """
81
- return html
82
 
83
- # Update overview on page load
84
- demo.load(update_overview, [], [overview_container])
85
-
86
- # View list page
87
- with gr.Tab("View List"):
88
- gr.Markdown("## View List")
89
-
90
- # List selector dropdown
91
- list_selector = gr.Dropdown(
92
- label="Select a list",
93
- choices=list(lists.keys()) if lists else [],
94
- interactive=True,
95
- elem_id="list-selector"
96
- )
97
-
98
- # Container for list items
99
- list_content = gr.HTML()
100
-
101
- # Back button (visual only, actual navigation handled by JS)
102
- gr.Button("Back to Overview", elem_classes=["back-btn"]).click(
103
- lambda: gr.Tabs(selected=0), # This is a hack to trigger tab switching
104
- [],
105
- []
106
- )
107
-
108
- # Function to display list items
109
- def display_list(list_name):
110
- if not list_name or list_name not in lists:
111
- return "<p>Please select a valid list</p>"
112
-
113
- sections = lists[list_name]
114
- html = ""
115
-
116
- for section in sections:
117
- html += f"<div class='section-card'><h3>{section.get('sectionTitle', 'Untitled Section')}</h3>"
118
- html += "<div class='item-grid'>"
119
-
120
- for item in section.get('items', []):
121
- title = item.get('title', 'Untitled')
122
- link = item.get('link', '#')
123
-
124
- html += f"<div class='item-card'>"
125
- html += f"<strong>{title}</strong><br>"
126
-
127
- if link.lower().endswith(('.jpeg', '.jpg', '.gif', '.png')):
128
- html += f"<img src='{link}' alt='{title}' style='max-width:100%; max-height:150px; margin:10px 0;'><br>"
129
-
130
- html += f"<a href='{link}' download style='color:#3b82f6; text-decoration:none;'>Download</a>"
131
- html += "</div>"
132
-
133
- html += "</div></div>"
134
-
135
- return html
136
-
137
- # Update list content when selection changes
138
- list_selector.change(
139
- display_list,
140
- [list_selector],
141
- [list_content]
142
- )
143
-
144
- # Admin page for data management
145
- with gr.Tab("Admin"):
146
- gr.Markdown("## Data Management")
147
-
148
- with gr.Row():
149
- with gr.Column():
150
- gr.Markdown("### Add New List Data")
151
- list_name_input = gr.Textbox(label="List Name")
152
- json_data = gr.Textbox(
153
- label="Section Data (JSON format)",
154
- lines=10,
155
- placeholder='''
156
- {
157
- "sectionTitle": "Sample Section",
158
- "items": [
159
- {
160
- "title": "Sample Item",
161
- "link": "https://example.com/sample.jpg"
162
- }
163
- ]
164
- }'''
165
- )
166
-
167
- add_button = gr.Button("Add Data")
168
- add_result = gr.Markdown()
169
-
170
- def add_data(list_name, data_json):
171
- if not list_name:
172
- return "Error: List name is required"
173
-
174
- try:
175
- data = json.loads(data_json)
176
- if list_name not in lists:
177
- lists[list_name] = []
178
-
179
- lists[list_name].append(data)
180
-
181
- # Update dropdown choices (will reflect on next page load)
182
- list_selector.choices = list(lists.keys())
183
-
184
- return f"Success: Data added to {list_name}"
185
- except json.JSONDecodeError:
186
- return "Error: Invalid JSON format"
187
- except Exception as e:
188
- return f"Error: {str(e)}"
189
-
190
- add_button.click(
191
- add_data,
192
- [list_name_input, json_data],
193
- [add_result]
194
- )
195
-
196
- with gr.Column():
197
- gr.Markdown("### View All Data")
198
- view_data_button = gr.Button("View All Data")
199
- data_output = gr.JSON()
200
-
201
- def get_all_data():
202
- return lists
203
-
204
- view_data_button.click(
205
- get_all_data,
206
- [],
207
- [data_output]
208
- )
209
-
210
- # Add button to clear all data
211
- clear_button = gr.Button("Clear All Data", variant="stop")
212
- clear_result = gr.Markdown()
213
-
214
- def clear_data():
215
- lists.clear()
216
- list_selector.choices = []
217
- return "All data cleared"
218
-
219
- clear_button.click(
220
- clear_data,
221
- [],
222
- [clear_result]
223
- )
224
-
225
- # ... (keep all other imports and code the same)
226
 
227
- # Update UI components when data changes
228
- def refresh_ui():
229
- list_selector.choices = list(lists.keys())
230
-
231
- # Set up event handlers to refresh UI
232
- add_button.click(lambda: None, [], [], js="() => {window.location.reload()}")
233
- clear_button.click(lambda: None, [], [], js="() => {window.location.reload()}")
234
-
235
- return demo
236
 
237
- # Create and launch the app
238
- demo = unishare_app()
239
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
 
2
  import os
3
+ from datetime import datetime
4
 
5
+ app = Flask(__name__)
 
6
 
7
+ # Ensure output folder exists
8
+ os.makedirs("markdown_files", exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ @app.route("/create-md", methods=["POST"])
11
+ def create_markdown():
12
+ data = request.get_json()
13
+ if not data or "title" not in data or "content" not in data:
14
+ return jsonify({"error": "Missing 'title' or 'content'"}), 400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
+ title = data["title"].strip()
17
+ content = data["content"]
 
 
 
 
 
 
 
18
 
19
+ # Sanitize filename
20
+ filename = f"{title.replace(' ', '_')}_{int(datetime.utcnow().timestamp())}.md"
21
+ filepath = os.path.join("markdown_files", filename)
22
+
23
+ # Write markdown content
24
+ with open(filepath, "w", encoding="utf-8") as f:
25
+ f.write(f"# {title}\n\n{content}")
26
+
27
+ return jsonify({
28
+ "message": "Markdown file created",
29
+ "filename": filename,
30
+ "path": filepath
31
+ }), 201
32
+
33
+ if __name__ == "__main__":
34
+ app.run(host="0.0.0.0", port=7860)