broadfield-dev commited on
Commit
0a7e835
Β·
verified Β·
1 Parent(s): 78ffeff

Initial Space setup of broadfield-dev/md2png via Builder

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -35
  2. Dockerfile +17 -0
  3. README.md +4 -4
  4. app.py +308 -0
  5. new_app.py (A new application file) +17 -0
  6. requirements.txt +4 -0
  7. schema.md +57 -0
.gitattributes CHANGED
@@ -1,35 +1 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ [Binary file - 1519 bytes]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ # Install wkhtmltopdf and dependencies
4
+ RUN apt-get update && apt-get install -y \
5
+ wkhtmltopdf \
6
+ && rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+ COPY requirements.txt .
10
+ RUN pip install --no-cache-dir -r requirements.txt
11
+ COPY . .
12
+
13
+ # Ensure the temp directory is writable
14
+ RUN mkdir -p /app/temp && chmod -R 777 /app/temp
15
+
16
+ ENV PORT=7860
17
+ CMD ["python", "app.py"]
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- title: Md2png
3
- emoji: πŸ“š
4
- colorFrom: indigo
5
- colorTo: yellow
6
  sdk: docker
7
  pinned: false
8
  ---
 
1
  ---
2
+ title: Markdown2PNG
3
+ emoji: πŸ‘€
4
+ colorFrom: red
5
+ colorTo: red
6
  sdk: docker
7
  pinned: false
8
  ---
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)))
new_app.py (A new application file) ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ \`\`\`python
2
+ # The new code for the application
3
+ print("This is the new app.")
4
+ \`\`\`
5
+
6
+ ## File Structure
7
+ \`\`\`
8
+ πŸ“ Root
9
+ πŸ“„ new_app.py
10
+ \`\`\`
11
+ \`\`\`
12
+
13
+ ---
14
+
15
+ ## 5. Unknown Format
16
+
17
+ If your document does not match any of the schemas above, it will be classified as **"Unknown"**. The entire document will be treated as a single component and will be rendered as-is.
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ flask==3.0.3
2
+ markdown==3.7
3
+ imgkit==1.2.3
4
+ pygments
schema.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Supported Format Schemas
2
+
3
+ This document outlines the specific structures the Intelligent Markdown Converter looks for to detect and parse different types of documents into selectable components.
4
+
5
+ ---
6
+
7
+ ## 1. Repo2Markdown Format
8
+
9
+ **Purpose:** To represent a project's directory structure and the full contents of its files in a single document.
10
+
11
+ **Schema Rules:**
12
+ 1. The document **must** contain a second-level heading exactly named \`## File Structure\`.
13
+ 2. The document **must** contain at least one file block, denoted by a third-level heading starting with \`### File:\`.
14
+ 3. For proper syntax highlighting, code files should have their content wrapped in fenced code blocks (e.g., \`\`\`python ... \`\`\`).
15
+
16
+ ---
17
+
18
+ ## 2. Standard README Format
19
+
20
+ **Purpose:** To parse a typical software project \`README.md\` file into its major sections.
21
+
22
+ **Schema Rules:**
23
+ 1. The document **must** start with a top-level heading (\`#\`).
24
+ 2. The document **must** contain at least one second-level heading (\`##\`). Each \`##\` heading and its content becomes a "Section" component.
25
+
26
+ ---
27
+
28
+ ## 3. Changelog Format
29
+
30
+ **Purpose:** To parse a standard "Keep a Changelog" formatted file into components for each version.
31
+
32
+ **Schema Rules:**
33
+ 1. The document **must** contain at least one version heading that follows the pattern: \`## [VersionNumber] - YYYY-MM-DD\`.
34
+ 2. Each version heading and its content becomes a "Version" component.
35
+
36
+ ---
37
+
38
+ ## 4. Agent Action Format
39
+
40
+ **Purpose:** To describe a series of programmatic actions and file manipulations for an agent to take on a Hugging Face Space.
41
+
42
+ **Schema Rules:**
43
+ 1. The document is detected by the presence of a \`### HF_ACTION:\` command or the specific header text "File and Code Formatting:".
44
+ 2. **File definitions** use the format \`### File: path/to/filename.ext\`, followed by a fenced code block or a binary file marker. These become "File" components.
45
+ 3. **File structure definitions** use the heading \`## File Structure\`, followed by a fenced code block. This becomes a "Structure" component.
46
+ 4. **Agent commands** are specified on a single line starting with \`### HF_ACTION: COMMAND arguments...\`. Each command becomes an "Action" component.
47
+ 5. All other text is grouped into an "Instructions & Rules" component.
48
+
49
+ **Example:**
50
+ \`\`\`markdown
51
+ **File and Code Formatting:**
52
+ When you provide NEW code...
53
+ ...
54
+ **Hugging Face Space Actions:**
55
+ ...
56
+
57
+ ### HF_ACTION: DELETE_FILE old_app.py