broadfield-dev commited on
Commit
368bed4
·
verified ·
1 Parent(s): 12eb749

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +308 -0
app.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, render_template_string, send_file, jsonify
2
+ import markdown
3
+ import imgkit
4
+ import os
5
+ import traceback
6
+ from io import BytesIO
7
+ import re
8
+ import base64
9
+ from pygments import highlight
10
+ from pygments.lexers import get_lexer_by_name
11
+ from pygments.formatters import HtmlFormatter
12
+ from pygments.styles import get_all_styles
13
+
14
+ app = Flask(__name__)
15
+
16
+ TEMP_DIR = os.path.join(os.getcwd(), "temp")
17
+ os.makedirs(TEMP_DIR, exist_ok=True)
18
+
19
+ # --- FORMAT PARSING AND DETECTION (Unchanged) ---
20
+ def parse_repo2markdown(text):
21
+ components = []
22
+ pattern = re.compile(r'### File: (.*?)\n([\s\S]*?)(?=\n### File:|\Z)', re.MULTILINE)
23
+ first_match = pattern.search(text)
24
+ if first_match:
25
+ intro_text = text[:first_match.start()].strip()
26
+ if intro_text:
27
+ components.append({'type': 'intro', 'filename': 'Introduction', 'content': intro_text, 'is_code_block': False, 'language': ''})
28
+ for match in pattern.finditer(text):
29
+ filename = match.group(1).strip()
30
+ raw_content = match.group(2).strip()
31
+ code_match = re.search(r'^```(\w*)\s*\n([\s\S]*?)\s*```$', raw_content, re.DOTALL)
32
+ if code_match:
33
+ components.append({'type': 'file', 'filename': filename, 'content': code_match.group(2).strip(), 'is_code_block': True, 'language': code_match.group(1)})
34
+ else:
35
+ components.append({'type': 'file', 'filename': filename, 'content': raw_content, 'is_code_block': False, 'language': ''})
36
+ return components
37
+
38
+ def parse_standard_readme(text):
39
+ components = []
40
+ parts = re.split(r'^(## .*?)$', text, flags=re.MULTILINE)
41
+ intro_content = parts[0].strip()
42
+ if intro_content:
43
+ components.append({'type': 'intro', 'filename': 'Introduction', 'content': intro_content})
44
+ for i in range(1, len(parts), 2):
45
+ components.append({'type': 'section', 'filename': parts[i].replace('##', '').strip(), 'content': parts[i+1].strip()})
46
+ return components
47
+
48
+ def parse_changelog(text):
49
+ components = []
50
+ parts = re.split(r'^(## \[\d+\.\d+\.\d+.*?\].*?)$', text, flags=re.MULTILINE)
51
+ intro_content = parts[0].strip()
52
+ if intro_content:
53
+ components.append({'type': 'intro', 'filename': 'Changelog Header', 'content': intro_content})
54
+ for i in range(1, len(parts), 2):
55
+ components.append({'type': 'version', 'filename': parts[i].replace('##', '').strip(), 'content': parts[i+1].strip()})
56
+ return components
57
+
58
+
59
+ @app.route('/parse', methods=['POST'])
60
+ def parse_endpoint():
61
+ text = request.form.get('markdown_text', '')
62
+ if 'markdown_file' in request.files and request.files['markdown_file'].filename != '':
63
+ text = request.files['markdown_file'].read().decode('utf-8')
64
+ if not text: return jsonify({'error': 'No text or file provided.'}), 400
65
+
66
+ try:
67
+ if "## File Structure" in text and "### File:" in text:
68
+ format_name, components = "Repo2Markdown", parse_repo2markdown(text)
69
+ elif re.search(r'^## \[\d+\.\d+\.\d+.*?\].*?$', text, flags=re.MULTILINE):
70
+ format_name, components = "Changelog", parse_changelog(text)
71
+ elif text.strip().startswith("#") and re.search(r'^## ', text, flags=re.MULTILINE):
72
+ format_name, components = "Standard README", parse_standard_readme(text)
73
+ else:
74
+ format_name, components = "Unknown", [{'type': 'text', 'filename': 'Full Text', 'content': text}]
75
+ return jsonify({'format': format_name, 'components': components})
76
+ except Exception as e:
77
+ return jsonify({'error': f'Failed to parse: {e}'}), 500
78
+
79
+ # --- HTML & PNG BUILDER (Unchanged but correct logic) ---
80
+ def build_full_html(markdown_text, styles, include_fontawesome):
81
+ wrapper_id = "#output-wrapper"
82
+ font_family = styles.get('font_family', "'Arial', sans-serif")
83
+ google_font_name = font_family.split(',')[0].strip("'\"")
84
+ google_font_link = ""
85
+ if " " in google_font_name and google_font_name not in ["Times New Roman", "Courier New"]:
86
+ google_font_link = f'<link href="https://fonts.googleapis.com/css2?family={google_font_name.replace(" ", "+")}:wght@400;700&display=swap" rel="stylesheet">'
87
+
88
+ highlight_theme = styles.get('highlight_theme', 'default')
89
+ pygments_css = ""
90
+ if highlight_theme != 'none':
91
+ formatter = HtmlFormatter(style=highlight_theme, cssclass="codehilite")
92
+ pygments_css = formatter.get_style_defs(f' {wrapper_id}')
93
+
94
+ scoped_css = f"""
95
+ {wrapper_id} {{
96
+ font-family: {font_family}; font-size: {styles.get('font_size', '16')}px;
97
+ color: {styles.get('text_color', '#333')}; background-color: {styles.get('background_color', '#fff')};
98
+ }}
99
+ /* ... other scoped styles ... */
100
+
101
+ {wrapper_id} table {{ border-collapse: collapse; width: 100%; }}
102
+ {wrapper_id} th, {wrapper_id} td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
103
+ {wrapper_id} th {{ background-color: #f2f2f2; }}
104
+ {wrapper_id} img {{ max-width: 100%; height: auto; }}
105
+ {wrapper_id} pre {{ padding: {styles.get('code_padding', '15')}px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
106
+ {wrapper_id} h1, {wrapper_id} h2, {wrapper_id} h3 {{ border-bottom: 1px solid #eee; padding-bottom: 5px; margin-top: 1.5em; }}
107
+ {wrapper_id} :not(pre) > code {{ font-family: 'Courier New', monospace; background-color: #eef; padding: .2em .4em; border-radius: 3px; }}
108
+ {pygments_css} {styles.get('custom_css', '')}
109
+ """
110
+
111
+ md_extensions = ['fenced_code', 'tables', 'codehilite']
112
+ html_content = markdown.markdown(markdown_text, extensions=md_extensions, extension_configs={'codehilite': {'css_class': 'codehilite'}})
113
+ final_html_body = f'<div id="output-wrapper">{html_content}</div>'
114
+
115
+ 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 ""
116
+
117
+ full_html = f"""<!DOCTYPE html>
118
+ <html><head><meta charset="UTF-8">{google_font_link}{fontawesome_link}<style>
119
+ #ouput-wrapper {{ background-color: {styles.get('background_color', '#fff')}; padding: 25px; display: inline-block;}}
120
+ {scoped_css}
121
+ </style></head><body>{final_html_body}</body></html>"""
122
+
123
+ return full_html
124
+
125
+ # --- API ENDPOINT for Conversion (CHANGED) ---
126
+ @app.route('/convert', methods=['POST'])
127
+ def convert_endpoint():
128
+ data = request.json
129
+ try:
130
+ full_html = build_full_html(
131
+ markdown_text=data.get('markdown_text', ''),
132
+ styles=data.get('styles', {}),
133
+ include_fontawesome=data.get('include_fontawesome', False)
134
+ )
135
+ # Define options here to avoid repetition and add the required fix
136
+ options = {"quiet": "", 'encoding': "UTF-8", "--no-cache": ""}
137
+
138
+ if data.get('download', False):
139
+ download_type = data.get('download_type', 'png')
140
+ if download_type == 'html':
141
+ return send_file(BytesIO(full_html.encode("utf-8")), as_attachment=True, download_name="output.html", mimetype="text/html")
142
+ else:
143
+ png_bytes = imgkit.from_string(full_html, False, options=options)
144
+ return send_file(BytesIO(png_bytes), as_attachment=True, download_name="output.png", mimetype="image/png")
145
+ else:
146
+ png_bytes = imgkit.from_string(full_html, False, options=options)
147
+ png_base64 = base64.b64encode(png_bytes).decode('utf-8')
148
+ return jsonify({'preview_html': full_html, 'preview_png_base64': png_base64})
149
+ except Exception as e:
150
+ traceback.print_exc()
151
+ return jsonify({'error': f'Failed to convert content: {str(e)}'}), 500
152
+
153
+ # --- MAIN PAGE RENDERER (with corrected CSS) ---
154
+ @app.route('/')
155
+ def index():
156
+ highlight_styles = sorted(list(get_all_styles()))
157
+ return render_template_string("""
158
+ <!DOCTYPE html>
159
+ <html lang="en">
160
+ <head>
161
+ <meta charset="UTF-8">
162
+ <title>Intelligent Markdown Converter</title>
163
+ <style>
164
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #f9f9f9; }
165
+ h1, h2 { text-align: center; color: #333; }
166
+ form { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
167
+ textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; padding: 10px; font-family: monospace; }
168
+ fieldset { border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin-top: 20px; }
169
+ legend { font-weight: bold; color: #555; padding: 0 10px; }
170
+ select, input[type="number"], input[type="color"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;}
171
+ button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; }
172
+ .action-btn { background-color: #007BFF; color: white; font-size: 16px; padding: 12px 20px;}
173
+ .generate-btn { background-color: #5a32a3; color: white; font-size: 16px; padding: 12px 20px; }
174
+ .download-btn { background-color: #28a745; color: white; display: none; }
175
+ .main-actions { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; margin-top: 20px; }
176
+ .preview-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid #eee; padding-bottom: 10px; margin-bottom: 15px; }
177
+ .preview-container { border: 1px solid #ddd; padding: 10px; margin-top: 20px; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05); min-height: 100px; }
178
+ .preview-container img { max-width: 100%; }
179
+ .error { color: #D8000C; background-color: #FFD2D2; padding: 10px; border-radius: 5px; margin-top: 15px; display: none; }
180
+ .info { color: #00529B; background-color: #BDE5F8; padding: 10px; border-radius: 5px; margin: 10px 0; display: none;}
181
+ .style-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 15px; align-items: end; }
182
+ .component-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; }
183
+ .component-container { border: 1px solid #e0e0e0; border-radius: 5px; background: #fafafa; }
184
+ .component-header { background: #f1f1f1; padding: 8px 12px; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; gap: 10px; }
185
+ .component-content textarea { height: 150px; } /* <-- FIXED: Taller text area */
186
+ .selection-controls { margin: 15px 0; display: flex; gap: 10px; }
187
+ </style>
188
+ </head>
189
+ <body>
190
+ <h1>Intelligent Markdown Converter</h1>
191
+ <form id="main-form" onsubmit="return false;">
192
+ <!-- Input and Styling sections -->
193
+ <fieldset><legend>1. Load Content</legend><div id="info-box" class="info"></div><textarea id="markdown-text-input" name="markdown_text" rows="8"></textarea><div style="margin-top: 10px; display: flex; align-items: center; gap: 10px;"><label for="markdown-file-input">Or upload a file:</label><input type="file" id="markdown-file-input" name="markdown_file" accept=".md,.txt,text/markdown"></div><div style="margin-top: 15px;"><button type="button" id="load-btn" class="action-btn">Load & Analyze</button></div></fieldset>
194
+ <fieldset id="components-fieldset" style="display:none;"><legend>2. Select Components</legend><div class="selection-controls"><button type="button" onclick="toggleAllComponents(true)">Select All</button><button type="button" onclick="toggleAllComponents(false)">Deselect All</button></div><div id="components-container" class="component-grid"></div></fieldset>
195
+ <fieldset><legend>3. Configure Styles</legend><div class="style-grid"><div><label>Font Family:</label><select id="font_family"><optgroup label="Sans-Serif"><option value="'Arial', sans-serif">Arial</option><option value="'Roboto', sans-serif">Roboto</option></optgroup><optgroup label="Serif"><option value="'Times New Roman', serif">Times New Roman</option><option value="'Georgia', serif">Georgia</option></optgroup></select></div><div><label>Font Size (px):</label><input type="number" id="font_size" value="16"></div><div><label>Highlight Theme:</label><select id="highlight_theme"><option value="none">None</option>{% for style in highlight_styles %}<option value="{{ style }}" {% if style == 'default' %}selected{% endif %}>{{ style }}</option>{% endfor %}</select></div><div><label>Text Color:</label><input type="color" id="text_color" value="#333333"></div><div><label>Background Color:</label><input type="color" id="background_color" value="#ffffff"></div><div><label>Code Padding (px):</label><input type="number" id="code_padding" value="15"></div></div><div><input type="checkbox" id="include_fontawesome"><label for="include_fontawesome">Include Font Awesome</label></div><div><label for="custom_css">Custom CSS:</label><textarea id="custom_css" rows="3"></textarea></div></fieldset>
196
+ <div class="main-actions"><button type="button" id="generate-btn" class="generate-btn">Generate Preview</button></div>
197
+ </form>
198
+
199
+ <div id="error-box" class="error"></div>
200
+
201
+ <div id="preview-section" style="display:none;">
202
+ <h2>Preview</h2>
203
+ <div class="preview-header">
204
+ <h3>HTML Output</h3>
205
+ <button type="button" id="download-html-btn" class="download-btn">Download HTML</button>
206
+ </div>
207
+ <div id="html-preview-container" class="preview-container"></div>
208
+ <div class="preview-header" style="margin-top: 30px;">
209
+ <h3>PNG Output</h3>
210
+ <button type="button" id="download-png-btn" class="download-btn">Download PNG</button>
211
+ </div>
212
+ <div id="png-preview-container" class="preview-container"></div>
213
+ </div>
214
+ <script>
215
+ // --- All JavaScript is unchanged from the previous correct version ---
216
+ // It correctly gathers style info without modifying the parent page.
217
+ const loadBtn = document.getElementById('load-btn'), generateBtn = document.getElementById('generate-btn'),
218
+ downloadHtmlBtn = document.getElementById('download-html-btn'), downloadPngBtn = document.getElementById('download-png-btn'),
219
+ markdownTextInput = document.getElementById('markdown-text-input'), markdownFileInput = document.getElementById('markdown-file-input'),
220
+ componentsFieldset = document.getElementById('components-fieldset'), componentsContainer = document.getElementById('components-container'),
221
+ previewSection = document.getElementById('preview-section'), htmlPreviewContainer = document.getElementById('html-preview-container'),
222
+ pngPreviewContainer = document.getElementById('png-preview-container'), errorBox = document.getElementById('error-box'),
223
+ infoBox = document.getElementById('info-box');
224
+ function toggleAllComponents(checked) { componentsContainer.querySelectorAll('.component-checkbox').forEach(cb => cb.checked = checked); }
225
+ function displayError(message) { errorBox.textContent = message; errorBox.style.display = 'block'; previewSection.style.display = 'none'; }
226
+ function buildPayload() {
227
+ let finalMarkdown = "";
228
+ if (componentsFieldset.style.display === 'block') {
229
+ const parts = [];
230
+ componentsContainer.querySelectorAll('.component-container').forEach(div => {
231
+ if (div.querySelector('.component-checkbox').checked) { parts.push(div.dataset.reconstructed || div.dataset.content); }
232
+ });
233
+ finalMarkdown = parts.join('\\n\\n---\\n\\n');
234
+ } else { finalMarkdown = markdownTextInput.value; }
235
+ return {
236
+ markdown_text: finalMarkdown,
237
+ styles: {
238
+ font_family: document.getElementById('font_family').value, font_size: document.getElementById('font_size').value,
239
+ text_color: document.getElementById('text_color').value, background_color: document.getElementById('background_color').value,
240
+ code_padding: document.getElementById('code_padding').value, highlight_theme: document.getElementById('highlight_theme').value,
241
+ custom_css: document.getElementById('custom_css').value
242
+ },
243
+ include_fontawesome: document.getElementById('include_fontawesome').checked,
244
+ };
245
+ }
246
+ loadBtn.addEventListener('click', async () => { /* Logic unchanged */ });
247
+ generateBtn.addEventListener('click', async () => {
248
+ generateBtn.textContent = 'Generating...'; generateBtn.disabled = true; errorBox.style.display = 'none';
249
+ const payload = buildPayload();
250
+ payload.download = false;
251
+ try {
252
+ const response = await fetch('/convert', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
253
+ const result = await response.json();
254
+ if (!response.ok) throw new Error(result.error || `Server error ${response.status}`);
255
+ previewSection.style.display = 'block';
256
+ htmlPreviewContainer.innerHTML = result.preview_html;
257
+ pngPreviewContainer.innerHTML = `<img src="data:image/png;base64,${result.preview_png_base64}" alt="PNG Preview">`;
258
+ downloadHtmlBtn.style.display = 'inline-block'; downloadPngBtn.style.display = 'inline-block';
259
+ } catch (err) { displayError('Error generating preview: ' + err.message); }
260
+ finally { generateBtn.textContent = 'Generate Preview'; generateBtn.disabled = false; }
261
+ });
262
+ async function handleDownload(fileType) {
263
+ const button = fileType === 'html' ? downloadHtmlBtn : downloadPngBtn;
264
+ button.textContent = 'Preparing...'; const payload = buildPayload();
265
+ payload.download = true; payload.download_type = fileType;
266
+ try {
267
+ const response = await fetch('/convert', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
268
+ if (!response.ok) throw new Error(`Download failed: ${response.statusText}`);
269
+ const blob = await response.blob(); const url = window.URL.createObjectURL(blob);
270
+ const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = 'output.' + fileType;
271
+ document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove();
272
+ } catch (err) { displayError('Error preparing download: ' + err.message); }
273
+ finally { button.textContent = `Download ${fileType.toUpperCase()}`; }
274
+ }
275
+ downloadHtmlBtn.addEventListener('click', () => handleDownload('html'));
276
+ downloadPngBtn.addEventListener('click', () => handleDownload('png'));
277
+ loadBtn.addEventListener('click', async () => {
278
+ loadBtn.textContent = 'Loading...'; loadBtn.disabled = true; errorBox.style.display = 'none'; infoBox.style.display = 'none'; componentsFieldset.style.display = 'none'; componentsContainer.innerHTML = '';
279
+ const formData = new FormData();
280
+ if (markdownFileInput.files.length > 0) { formData.append('markdown_file', markdownFileInput.files[0]); } else { formData.append('markdown_text', markdownTextInput.value); }
281
+ try {
282
+ const response = await fetch('/parse', { method: 'POST', body: formData });
283
+ const result = await response.json();
284
+ if (!response.ok) throw new Error(result.error || `Server error`);
285
+ infoBox.innerHTML = `Detected Format: <strong>${result.format}</strong>`; infoBox.style.display = 'block';
286
+ if (result.format !== 'Unknown') {
287
+ componentsFieldset.style.display = 'block';
288
+ result.components.forEach((comp, index) => {
289
+ const div = document.createElement('div'); div.className = 'component-container'; div.dataset.type = comp.type; div.dataset.filename = comp.filename; div.dataset.content = comp.content;
290
+ let reconstructedContent = comp.content;
291
+ if (comp.is_code_block) { div.dataset.isCodeBlock = 'true'; div.dataset.language = comp.language || ''; reconstructedContent = "```" + (comp.language || '') + "\\n" + comp.content + "\\n```"; }
292
+ if (comp.type === 'section') div.dataset.reconstructed = `## ${comp.filename}\\n${comp.content}`; if (comp.type === 'version') div.dataset.reconstructed = `## ${comp.filename}\\n${comp.content}`;
293
+ div.innerHTML = `<div class="component-header"><input type="checkbox" id="comp-check-${index}" class="component-checkbox" checked><label for="comp-check-${index}">${comp.filename}</label></div><div class="component-content"><textarea readonly>${comp.content}</textarea></div>`;
294
+ componentsContainer.appendChild(div);
295
+ });
296
+ }
297
+ if(markdownFileInput.files.length > 0) { markdownTextInput.value = await markdownFileInput.files[0].text(); }
298
+ } catch (err) { displayError('Error parsing content: ' + err.message); } finally { loadBtn.textContent = 'Load & Analyze'; loadBtn.disabled = false; }
299
+ });
300
+ </script>
301
+ </body>
302
+ </html>
303
+ """, highlight_styles=highlight_styles)
304
+
305
+ if __name__ == "__main__":
306
+ # Ensure you have installed the required libraries:
307
+ # pip install Flask markdown imgkit pygments
308
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))