broadfield-dev commited on
Commit
5ecbc8d
·
verified ·
1 Parent(s): a761a2e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +132 -153
app.py CHANGED
@@ -6,7 +6,6 @@ import traceback
6
  from io import BytesIO
7
  import re
8
 
9
- # New imports for syntax highlighting
10
  from pygments import highlight
11
  from pygments.lexers import get_lexer_by_name
12
  from pygments.formatters import HtmlFormatter
@@ -14,18 +13,13 @@ from pygments.styles import get_all_styles
14
 
15
  app = Flask(__name__)
16
 
17
- # Configure a temporary directory for file operations
18
  TEMP_DIR = os.path.join(os.getcwd(), "temp")
19
  os.makedirs(TEMP_DIR, exist_ok=True)
20
 
21
- # --- UTILITY FUNCTIONS (Back-end) ---
22
-
23
- def is_repo2markdown_format(text):
24
- """Detects if the text is in the Repo2Markdown format."""
25
- return "## File Structure" in text and text.count("### File:") > 0
26
 
27
  def parse_repo2markdown(text):
28
- """Parses Repo2Markdown text, extracts files, and prepares them for the UI."""
29
  components = []
30
  pattern = re.compile(r'### File: (.*?)\n([\s\S]*?)(?=\n### File:|\Z)', re.MULTILINE)
31
 
@@ -41,35 +35,86 @@ def parse_repo2markdown(text):
41
  code_match = re.search(r'^```(\w*)\s*\n([\s\S]*?)\s*```$', raw_content, re.DOTALL)
42
 
43
  if code_match:
44
- language = code_match.group(1)
45
- inner_content = code_match.group(2).strip()
46
- components.append({'type': 'file', 'filename': filename, 'content': inner_content, 'is_code_block': True, 'language': language})
47
  else:
48
  components.append({'type': 'file', 'filename': filename, 'content': raw_content, 'is_code_block': False, 'language': ''})
49
-
50
  return components
51
 
52
- # --- API ENDPOINTS (Back-end) ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  @app.route('/parse', methods=['POST'])
55
  def parse_endpoint():
56
- """Receives markdown text and returns parsed components as JSON."""
 
57
  if 'markdown_file' in request.files and request.files['markdown_file'].filename != '':
58
- file = request.files['markdown_file']
59
- text = file.read().decode('utf-8')
 
 
60
  else:
61
  text = request.form.get('markdown_text', '')
62
 
63
  if not text:
64
  return jsonify({'error': 'No text or file provided.'}), 400
65
 
66
- if is_repo2markdown_format(text):
67
- try:
68
- return jsonify(parse_repo2markdown(text))
69
- except Exception as e:
70
- return jsonify({'error': f'Failed to parse Repo2Markdown: {str(e)}'}), 500
71
- else:
72
- return jsonify([{'type': 'text', 'filename': 'Full Text', 'content': text}])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  @app.route('/convert', methods=['POST'])
75
  def convert_endpoint():
@@ -77,27 +122,25 @@ def convert_endpoint():
77
  data = request.json
78
  markdown_text = data.get('markdown_text', '')
79
  styles = data.get('styles', {})
 
80
  include_fontawesome = data.get('include_fontawesome', False)
81
  download_type = data.get('download_type', 'png')
82
  is_download_request = data.get('download', False)
83
 
84
  try:
85
- # --- CSS & Font Generation (Scoped) ---
86
  wrapper_id = "#output-wrapper"
87
  font_family = styles.get('font_family', "'Arial', sans-serif")
88
  google_font_name = font_family.split(',')[0].strip("'\"")
89
  google_font_link = ""
90
- if " " in google_font_name and google_font_name not in ["Times New Roman", "Courier New"]: # Simple check for Google Font
91
  google_font_link = f'<link href="https://fonts.googleapis.com/css2?family={google_font_name.replace(" ", "+")}:wght@400;700&display=swap" rel="stylesheet">'
92
 
93
  highlight_theme = styles.get('highlight_theme', 'default')
94
  pygments_css = ""
95
  if highlight_theme != 'none':
96
  formatter = HtmlFormatter(style=highlight_theme, cssclass="codehilite")
97
- # Get the CSS definitions for the chosen theme.
98
- pygments_css = formatter.get_style_defs()
99
 
