Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
from flask import Flask, request, render_template_string, send_file
|
2 |
import markdown
|
3 |
import imgkit
|
4 |
import os
|
@@ -12,25 +12,14 @@ app = Flask(__name__)
|
|
12 |
TEMP_DIR = os.path.join(os.getcwd(), "temp")
|
13 |
os.makedirs(TEMP_DIR, exist_ok=True)
|
14 |
|
15 |
-
#
|
16 |
-
DEFAULT_STYLES = {
|
17 |
-
"font_family": "'Arial', sans-serif",
|
18 |
-
"font_size": "16",
|
19 |
-
"text_color": "#333333",
|
20 |
-
"background_color": "#ffffff",
|
21 |
-
"code_bg_color": "#f4f4f4",
|
22 |
-
"code_padding": "15",
|
23 |
-
"custom_css": ""
|
24 |
-
}
|
25 |
|
26 |
def is_repo2markdown_format(text):
|
27 |
"""Detects if the text is in the Repo2Markdown format."""
|
28 |
return "## File Structure" in text and text.count("### File:") > 0
|
29 |
|
30 |
def parse_repo2markdown(text):
|
31 |
-
"""
|
32 |
-
Parses Repo2Markdown text, extracts files, and cleans content for display.
|
33 |
-
"""
|
34 |
components = []
|
35 |
# Regex to find sections starting with '### File:'
|
36 |
pattern = re.compile(r'### File: (.*?)\n([\s\S]*?)(?=\n### File:|\Z)', re.MULTILINE)
|
@@ -39,133 +28,118 @@ def parse_repo2markdown(text):
|
|
39 |
if first_match:
|
40 |
intro_text = text[:first_match.start()].strip()
|
41 |
if intro_text:
|
42 |
-
components.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
for match in pattern.finditer(text):
|
45 |
filename = match.group(1).strip()
|
46 |
raw_content = match.group(2).strip()
|
47 |
|
48 |
-
# Check if the
|
49 |
code_match = re.search(r'^```(\w*)\s*\n([\s\S]*?)\s*```$', raw_content, re.DOTALL)
|
50 |
|
51 |
if code_match:
|
52 |
-
# It's a code block; store the inner content and language
|
53 |
language = code_match.group(1)
|
54 |
inner_content = code_match.group(2).strip()
|
55 |
-
components.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
else:
|
57 |
# It's plain text (e.g., binary file notification)
|
58 |
-
components.append({
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
return components
|
61 |
|
62 |
-
|
63 |
-
def index():
|
64 |
-
"""Main route to handle parsing, component selection, and conversion."""
|
65 |
-
preview_html = None
|
66 |
-
download_available = False
|
67 |
-
error_message = None
|
68 |
-
components = []
|
69 |
-
final_markdown_to_render = ""
|
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 |
-
if comp_data['is_code_block']:
|
120 |
-
# Re-add the fences for rendering
|
121 |
-
reconstructed_content = f"```{comp_data['language']}\n{comp_data['content']}\n```"
|
122 |
-
else:
|
123 |
-
reconstructed_content = comp_data['content']
|
124 |
-
final_markdown_parts.append(f"### File: {comp_data['filename']}\n{reconstructed_content}")
|
125 |
-
|
126 |
-
final_markdown_to_render = "\n\n---\n\n".join(final_markdown_parts)
|
127 |
-
|
128 |
-
except Exception as e:
|
129 |
-
error_message = f"Error processing Repo2Markdown: {e}"
|
130 |
else:
|
131 |
-
#
|
132 |
-
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
table {{ border-collapse: collapse; width: 100%; }}
|
144 |
-
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
|
145 |
-
th {{ background-color: #f2f2f2; }}
|
146 |
-
img {{ max-width: 100%; height: auto; }}
|
147 |
-
pre {{ background: {styles['code_bg_color']}; padding: {styles['code_padding']}px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
|
148 |
-
code {{ background: {styles['code_bg_color']}; padding: 0.2em 0.4em; margin: 0; font-size: 85%; border-radius: 3px; }}
|
149 |
-
pre > code {{ padding: 0; margin: 0; font-size: inherit; background: transparent; border-radius: 0; }}
|
150 |
-
{styles['custom_css']}
|
151 |
-
</style>"""
|
152 |
-
full_html = f'<!DOCTYPE html><html><head><meta charset="UTF-8">{fontawesome_link}{style_block}</head><body>{html_content}</body></html>'
|
153 |
-
|
154 |
-
preview_html = full_html
|
155 |
-
download_available = True
|
156 |
-
|
157 |
-
if "download" in request.form:
|
158 |
-
if download_type == "html":
|
159 |
-
return send_file(BytesIO(full_html.encode("utf-8")), as_attachment=True, download_name="output.html", mimetype="text/html")
|
160 |
-
else:
|
161 |
-
png_path = os.path.join(TEMP_DIR, "output.png")
|
162 |
-
imgkit.from_string(full_html, png_path, options={"quiet": "", 'encoding': "UTF-8"})
|
163 |
-
return send_file(png_path, as_attachment=True, download_name="output.png", mimetype="image/png")
|
164 |
-
|
165 |
-
except Exception as e:
|
166 |
-
error_message = f"An error occurred during conversion: {e}"
|
167 |
-
print(f"Error: {traceback.format_exc()}")
|
168 |
-
|
169 |
return render_template_string("""
|
170 |
<!DOCTYPE html>
|
171 |
<html lang="en">
|
@@ -178,22 +152,21 @@ def index():
|
|
178 |
h1 { text-align: center; }
|
179 |
form { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
|
180 |
textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; padding: 10px; font-family: monospace; }
|
181 |
-
.controls { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 20px; margin-top: 20px; }
|
182 |
-
.main-actions { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
|
183 |
fieldset { border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin-top: 20px; }
|
184 |
legend { font-weight: bold; color: #555; padding: 0 10px; }
|
185 |
-
.style-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px; }
|
186 |
-
.style-grid > div { display: flex; flex-direction: column; }
|
187 |
-
label { margin-bottom: 5px; color: #666; font-size: 14px; }
|
188 |
-
select, input[type="number"], input[type="color"], input[type="text"], input[type="file"] { padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
|
189 |
button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; }
|
190 |
.action-btn { background-color: #007BFF; color: white; font-size: 16px; padding: 12px 20px;}
|
191 |
.action-btn:hover { background-color: #0056b3; }
|
192 |
-
.
|
|
|
|
|
193 |
.download-btn:hover { background-color: #218838; }
|
194 |
-
.
|
195 |
-
.
|
|
|
|
|
196 |
.info { color: #00529B; background-color: #BDE5F8; padding: 10px; border-radius: 5px; margin: 10px 0; }
|
|
|
197 |
.component-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; }
|
198 |
.component-container { border: 1px solid #e0e0e0; border-radius: 5px; background: #fafafa; }
|
199 |
.component-header { background: #f1f1f1; padding: 8px 12px; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; gap: 10px; }
|
@@ -203,79 +176,235 @@ def index():
|
|
203 |
.component-content textarea { height: 150px; }
|
204 |
.selection-controls { margin: 15px 0; display: flex; gap: 10px; }
|
205 |
</style>
|
206 |
-
<script>
|
207 |
-
function toggleAllComponents(checked) {
|
208 |
-
const checkboxes = document.querySelectorAll('.component-checkbox');
|
209 |
-
checkboxes.forEach(cb => cb.checked = checked);
|
210 |
-
}
|
211 |
-
</script>
|
212 |
</head>
|
213 |
<body>
|
214 |
<h1>Advanced Markdown Converter & Composer</h1>
|
215 |
-
<form
|
216 |
<fieldset>
|
217 |
-
<legend>
|
218 |
-
<div class="info">Paste
|
219 |
-
<textarea name="markdown_text" rows="8"
|
220 |
<div style="margin-top: 10px; display: flex; align-items: center; gap: 10px;">
|
221 |
-
<label for="
|
222 |
-
<input type="file"
|
|
|
|
|
|
|
223 |
</div>
|
224 |
</fieldset>
|
225 |
|
226 |
-
|
227 |
-
<
|
228 |
-
|
229 |
-
<
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
<div class="component-container">
|
236 |
-
<div class="component-header">
|
237 |
-
<input type="checkbox" name="include_comp_{{ loop.index0 }}" id="include_comp_{{ loop.index0 }}" class="component-checkbox" {% if comp.is_selected %}checked{% else %}checked{% endif %}>
|
238 |
-
<label for="include_comp_{{ loop.index0 }}">{{ comp.filename }}</label>
|
239 |
-
</div>
|
240 |
-
<div class="component-content">
|
241 |
-
<textarea readonly>{{ comp.content }}</textarea>
|
242 |
-
</div>
|
243 |
-
</div>
|
244 |
-
{% endfor %}
|
245 |
-
</div>
|
246 |
-
</fieldset>
|
247 |
-
{% endif %}
|
248 |
-
|
249 |
<fieldset>
|
250 |
-
<legend>
|
251 |
<div class="style-grid">
|
252 |
-
<div><label
|
253 |
-
<div><label
|
254 |
-
<div><label
|
255 |
-
<div><label
|
256 |
-
<div><label
|
257 |
-
<div><label
|
258 |
</div>
|
259 |
-
<div><input type="checkbox" id="include_fontawesome"
|
260 |
-
<div><label for="custom_css">Custom CSS:</label><textarea id="custom_css"
|
261 |
</fieldset>
|
262 |
|
263 |
<div class="controls">
|
264 |
<div class="main-actions">
|
265 |
-
<button type="
|
266 |
-
<div><label
|
267 |
-
|
268 |
</div>
|
269 |
</div>
|
270 |
</form>
|
271 |
|
272 |
-
|
273 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
274 |
</body>
|
275 |
</html>
|
276 |
-
"""
|
277 |
-
styles=styles, markdown_text=markdown_text, download_type=download_type, include_fontawesome=include_fontawesome,
|
278 |
-
download_available=download_available, preview_html=preview_html, error_message=error_message, components=components)
|
279 |
|
280 |
if __name__ == "__main__":
|
281 |
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
|
|
|
1 |
+
from flask import Flask, request, render_template_string, send_file, jsonify
|
2 |
import markdown
|
3 |
import imgkit
|
4 |
import os
|
|
|
12 |
TEMP_DIR = os.path.join(os.getcwd(), "temp")
|
13 |
os.makedirs(TEMP_DIR, exist_ok=True)
|
14 |
|
15 |
+
# --- UTILITY FUNCTIONS (Back-end) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
16 |
|
17 |
def is_repo2markdown_format(text):
|
18 |
"""Detects if the text is in the Repo2Markdown format."""
|
19 |
return "## File Structure" in text and text.count("### File:") > 0
|
20 |
|
21 |
def parse_repo2markdown(text):
|
22 |
+
"""Parses Repo2Markdown text, extracts files, and prepares them for the UI."""
|
|
|
|
|
23 |
components = []
|
24 |
# Regex to find sections starting with '### File:'
|
25 |
pattern = re.compile(r'### File: (.*?)\n([\s\S]*?)(?=\n### File:|\Z)', re.MULTILINE)
|
|
|
28 |
if first_match:
|
29 |
intro_text = text[:first_match.start()].strip()
|
30 |
if intro_text:
|
31 |
+
components.append({
|
32 |
+
'type': 'intro',
|
33 |
+
'filename': 'Introduction',
|
34 |
+
'content': intro_text,
|
35 |
+
'is_code_block': False,
|
36 |
+
'language': ''
|
37 |
+
})
|
38 |
|
39 |
for match in pattern.finditer(text):
|
40 |
filename = match.group(1).strip()
|
41 |
raw_content = match.group(2).strip()
|
42 |
|
43 |
+
# Check if the content is a single fenced code block and extract its parts
|
44 |
code_match = re.search(r'^```(\w*)\s*\n([\s\S]*?)\s*```$', raw_content, re.DOTALL)
|
45 |
|
46 |
if code_match:
|
|
|
47 |
language = code_match.group(1)
|
48 |
inner_content = code_match.group(2).strip()
|
49 |
+
components.append({
|
50 |
+
'type': 'file',
|
51 |
+
'filename': filename,
|
52 |
+
'content': inner_content,
|
53 |
+
'is_code_block': True,
|
54 |
+
'language': language
|
55 |
+
})
|
56 |
else:
|
57 |
# It's plain text (e.g., binary file notification)
|
58 |
+
components.append({
|
59 |
+
'type': 'file',
|
60 |
+
'filename': filename,
|
61 |
+
'content': raw_content,
|
62 |
+
'is_code_block': False,
|
63 |
+
'language': ''
|
64 |
+
})
|
65 |
|
66 |
return components
|
67 |
|
68 |
+
# --- API ENDPOINTS (Back-end) ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
|
70 |
+
@app.route('/parse', methods=['POST'])
|
71 |
+
def parse_endpoint():
|
72 |
+
"""Receives markdown text and returns parsed components as JSON."""
|
73 |
+
if 'markdown_file' in request.files and request.files['markdown_file'].filename != '':
|
74 |
+
file = request.files['markdown_file']
|
75 |
+
text = file.read().decode('utf-8')
|
76 |
+
else:
|
77 |
+
text = request.form.get('markdown_text', '')
|
78 |
+
|
79 |
+
if not text:
|
80 |
+
return jsonify({'error': 'No text or file provided.'}), 400
|
81 |
+
|
82 |
+
if is_repo2markdown_format(text):
|
83 |
+
try:
|
84 |
+
components = parse_repo2markdown(text)
|
85 |
+
return jsonify(components)
|
86 |
+
except Exception as e:
|
87 |
+
return jsonify({'error': f'Failed to parse Repo2Markdown: {str(e)}'}), 500
|
88 |
+
else:
|
89 |
+
# If not the special format, return it as a single "text" component
|
90 |
+
return jsonify([{'type': 'text', 'filename': 'Full Text', 'content': text}])
|
91 |
+
|
92 |
+
@app.route('/convert', methods=['POST'])
|
93 |
+
def convert_endpoint():
|
94 |
+
"""Receives final markdown and styles, returns HTML preview or PNG file."""
|
95 |
+
data = request.json
|
96 |
+
markdown_text = data.get('markdown_text', '')
|
97 |
+
styles = data.get('styles', {})
|
98 |
+
include_fontawesome = data.get('include_fontawesome', False)
|
99 |
+
download_type = data.get('download_type', 'png')
|
100 |
+
is_download_request = data.get('download', False)
|
101 |
+
|
102 |
+
if not markdown_text:
|
103 |
+
return jsonify({'error': 'No markdown content to convert.'}), 400
|
104 |
+
|
105 |
+
try:
|
106 |
+
html_content = markdown.markdown(markdown_text, extensions=['fenced_code', 'tables'])
|
107 |
|
108 |
+
fontawesome_link = '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">' if include_fontawesome else ""
|
109 |
+
style_block = f"""<style>
|
110 |
+
body {{ font-family: {styles.get('font_family', 'Arial, sans-serif')}; font-size: {styles.get('font_size', '16')}px; color: {styles.get('text_color', '#333')}; background-color: {styles.get('background_color', '#fff')}; padding: 25px; display: inline-block; }}
|
111 |
+
h3 {{ border-bottom: 1px solid #ccc; padding-bottom: 5px; margin-top: 2em; }}
|
112 |
+
table {{ border-collapse: collapse; width: 100%; }}
|
113 |
+
th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
|
114 |
+
th {{ background-color: #f2f2f2; }}
|
115 |
+
img {{ max-width: 100%; height: auto; }}
|
116 |
+
pre {{ background: {styles.get('code_bg_color', '#f4f4f4')}; padding: {styles.get('code_padding', '15')}px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
|
117 |
+
code {{ background: {styles.get('code_bg_color', '#f4f4f4')}; padding: 0.2em 0.4em; margin: 0; font-size: 85%; border-radius: 3px; }}
|
118 |
+
pre > code {{ padding: 0; margin: 0; font-size: inherit; background: transparent; border-radius: 0; }}
|
119 |
+
{styles.get('custom_css', '')}
|
120 |
+
</style>"""
|
121 |
+
full_html = f'<!DOCTYPE html><html><head><meta charset="UTF-8">{fontawesome_link}{style_block}</head><body>{html_content}</body></html>'
|
122 |
+
|
123 |
+
if is_download_request:
|
124 |
+
if download_type == 'html':
|
125 |
+
return send_file(BytesIO(full_html.encode("utf-8")), as_attachment=True, download_name="output.html", mimetype="text/html")
|
126 |
+
else: # PNG
|
127 |
+
png_path = os.path.join(TEMP_DIR, "output.png")
|
128 |
+
imgkit.from_string(full_html, png_path, options={"quiet": "", 'encoding': "UTF-8"})
|
129 |
+
return send_file(png_path, as_attachment=True, download_name="output.png", mimetype="image/png")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
130 |
else:
|
131 |
+
# Return HTML for preview
|
132 |
+
return jsonify({'preview_html': full_html})
|
133 |
|
134 |
+
except Exception as e:
|
135 |
+
traceback.print_exc()
|
136 |
+
return jsonify({'error': f'Failed to convert content: {str(e)}'}), 500
|
137 |
+
|
138 |
+
# --- MAIN PAGE (Front-end) ---
|
139 |
+
|
140 |
+
@app.route('/')
|
141 |
+
def index():
|
142 |
+
"""Serves the main HTML page with all the client-side JavaScript."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
return render_template_string("""
|
144 |
<!DOCTYPE html>
|
145 |
<html lang="en">
|
|
|
152 |
h1 { text-align: center; }
|
153 |
form { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
|
154 |
textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; padding: 10px; font-family: monospace; }
|
|
|
|
|
155 |
fieldset { border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin-top: 20px; }
|
156 |
legend { font-weight: bold; color: #555; padding: 0 10px; }
|
|
|
|
|
|
|
|
|
157 |
button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; }
|
158 |
.action-btn { background-color: #007BFF; color: white; font-size: 16px; padding: 12px 20px;}
|
159 |
.action-btn:hover { background-color: #0056b3; }
|
160 |
+
.generate-btn { background-color: #5a32a3; color: white; font-size: 16px; padding: 12px 20px; }
|
161 |
+
.generate-btn:hover { background-color: #4a298a; }
|
162 |
+
.download-btn { background-color: #28a745; color: white; display: none; } /* Hidden by default */
|
163 |
.download-btn:hover { background-color: #218838; }
|
164 |
+
.controls { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 20px; margin-top: 20px; }
|
165 |
+
.main-actions { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
|
166 |
+
.preview-container { border: 1px solid #ddd; padding: 20px; margin-top: 20px; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05); min-height: 100px; }
|
167 |
+
.error { color: #D8000C; background-color: #FFD2D2; padding: 10px; border-radius: 5px; margin-top: 15px; display: none; }
|
168 |
.info { color: #00529B; background-color: #BDE5F8; padding: 10px; border-radius: 5px; margin: 10px 0; }
|
169 |
+
/* Component Selection Styles */
|
170 |
.component-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; }
|
171 |
.component-container { border: 1px solid #e0e0e0; border-radius: 5px; background: #fafafa; }
|
172 |
.component-header { background: #f1f1f1; padding: 8px 12px; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; gap: 10px; }
|
|
|
176 |
.component-content textarea { height: 150px; }
|
177 |
.selection-controls { margin: 15px 0; display: flex; gap: 10px; }
|
178 |
</style>
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
</head>
|
180 |
<body>
|
181 |
<h1>Advanced Markdown Converter & Composer</h1>
|
182 |
+
<form id="main-form">
|
183 |
<fieldset>
|
184 |
+
<legend>1. Load Content</legend>
|
185 |
+
<div class="info">Paste content or upload a file, then click "Load & Analyze".</div>
|
186 |
+
<textarea id="markdown-text-input" name="markdown_text" rows="8"></textarea>
|
187 |
<div style="margin-top: 10px; display: flex; align-items: center; gap: 10px;">
|
188 |
+
<label for="markdown-file-input">Or upload a file:</label>
|
189 |
+
<input type="file" id="markdown-file-input" name="markdown_file" accept=".md,.txt,text/markdown">
|
190 |
+
</div>
|
191 |
+
<div style="margin-top: 15px;">
|
192 |
+
<button type="button" id="load-btn" class="action-btn">Load & Analyze</button>
|
193 |
</div>
|
194 |
</fieldset>
|
195 |
|
196 |
+
<fieldset id="components-fieldset" style="display:none;">
|
197 |
+
<legend>2. Select Components</legend>
|
198 |
+
<div class="selection-controls">
|
199 |
+
<button type="button" onclick="toggleAllComponents(true)">Select All</button>
|
200 |
+
<button type="button" onclick="toggleAllComponents(false)">Deselect All</button>
|
201 |
+
</div>
|
202 |
+
<div id="components-container" class="component-grid"></div>
|
203 |
+
</fieldset>
|
204 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
205 |
<fieldset>
|
206 |
+
<legend>3. Configure Styles</legend>
|
207 |
<div class="style-grid">
|
208 |
+
<div><label>Font Family:</label><select id="font_family"><option value="'Arial', sans-serif">Arial</option><option value="'Georgia', serif">Georgia</option><option value="'Times New Roman', serif">Times New Roman</option></select></div>
|
209 |
+
<div><label>Font Size (px):</label><input type="number" id="font_size" value="16"></div>
|
210 |
+
<div><label>Text Color:</label><input type="color" id="text_color" value="#333333"></div>
|
211 |
+
<div><label>Background Color:</label><input type="color" id="background_color" value="#ffffff"></div>
|
212 |
+
<div><label>Code BG Color:</label><input type="color" id="code_bg_color" value="#f4f4f4"></div>
|
213 |
+
<div><label>Code Padding (px):</label><input type="number" id="code_padding" value="15"></div>
|
214 |
</div>
|
215 |
+
<div><input type="checkbox" id="include_fontawesome"><label for="include_fontawesome">Include Font Awesome</label></div>
|
216 |
+
<div><label for="custom_css">Custom CSS:</label><textarea id="custom_css" rows="3"></textarea></div>
|
217 |
</fieldset>
|
218 |
|
219 |
<div class="controls">
|
220 |
<div class="main-actions">
|
221 |
+
<button type="button" id="generate-btn" class="generate-btn">Generate Preview</button>
|
222 |
+
<div><label>Output format:</label><select id="download_type"><option value="png">PNG</option><option value="html">HTML</option></select></div>
|
223 |
+
<button type="button" id="download-btn" class="download-btn">Download</button>
|
224 |
</div>
|
225 |
</div>
|
226 |
</form>
|
227 |
|
228 |
+
<div id="error-box" class="error"></div>
|
229 |
+
|
230 |
+
<h2>Preview</h2>
|
231 |
+
<div id="preview-container" class="preview-container"></div>
|
232 |
+
|
233 |
+
<script>
|
234 |
+
// --- DOM Elements ---
|
235 |
+
const loadBtn = document.getElementById('load-btn');
|
236 |
+
const generateBtn = document.getElementById('generate-btn');
|
237 |
+
const downloadBtn = document.getElementById('download-btn');
|
238 |
+
const markdownTextInput = document.getElementById('markdown-text-input');
|
239 |
+
const markdownFileInput = document.getElementById('markdown-file-input');
|
240 |
+
const componentsFieldset = document.getElementById('components-fieldset');
|
241 |
+
const componentsContainer = document.getElementById('components-container');
|
242 |
+
const previewContainer = document.getElementById('preview-container');
|
243 |
+
const errorBox = document.getElementById('error-box');
|
244 |
+
|
245 |
+
// --- Client-Side Functions ---
|
246 |
+
function toggleAllComponents(checked) {
|
247 |
+
componentsContainer.querySelectorAll('.component-checkbox').forEach(cb => cb.checked = checked);
|
248 |
+
}
|
249 |
+
|
250 |
+
function displayError(message) {
|
251 |
+
errorBox.textContent = message;
|
252 |
+
errorBox.style.display = 'block';
|
253 |
+
previewContainer.innerHTML = '';
|
254 |
+
}
|
255 |
+
|
256 |
+
// --- Event Listeners ---
|
257 |
+
loadBtn.addEventListener('click', async () => {
|
258 |
+
loadBtn.textContent = 'Loading...';
|
259 |
+
errorBox.style.display = 'none';
|
260 |
+
|
261 |
+
const formData = new FormData();
|
262 |
+
if (markdownFileInput.files.length > 0) {
|
263 |
+
formData.append('markdown_file', markdownFileInput.files[0]);
|
264 |
+
} else {
|
265 |
+
formData.append('markdown_text', markdownTextInput.value);
|
266 |
+
}
|
267 |
+
|
268 |
+
try {
|
269 |
+
const response = await fetch('/parse', { method: 'POST', body: formData });
|
270 |
+
const components = await response.json();
|
271 |
+
|
272 |
+
if (components.error) {
|
273 |
+
throw new Error(components.error);
|
274 |
+
}
|
275 |
+
|
276 |
+
// Clear previous components
|
277 |
+
componentsContainer.innerHTML = '';
|
278 |
+
|
279 |
+
if (components.length > 1 || components[0]?.type !== 'text') {
|
280 |
+
componentsFieldset.style.display = 'block';
|
281 |
+
components.forEach((comp, index) => {
|
282 |
+
const div = document.createElement('div');
|
283 |
+
div.className = 'component-container';
|
284 |
+
div.dataset.filename = comp.filename;
|
285 |
+
div.dataset.type = comp.type;
|
286 |
+
div.dataset.isCodeBlock = comp.is_code_block;
|
287 |
+
div.dataset.language = comp.language;
|
288 |
+
// Store content in a hidden div to avoid issues with textarea rendering
|
289 |
+
const contentHolder = document.createElement('div');
|
290 |
+
contentHolder.style.display = 'none';
|
291 |
+
contentHolder.textContent = comp.content;
|
292 |
+
div.appendChild(contentHolder);
|
293 |
+
|
294 |
+
div.innerHTML += `
|
295 |
+
<div class="component-header">
|
296 |
+
<input type="checkbox" id="comp-check-${index}" class="component-checkbox" checked>
|
297 |
+
<label for="comp-check-${index}">${comp.filename}</label>
|
298 |
+
</div>
|
299 |
+
<div class="component-content">
|
300 |
+
<textarea readonly>${comp.content}</textarea>
|
301 |
+
</div>`;
|
302 |
+
componentsContainer.appendChild(div);
|
303 |
+
});
|
304 |
+
} else {
|
305 |
+
// Not Repo2Markdown format, hide the component selector
|
306 |
+
componentsFieldset.style.display = 'none';
|
307 |
+
}
|
308 |
+
// Populate the text area if a file was uploaded
|
309 |
+
if(markdownFileInput.files.length > 0) {
|
310 |
+
markdownTextInput.value = await markdownFileInput.files[0].text();
|
311 |
+
}
|
312 |
+
|
313 |
+
|
314 |
+
} catch (err) {
|
315 |
+
displayError('Error parsing content: ' + err.message);
|
316 |
+
} finally {
|
317 |
+
loadBtn.textContent = 'Load & Analyze';
|
318 |
+
}
|
319 |
+
});
|
320 |
+
|
321 |
+
async function handleGeneration(isDownload = false) {
|
322 |
+
const buttonToUpdate = isDownload ? downloadBtn : generateBtn;
|
323 |
+
buttonToUpdate.textContent = 'Generating...';
|
324 |
+
errorBox.style.display = 'none';
|
325 |
+
|
326 |
+
let finalMarkdown = "";
|
327 |
+
// If components are visible, compose from them. Otherwise, use the text area.
|
328 |
+
if (componentsFieldset.style.display === 'block') {
|
329 |
+
const parts = [];
|
330 |
+
const componentDivs = componentsContainer.querySelectorAll('.component-container');
|
331 |
+
componentDivs.forEach(div => {
|
332 |
+
if (div.querySelector('.component-checkbox').checked) {
|
333 |
+
const content = div.querySelector('div').textContent; // Get content from hidden holder
|
334 |
+
let partContent = content;
|
335 |
+
if (div.dataset.isCodeBlock === 'true') {
|
336 |
+
partContent = "```" + div.dataset.language + "\\n" + content + "\\n```";
|
337 |
+
}
|
338 |
+
|
339 |
+
if (div.dataset.type === 'intro') {
|
340 |
+
parts.push(partContent);
|
341 |
+
} else {
|
342 |
+
parts.push(`### File: ${div.dataset.filename}\\n${partContent}`);
|
343 |
+
}
|
344 |
+
}
|
345 |
+
});
|
346 |
+
finalMarkdown = parts.join('\\n\\n---\\n\\n');
|
347 |
+
} else {
|
348 |
+
finalMarkdown = markdownTextInput.value;
|
349 |
+
}
|
350 |
+
|
351 |
+
const payload = {
|
352 |
+
markdown_text: finalMarkdown,
|
353 |
+
styles: {
|
354 |
+
font_family: document.getElementById('font_family').value,
|
355 |
+
font_size: document.getElementById('font_size').value,
|
356 |
+
text_color: document.getElementById('text_color').value,
|
357 |
+
background_color: document.getElementById('background_color').value,
|
358 |
+
code_bg_color: document.getElementById('code_bg_color').value,
|
359 |
+
code_padding: document.getElementById('code_padding').value,
|
360 |
+
custom_css: document.getElementById('custom_css').value
|
361 |
+
},
|
362 |
+
include_fontawesome: document.getElementById('include_fontawesome').checked,
|
363 |
+
download_type: document.getElementById('download_type').value,
|
364 |
+
download: isDownload
|
365 |
+
};
|
366 |
+
|
367 |
+
try {
|
368 |
+
const response = await fetch('/convert', {
|
369 |
+
method: 'POST',
|
370 |
+
headers: { 'Content-Type': 'application/json' },
|
371 |
+
body: JSON.stringify(payload)
|
372 |
+
});
|
373 |
+
|
374 |
+
if (isDownload) {
|
375 |
+
if (!response.ok) throw new Error(`Download failed: ${response.statusText}`);
|
376 |
+
const blob = await response.blob();
|
377 |
+
const url = window.URL.createObjectURL(blob);
|
378 |
+
const a = document.createElement('a');
|
379 |
+
a.style.display = 'none';
|
380 |
+
a.href = url;
|
381 |
+
a.download = 'output.' + payload.download_type;
|
382 |
+
document.body.appendChild(a);
|
383 |
+
a.click();
|
384 |
+
window.URL.revokeObjectURL(url);
|
385 |
+
a.remove();
|
386 |
+
} else {
|
387 |
+
const result = await response.json();
|
388 |
+
if (result.error) throw new Error(result.error);
|
389 |
+
previewContainer.innerHTML = result.preview_html;
|
390 |
+
downloadBtn.style.display = 'inline-block'; // Show download button after a successful preview
|
391 |
+
}
|
392 |
+
|
393 |
+
} catch (err) {
|
394 |
+
displayError('Error generating output: ' + err.message);
|
395 |
+
} finally {
|
396 |
+
generateBtn.textContent = 'Generate Preview';
|
397 |
+
downloadBtn.textContent = 'Download';
|
398 |
+
}
|
399 |
+
}
|
400 |
+
|
401 |
+
generateBtn.addEventListener('click', () => handleGeneration(false));
|
402 |
+
downloadBtn.addEventListener('click', () => handleGeneration(true));
|
403 |
+
|
404 |
+
</script>
|
405 |
</body>
|
406 |
</html>
|
407 |
+
""")
|
|
|
|
|
408 |
|
409 |
if __name__ == "__main__":
|
410 |
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
|