100
- # All styles are now prefixed with the wrapper_id for isolation.
101
  scoped_css = f"""
102
  {wrapper_id} {{
103
  font-family: {font_family};
@@ -105,44 +148,26 @@ def convert_endpoint():
105
  color: {styles.get('text_color', '#333')};
106
  background-color: {styles.get('background_color', '#fff')};
107
  }}
108
- {wrapper_id} h3 {{ border-bottom: 1px solid #ccc; padding-bottom: 5px; margin-top: 2em; }}
109
  {wrapper_id} table {{ border-collapse: collapse; width: 100%; }}
110
  {wrapper_id} th, {wrapper_id} td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
111
  {wrapper_id} th {{ background-color: #f2f2f2; }}
112
  {wrapper_id} img {{ max-width: 100%; height: auto; }}
113
  {wrapper_id} pre {{ padding: {styles.get('code_padding', '15')}px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
114
- {wrapper_id} code {{ font-family: 'Courier New', monospace; padding: 0.2em 0.4em; margin: 0; font-size: 85%; }}
115
- {wrapper_id} pre code {{ padding: 0; margin: 0; font-size: inherit; background: transparent; border-radius: 0; }}
116
  {pygments_css}
117
  {styles.get('custom_css', '')}
118
  """
119
 
120
- # --- HTML Conversion ---
121
- # The 'codehilite' extension enables the CSS classes that Pygments uses.
122
  md_extensions = ['fenced_code', 'tables', 'codehilite']
123
  html_content = markdown.markdown(markdown_text, extensions=md_extensions, extension_configs={'codehilite': {'css_class': 'codehilite'}})
124
-
125
- # Wrap final HTML content in the isolated div
126
  final_html_body = f'<div id="output-wrapper">{html_content}</div>'
127
-
128
- 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 ""
129
 
130
  full_html = f"""<!DOCTYPE html>
131
- <html>
132
- <head>
133
- <meta charset="UTF-8">
134
- {google_font_link}
135
- {fontawesome_link}
136
- <style>
137
- /* For PNG generation, give the body the background color */
138
- body {{ background-color: {styles.get('background_color', '#fff')}; padding: 25px; display: inline-block;}}
139
- {scoped_css}
140
- </style>
141
- </head>
142
- <body>
143
- {final_html_body}
144
- </body>
145
- </html>"""
146
 
147
  if is_download_request:
148
  if download_type == 'html':
@@ -158,23 +183,21 @@ def convert_endpoint():
158
  traceback.print_exc()
159
  return jsonify({'error': f'Failed to convert content: {str(e)}'}), 500
160
 
161
-
162
- # --- MAIN PAGE (Front-end) ---
163
-
164
  @app.route('/')
165
  def index():
166
  """Serves the main HTML page with all the client-side JavaScript."""
167
  highlight_styles = sorted(list(get_all_styles()))
168
  return render_template_string("""
169
  <!DOCTYPE html>
 
170
  <html lang="en">
171
  <head>
172
  <meta charset="UTF-8">
173
- <title>Advanced Markdown Converter & Composer</title>
174
  <style>
175
  body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #f9f9f9; }
176
- h1, h2, h3 { color: #333; }
177
- h1 { text-align: center; }
178
  form { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
179
  textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; padding: 10px; font-family: monospace; }
180
  fieldset { border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin-top: 20px; }
@@ -182,33 +205,27 @@ def index():
182
  select, input[type="number"], input[type="color"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;}
183
  button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; }
184
  .action-btn { background-color: #007BFF; color: white; font-size: 16px; padding: 12px 20px;}
185
- .action-btn:hover { background-color: #0056b3; }
186
  .generate-btn { background-color: #5a32a3; color: white; font-size: 16px; padding: 12px 20px; }
187
- .generate-btn:hover { background-color: #4a298a; }
188
  .download-btn { background-color: #28a745; color: white; display: none; }
189
- .download-btn:hover { background-color: #218838; }
190
  .controls { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 20px; margin-top: 20px; }
191
  .main-actions { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
192
  .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; }
193
  .error { color: #D8000C; background-color: #FFD2D2; padding: 10px; border-radius: 5px; margin-top: 15px; display: none; }
194
- .info { color: #00529B; background-color: #BDE5F8; padding: 10px; border-radius: 5px; margin: 10px 0; }
195
  .style-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 15px; align-items: end; }
196
  .component-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; }
197
  .component-container { border: 1px solid #e0e0e0; border-radius: 5px; background: #fafafa; }
198
  .component-header { background: #f1f1f1; padding: 8px 12px; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; gap: 10px; }
199
- .component-header input[type="checkbox"] { width: 18px; height: 18px; }
200
- .component-header label { margin-bottom: 0; font-weight: bold; }
201
- .component-content { padding: 10px; }
202
  .component-content textarea { height: 150px; }
203
  .selection-controls { margin: 15px 0; display: flex; gap: 10px; }
204
  </style>
205
  </head>
206
  <body>
207
- <h1>Advanced Markdown Converter & Composer</h1>
208
  <form id="main-form" onsubmit="return false;">
209
  <fieldset>
210
  <legend>1. Load Content</legend>
211
- <div class="info">Paste content or upload a file, then click "Load & Analyze".</div>
212
  <textarea id="markdown-text-input" name="markdown_text" rows="8"></textarea>
213
  <div style="margin-top: 10px; display: flex; align-items: center; gap: 10px;">
214
  <label for="markdown-file-input">Or upload a file:</label>
@@ -230,55 +247,14 @@ def index():
230
 
231
  <fieldset>
232
  <legend>3. Configure Styles</legend>
 
233
  <div class="style-grid">
234
- <div>
235
- <label>Font Family:</label>
236
- <select id="font_family">
237
- <optgroup label="Sans-Serif">
238
- <option value="'Arial', sans-serif">Arial</option>
239
- <option value="'Helvetica', sans-serif">Helvetica</option>
240
- <option value="'Verdana', sans-serif">Verdana</option>
241
- <option value="'Roboto', sans-serif">Roboto</option>
242
- <option value="'Open Sans', sans-serif">Open Sans</option>
243
- <option value="'Lato', sans-serif">Lato</option>
244
- <option value="'Montserrat', sans-serif">Montserrat</option>
245
- </optgroup>
246
- <optgroup label="Serif">
247
- <option value="'Times New Roman', serif">Times New Roman</option>
248
- <option value="'Georgia', serif">Georgia</option>
249
- <option value="'Garamond', serif">Garamond</option>
250
- <option value="'Playfair Display', serif">Playfair Display</option>
251
- <option value="'Merriweather', serif">Merriweather</option>
252
- </optgroup>
253
- <optgroup label="Monospace">
254
- <option value="'Courier New', monospace">Courier New</option>
255
- <option value="'Lucida Console', monospace">Lucida Console</option>
256
- <option value="'Roboto Mono', monospace">Roboto Mono</option>
257
- <option value="'Source Code Pro', monospace">Source Code Pro</option>
258
- <option value="'Inconsolata', monospace">Inconsolata</option>
259
- </optgroup>
260
- <optgroup label="Display">
261
- <option value="'Oswald', sans-serif">Oswald</option>
262
- <option value="'Raleway', sans-serif">Raleway</option>
263
- <option value="'Lobster', cursive">Lobster</option>
264
- </optgroup>
265
- <optgroup label="Handwriting">
266
- <option value="'Dancing Script', cursive">Dancing Script</option>
267
- <option value="'Pacifico', cursive">Pacifico</option>
268
- <option value="'Caveat', cursive">Caveat</option>
269
- </optgroup>
270
- </select>
271
- </div>
272
  <div><label>Font Size (px):</label><input type="number" id="font_size" value="16"></div>
273
- <div>
274
- <label>Highlight Theme:</label>
275
- <select id="highlight_theme">
276
- <option value="none">None</option>
277
- {% for style in highlight_styles %}
278
- <option value="{{ style }}" {% if style == 'default' %}selected{% endif %}>{{ style }}</option>
279
- {% endfor %}
280
- </select>
281
- </div>
282
  <div><label>Text Color:</label><input type="color" id="text_color" value="#333333"></div>
283
  <div><label>Background Color:</label><input type="color" id="background_color" value="#ffffff"></div>
284
  <div><label>Code Padding (px):</label><input type="number" id="code_padding" value="15"></div>
@@ -302,6 +278,9 @@ def index():
302
  <div id="preview-container" class="preview-container"></div>
303
 
304
  <script>
 
 
 
305
  const loadBtn = document.getElementById('load-btn');
306
  const generateBtn = document.getElementById('generate-btn');
307
  const downloadBtn = document.getElementById('download-btn');
@@ -312,23 +291,21 @@ def index():
312
  const previewContainer = document.getElementById('preview-container');
313
  const errorBox = document.getElementById('error-box');
314
 
315
- function toggleAllComponents(checked) {
316
- componentsContainer.querySelectorAll('.component-checkbox').forEach(cb => cb.checked = checked);
317
- }
318
 
319
  function displayError(message) {
320
  errorBox.textContent = message;
321
  errorBox.style.display = 'block';
322
- previewContainer.innerHTML = '';
323
  }
324
 
 
325
  loadBtn.addEventListener('click', async () => {
326
  loadBtn.textContent = 'Loading...';
 
327
  errorBox.style.display = 'none';
 
328
  componentsFieldset.style.display = 'none';
329
  componentsContainer.innerHTML = '';
330
 
331
-
332
  const formData = new FormData();
333
  if (markdownFileInput.files.length > 0) {
334
  formData.append('markdown_file', markdownFileInput.files[0]);
@@ -338,26 +315,36 @@ def index():
338
 
339
  try {
340
  const response = await fetch('/parse', { method: 'POST', body: formData });
341
- const components = await response.json();
342
 
343
- if (components.error) throw new Error(components.error);
344
 
345
- if (components.length > 1 || (components.length > 0 && components[0]?.type !== 'text')) {
 
 
 
346
  componentsFieldset.style.display = 'block';
347
- components.forEach((comp, index) => {
348
  const div = document.createElement('div');
349
  div.className = 'component-container';
350
- div.dataset.filename = comp.filename;
351
  div.dataset.type = comp.type;
352
- div.dataset.isCodeBlock = comp.is_code_block;
353
- div.dataset.language = comp.language;
354
 
355
- const contentHolder = document.createElement('div');
356
- contentHolder.style.display = 'none';
357
- contentHolder.textContent = comp.content;
358
- div.appendChild(contentHolder);
 
 
 
 
 
 
 
 
 
359
 
360
- div.innerHTML += `
361
  <div class="component-header">
362
  <input type="checkbox" id="comp-check-${index}" class="component-checkbox" checked>
363
  <label for="comp-check-${index}">${comp.filename}</label>
@@ -373,32 +360,24 @@ def index():
373
  displayError('Error parsing content: ' + err.message);
374
  } finally {
375
  loadBtn.textContent = 'Load & Analyze';
 
376
  }
377
  });
378
-
379
  async function handleGeneration(isDownload = false) {
380
- const buttonToUpdate = isDownload ? downloadBtn : generateBtn;
381
  buttonToUpdate.textContent = 'Generating...';
382
  buttonToUpdate.disabled = true;
383
  errorBox.style.display = 'none';
384
 
385
  let finalMarkdown = "";
 
386
  if (componentsFieldset.style.display === 'block') {
387
  const parts = [];
388
  const componentDivs = componentsContainer.querySelectorAll('.component-container');
389
  componentDivs.forEach(div => {
390
  if (div.querySelector('.component-checkbox').checked) {
391
- const content = div.querySelector('div').textContent;
392
- let partContent = content;
393
- if (div.dataset.isCodeBlock === 'true') {
394
- partContent = "```" + div.dataset.language + "\\n" + content + "\\n```";
395
- }
396
-
397
- if (div.dataset.type === 'intro') {
398
- parts.push(partContent);
399
- } else {
400
- parts.push(`### File: ${div.dataset.filename}\\n${partContent}`);
401
- }
402
  }
403
  });
404
  finalMarkdown = parts.join('\\n\\n---\\n\\n');
@@ -433,17 +412,12 @@ def index():
433
  if (!response.ok) throw new Error(`Download failed: ${response.statusText}`);
434
  const blob = await response.blob();
435
  const url = window.URL.createObjectURL(blob);
436
- const a = document.createElement('a');
437
- a.style.display = 'none';
438
- a.href = url;
439
  a.download = 'output.' + payload.download_type;
440
- document.body.appendChild(a);
441
- a.click();
442
- window.URL.revokeObjectURL(url);
443
- a.remove();
444
  } else {
445
  const result = await response.json();
446
- if (result.error) throw new Error(result.error);
447
  previewContainer.innerHTML = result.preview_html;
448
  downloadBtn.style.display = 'inline-block';
449
  }
@@ -455,13 +429,18 @@ def index():
455
  buttonToUpdate.disabled = false;
456
  }
457
  }
458
-
 
 
459
  generateBtn.addEventListener('click', () => handleGeneration(false));
460
  downloadBtn.addEventListener('click', () => handleGeneration(true));
 
461
  </script>
462
  </body>
463
  </html>
464
  """, highlight_styles=highlight_styles)
465
 
466
  if __name__ == "__main__":
 
 
467
  app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
 
6
  from io import BytesIO
7
  import re
8
 
 
9
  from pygments import highlight
10
  from pygments.lexers import get_lexer_by_name
11
  from pygments.formatters import HtmlFormatter
 
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
+ # --- NEW: FORMAT PARSING FUNCTIONS ---
 
 
 
 
20
 
21
  def parse_repo2markdown(text):
22
+ """Parses the 'Repo2Markdown' format into file components."""
23
  components = []
24
  pattern = re.compile(r'### File: (.*?)\n([\s\S]*?)(?=\n### File:|\Z)', re.MULTILINE)
25
 
 
35
  code_match = re.search(r'^```(\w*)\s*\n([\s\S]*?)\s*```$', raw_content, re.DOTALL)
36
 
37
  if code_match:
38
+ components.append({'type': 'file', 'filename': filename, 'content': code_match.group(2).strip(), 'is_code_block': True, 'language': code_match.group(1)})
 
 
39
  else:
40
  components.append({'type': 'file', 'filename': filename, 'content': raw_content, 'is_code_block': False, 'language': ''})
 
41
  return components
42
 
43
+ def parse_standard_readme(text):
44
+ """Parses a standard README with a main title and '##' sections."""
45
+ components = []
46
+ # Split by '## ' but keep the delimiter. The pattern looks for '## ' at the beginning of a line.
47
+ parts = re.split(r'^(## .*?)$', text, flags=re.MULTILINE)
48
+
49
+ # The first part is the introduction (everything before the first '##')
50
+ intro_content = parts[0].strip()
51
+ if intro_content:
52
+ components.append({'type': 'intro', 'filename': 'Introduction', 'content': intro_content})
53
+
54
+ # Process the remaining parts, which come in pairs of (heading, content)
55
+ for i in range(1, len(parts), 2):
56
+ heading = parts[i].replace('##', '').strip()
57
+ content = parts[i+1].strip()
58
+ components.append({'type': 'section', 'filename': heading, 'content': content})
59
+ return components
60
+
61
+ def parse_changelog(text):
62
+ """Parses a changelog file with version headings."""
63
+ components = []
64
+ # Split by version headers like '## [1.0.0] - 2023-01-01'
65
+ parts = re.split(r'^(## \[\d+\.\d+\.\d+.*?\].*?)$', text, flags=re.MULTILINE)
66
+
67
+ intro_content = parts[0].strip()
68
+ if intro_content:
69
+ components.append({'type': 'intro', 'filename': 'Changelog Header', 'content': intro_content})
70
+
71
+ for i in range(1, len(parts), 2):
72
+ heading = parts[i].replace('##', '').strip()
73
+ content = parts[i+1].strip()
74
+ components.append({'type': 'version', 'filename': heading, 'content': content})
75
+ return components
76
+
77
+ # --- DETECTION AND PARSING LOGIC ---
78
 
79
  @app.route('/parse', methods=['POST'])
80
  def parse_endpoint():
81
+ """Detects the format of the input text and parses it into components."""
82
+ text = ""
83
  if 'markdown_file' in request.files and request.files['markdown_file'].filename != '':
84
+ try:
85
+ text = request.files['markdown_file'].read().decode('utf-8')
86
+ except Exception as e:
87
+ return jsonify({'error': f"Error reading file: {str(e)}"}), 400
88
  else:
89
  text = request.form.get('markdown_text', '')
90
 
91
  if not text:
92
  return jsonify({'error': 'No text or file provided.'}), 400
93
 
94
+ # Format Detection Logic
95
+ format_name = "Unknown"
96
+ components = []
97
+ try:
98
+ if "## File Structure" in text and text.count("### File:") > 0:
99
+ format_name = "Repo2Markdown"
100
+ components = parse_repo2markdown(text)
101
+ elif re.search(r'^## \[\d+\.\d+\.\d+.*?\].*?$', text, flags=re.MULTILINE):
102
+ format_name = "Changelog"
103
+ components = parse_changelog(text)
104
+ elif text.strip().startswith("#") and re.search(r'^## ', text, flags=re.MULTILINE):
105
+ format_name = "Standard README"
106
+ components = parse_standard_readme(text)
107
+
108
+ if not components: # If parsing failed or format is unknown
109
+ format_name = "Unknown"
110
+ components = [{'type': 'text', 'filename': 'Full Text', 'content': text}]
111
+
112
+ return jsonify({'format': format_name, 'components': components})
113
+
114
+ except Exception as e:
115
+ traceback.print_exc()
116
+ return jsonify({'error': f'Failed to parse content: {str(e)}'}), 500
117
+
118
 
119
  @app.route('/convert', methods=['POST'])
120
  def convert_endpoint():
 
122
  data = request.json
123
  markdown_text = data.get('markdown_text', '')
124
  styles = data.get('styles', {})
125
+ # ... (rest of the conversion logic is unchanged)
126
  include_fontawesome = data.get('include_fontawesome', False)
127
  download_type = data.get('download_type', 'png')
128
  is_download_request = data.get('download', False)
129
 
130
  try:
 
131
  wrapper_id = "#output-wrapper"
132
  font_family = styles.get('font_family', "'Arial', sans-serif")
133
  google_font_name = font_family.split(',')[0].strip("'\"")
134
  google_font_link = ""
135
+ if " " in google_font_name and google_font_name not in ["Times New Roman", "Courier New"]:
136
  google_font_link = f'<link href="https://fonts.googleapis.com/css2?family={google_font_name.replace(" ", "+")}:wght@400;700&display=swap" rel="stylesheet">'
137
 
138
  highlight_theme = styles.get('highlight_theme', 'default')
139
  pygments_css = ""
140
  if highlight_theme != 'none':
141
  formatter = HtmlFormatter(style=highlight_theme, cssclass="codehilite")
142
+ pygments_css = formatter.get_style_defs(f' {wrapper_id}') # Scope pygments CSS
 
143
 
 
144
  scoped_css = f"""
145
  {wrapper_id} {{
146
  font-family: {font_family};
 
148
  color: {styles.get('text_color', '#333')};
149
  background-color: {styles.get('background_color', '#fff')};
150
  }}
151
+ {wrapper_id} h1, {wrapper_id} h2, {wrapper_id} h3 {{ border-bottom: 1px solid #eee; padding-bottom: 5px; margin-top: 1.5em; }}
152
  {wrapper_id} table {{ border-collapse: collapse; width: 100%; }}
153
  {wrapper_id} th, {wrapper_id} td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }}
154
  {wrapper_id} th {{ background-color: #f2f2f2; }}
155
  {wrapper_id} img {{ max-width: 100%; height: auto; }}
156
  {wrapper_id} pre {{ padding: {styles.get('code_padding', '15')}px; border-radius: 5px; white-space: pre-wrap; word-wrap: break-word; }}
157
+ {wrapper_id} :not(pre) > code {{ font-family: 'Courier New', monospace; background-color: #eef; padding: .2em .4em; border-radius: 3px; }}
 
158
  {pygments_css}
159
  {styles.get('custom_css', '')}
160
  """
161
 
 
 
162
  md_extensions = ['fenced_code', 'tables', 'codehilite']
163
  html_content = markdown.markdown(markdown_text, extensions=md_extensions, extension_configs={'codehilite': {'css_class': 'codehilite'}})
 
 
164
  final_html_body = f'<div id="output-wrapper">{html_content}</div>'
 
 
165
 
166
  full_html = f"""<!DOCTYPE html>
167
+ <html><head><meta charset="UTF-8">{google_font_link}{fontawesome_link}<style>
168
+ body {{ background-color: {styles.get('background_color', '#fff')}; padding: 25px; display: inline-block;}}
169
+ {scoped_css}
170
+ </style></head><body>{final_html_body}</body></html>"""
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  if is_download_request:
173
  if download_type == 'html':
 
183
  traceback.print_exc()
184
  return jsonify({'error': f'Failed to convert content: {str(e)}'}), 500
185
 
 
 
 
186
  @app.route('/')
187
  def index():
188
  """Serves the main HTML page with all the client-side JavaScript."""
189
  highlight_styles = sorted(list(get_all_styles()))
190
  return render_template_string("""
191
  <!DOCTYPE html>
192
+ <!-- ... (HTML and JavaScript are largely unchanged but will now react to the new 'format' key from the API) ... -->
193
  <html lang="en">
194
  <head>
195
  <meta charset="UTF-8">
196
+ <title>Intelligent Markdown Converter</title>
197
  <style>
198
  body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; max-width: 1200px; margin: 0 auto; padding: 20px; background-color: #f9f9f9; }
199
+ h1 { text-align: center; color: #333; }
200
+ /* ... Other styles remain the same ... */
201
  form { background: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); margin-bottom: 20px; }
202
  textarea { width: 100%; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; padding: 10px; font-family: monospace; }
203
  fieldset { border: 1px solid #ddd; padding: 15px; border-radius: 5px; margin-top: 20px; }
 
205
  select, input[type="number"], input[type="color"] { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;}
206
  button { padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; font-size: 14px; transition: background-color 0.2s; }
207
  .action-btn { background-color: #007BFF; color: white; font-size: 16px; padding: 12px 20px;}
 
208
  .generate-btn { background-color: #5a32a3; color: white; font-size: 16px; padding: 12px 20px; }
 
209
  .download-btn { background-color: #28a745; color: white; display: none; }
 
210
  .controls { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 20px; margin-top: 20px; }
211
  .main-actions { display: flex; flex-wrap: wrap; gap: 15px; align-items: center; }
212
  .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; }
213
  .error { color: #D8000C; background-color: #FFD2D2; padding: 10px; border-radius: 5px; margin-top: 15px; display: none; }
214
+ .info { color: #00529B; background-color: #BDE5F8; padding: 10px; border-radius: 5px; margin: 10px 0; display: none;} /* Hidden by default */
215
  .style-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 15px; align-items: end; }
216
  .component-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 15px; }
217
  .component-container { border: 1px solid #e0e0e0; border-radius: 5px; background: #fafafa; }
218
  .component-header { background: #f1f1f1; padding: 8px 12px; border-bottom: 1px solid #e0e0e0; display: flex; align-items: center; gap: 10px; }
 
 
 
219
  .component-content textarea { height: 150px; }
220
  .selection-controls { margin: 15px 0; display: flex; gap: 10px; }
221
  </style>
222
  </head>
223
  <body>
224
+ <h1>Intelligent Markdown Converter</h1>
225
  <form id="main-form" onsubmit="return false;">
226
  <fieldset>
227
  <legend>1. Load Content</legend>
228
+ <div id="info-box" class="info"></div>
229
  <textarea id="markdown-text-input" name="markdown_text" rows="8"></textarea>
230
  <div style="margin-top: 10px; display: flex; align-items: center; gap: 10px;">
231
  <label for="markdown-file-input">Or upload a file:</label>
 
247
 
248
  <fieldset>
249
  <legend>3. Configure Styles</legend>
250
+ <!-- Styling options from previous version go here, unchanged -->
251
  <div class="style-grid">
252
+ <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><option value="'Open Sans', sans-serif">Open Sans</option></optgroup><optgroup label="Serif"><option value="'Times New Roman', serif">Times New Roman</option><option value="'Georgia', serif">Georgia</option><option value="'Playfair Display', serif">Playfair Display</option></optgroup><optgroup label="Monospace"><option value="'Courier New', monospace">Courier New</option><option value="'Roboto Mono', monospace">Roboto Mono</option></optgroup></select></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  <div><label>Font Size (px):</label><input type="number" id="font_size" value="16"></div>
254
+ <div><label>Highlight Theme:</label><select id="highlight_theme">
255
+ <option value="none">None</option>
256
+ {% for style in highlight_styles %}<option value="{{ style }}" {% if style == 'default' %}selected{% endif %}>{{ style }}</option>{% endfor %}
257
+ </select></div>
 
 
 
 
 
258
  <div><label>Text Color:</label><input type="color" id="text_color" value="#333333"></div>
259
  <div><label>Background Color:</label><input type="color" id="background_color" value="#ffffff"></div>
260
  <div><label>Code Padding (px):</label><input type="number" id="code_padding" value="15"></div>
 
278
  <div id="preview-container" class="preview-container"></div>
279
 
280
  <script>
281
+ // --- DOM Elements ---
282
+ const infoBox = document.getElementById('info-box');
283
+ // ... all other element selectors are the same ...
284
  const loadBtn = document.getElementById('load-btn');
285
  const generateBtn = document.getElementById('generate-btn');
286
  const downloadBtn = document.getElementById('download-btn');
 
291
  const previewContainer = document.getElementById('preview-container');
292
  const errorBox = document.getElementById('error-box');
293
 
 
 
 
294
 
295
  function displayError(message) {
296
  errorBox.textContent = message;
297
  errorBox.style.display = 'block';
 
298
  }
299
 
300
+ // --- Event Listeners ---
301
  loadBtn.addEventListener('click', async () => {
302
  loadBtn.textContent = 'Loading...';
303
+ loadBtn.disabled = true;
304
  errorBox.style.display = 'none';
305
+ infoBox.style.display = 'none';
306
  componentsFieldset.style.display = 'none';
307
  componentsContainer.innerHTML = '';
308
 
 
309
  const formData = new FormData();
310
  if (markdownFileInput.files.length > 0) {
311
  formData.append('markdown_file', markdownFileInput.files[0]);
 
315
 
316
  try {
317
  const response = await fetch('/parse', { method: 'POST', body: formData });
318
+ const result = await response.json();
319
 
320
+ if (!response.ok) throw new Error(result.error || `Server responded with status ${response.status}`);
321
 
322
+ infoBox.innerHTML = `Detected Format: <strong>${result.format}</strong>`;
323
+ infoBox.style.display = 'block';
324
+
325
+ if (result.format !== 'Unknown') {
326
  componentsFieldset.style.display = 'block';
327
+ result.components.forEach((comp, index) => {
328
  const div = document.createElement('div');
329
  div.className = 'component-container';
 
330
  div.dataset.type = comp.type;
331
+ div.dataset.filename = comp.filename;
 
332
 
333
+ let reconstructedContent = comp.content;
334
+ // Store original content parts for reconstruction
335
+ div.dataset.content = comp.content;
336
+ if (comp.is_code_block) {
337
+ div.dataset.isCodeBlock = 'true';
338
+ div.dataset.language = comp.language || '';
339
+ reconstructedContent = "```" + (comp.language || '') + "\\n" + comp.content + "\\n```";
340
+ }
341
+ // Store the full reconstructable content for the 'generate' step
342
+ div.dataset.reconstructed = reconstructedContent;
343
+
344
+ if (comp.type === 'section') div.dataset.reconstructed = `## ${comp.filename}\\n${comp.content}`;
345
+ if (comp.type === 'version') div.dataset.reconstructed = `## ${comp.filename}\\n${comp.content}`;
346
 
347
+ div.innerHTML = `
348
  <div class="component-header">
349
  <input type="checkbox" id="comp-check-${index}" class="component-checkbox" checked>
350
  <label for="comp-check-${index}">${comp.filename}</label>
 
360
  displayError('Error parsing content: ' + err.message);
361
  } finally {
362
  loadBtn.textContent = 'Load & Analyze';
363
+ loadBtn.disabled = false;
364
  }
365
  });
366
+
367
  async function handleGeneration(isDownload = false) {
368
+ const buttonToUpdate = isDownload ? downloadBtn : generateBtn;
369
  buttonToUpdate.textContent = 'Generating...';
370
  buttonToUpdate.disabled = true;
371
  errorBox.style.display = 'none';
372
 
373
  let finalMarkdown = "";
374
+ // If components are visible, compose from them. Otherwise, use the text area.
375
  if (componentsFieldset.style.display === 'block') {
376
  const parts = [];
377
  const componentDivs = componentsContainer.querySelectorAll('.component-container');
378
  componentDivs.forEach(div => {
379
  if (div.querySelector('.component-checkbox').checked) {
380
+ parts.push(div.dataset.reconstructed || div.dataset.content);
 
 
 
 
 
 
 
 
 
 
381
  }
382
  });
383
  finalMarkdown = parts.join('\\n\\n---\\n\\n');
 
412
  if (!response.ok) throw new Error(`Download failed: ${response.statusText}`);
413
  const blob = await response.blob();
414
  const url = window.URL.createObjectURL(blob);
415
+ const a = document.createElement('a'); a.style.display = 'none'; a.href = url;
 
 
416
  a.download = 'output.' + payload.download_type;
417
+ document.body.appendChild(a); a.click(); window.URL.revokeObjectURL(url); a.remove();
 
 
 
418
  } else {
419
  const result = await response.json();
420
+ if (!response.ok) throw new Error(result.error || `Server responded with status ${response.status}`);
421
  previewContainer.innerHTML = result.preview_html;
422
  downloadBtn.style.display = 'inline-block';
423
  }
 
429
  buttonToUpdate.disabled = false;
430
  }
431
  }
432
+
433
+ // Other functions like toggleAllComponents and event listeners for generate/download remain the same
434
+ function toggleAllComponents(checked) { componentsContainer.querySelectorAll('.component-checkbox').forEach(cb => cb.checked = checked); }
435
  generateBtn.addEventListener('click', () => handleGeneration(false));
436
  downloadBtn.addEventListener('click', () => handleGeneration(true));
437
+
438
  </script>
439
  </body>
440
  </html>
441
  """, highlight_styles=highlight_styles)
442
 
443
  if __name__ == "__main__":
444
+ # Ensure you have installed the required libraries:
445
+ # pip install Flask markdown imgkit pygments
446
  app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))