broadfield-dev commited on
Commit
471be14
·
verified ·
1 Parent(s): 6fb9f70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +312 -183
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
- # Define default values for styling options
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({'type': 'intro', 'filename': 'Introduction', 'content': intro_text, 'is_code_block': False, 'language': ''})
 
 
 
 
 
 
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 entire content is a single fenced code block
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({'type': 'file', 'filename': filename, 'content': inner_content, 'is_code_block': True, 'language': language})
 
 
 
 
 
 
56
  else:
57
  # It's plain text (e.g., binary file notification)
58
- components.append({'type': 'file', 'filename': filename, 'content': raw_content, 'is_code_block': False, 'language': ''})
 
 
 
 
 
 
59
 
60
  return components
61
 
62
- @app.route("/", methods=["GET", "POST"])
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
- # Set defaults for a GET request
72
- markdown_text = ""
73
- download_type = "png"
74
- styles = DEFAULT_STYLES.copy()
75
- include_fontawesome = False
76
-
77
- if request.method == "POST":
78
- # Always update styles and settings from the form on any POST
79
- styles = {key: request.form.get(key, default) for key, default in DEFAULT_STYLES.items()}
80
- include_fontawesome = "include_fontawesome" in request.form
81
- download_type = request.form.get("download_type", "png")
82
-
83
- # --- TEXT PROCESSING LOGIC ---
84
- # Prioritize new text/file upload. This is the source of truth for parsing.
85
- new_markdown_text = request.form.get("markdown_text", "")
86
- uploaded_file = request.files.get("markdown_file")
87
-
88
- if uploaded_file and uploaded_file.filename != '':
89
- try:
90
- markdown_text = uploaded_file.read().decode("utf-8")
91
- except Exception as e:
92
- error_message = f"Error reading file: {e}"
93
- markdown_text = "" # Clear text on error
94
- else:
95
- markdown_text = new_markdown_text
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
- # --- PARSING & COMPONENT BUILDING ---
98
- if markdown_text and is_repo2markdown_format(markdown_text):
99
- try:
100
- # Always re-parse the source text to generate fresh components
101
- parsed_components = parse_repo2markdown(markdown_text)
102
- final_markdown_parts = []
103
-
104
- # Check for user selections and reconstruct both the component list for the UI
105
- # and the final markdown for rendering.
106
- for i, comp_data in enumerate(parsed_components):
107
- is_selected = f'include_comp_{i}' in request.form
108
-
109
- # Update component with selection status for re-rendering the UI
110
- comp_data['is_selected'] = is_selected
111
- components.append(comp_data)
112
-
113
- # If selected, add it to the list for the final document
114
- if is_selected:
115
- if comp_data['type'] == 'intro':
116
- final_markdown_parts.append(comp_data['content'])
117
- else: # It's a file
118
- reconstructed_content = ""
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
- # If not Repo2Markdown format, just treat it as plain markdown
132
- final_markdown_to_render = markdown_text
133
 
134
- # --- HTML & PNG Conversion Logic ---
135
- if final_markdown_to_render:
136
- try:
137
- html_content = markdown.markdown(final_markdown_to_render, extensions=['fenced_code', 'tables'])
138
-
139
- 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 ""
140
- style_block = f"""<style>
141
- body {{ font-family: {styles['font_family']}; font-size: {styles['font_size']}px; color: {styles['text_color']}; background-color: {styles['background_color']}; padding: 25px; display: inline-block; }}
142
- h3 {{ border-bottom: 1px solid #ccc; padding-bottom: 5px; margin-top: 2em; }}
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
- .download-btn { background-color: #28a745; color: white; }
 
 
193
  .download-btn:hover { background-color: #218838; }
194
- .preview { border: 1px solid #ddd; padding: 20px; margin-top: 20px; background: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
195
- .error { color: #D8000C; background-color: #FFD2D2; padding: 10px; border-radius: 5px; margin-top: 15px; }
 
 
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 method="post" enctype="multipart/form-data">
216
  <fieldset>
217
- <legend>Source Content</legend>
218
- <div class="info">Paste your content below, or upload a file. If Repo2Markdown format is detected, component selection will appear.</div>
219
- <textarea name="markdown_text" rows="8" placeholder="Paste your Markdown here...">{{ markdown_text }}</textarea>
220
  <div style="margin-top: 10px; display: flex; align-items: center; gap: 10px;">
221
- <label for="markdown_file" style="margin-bottom:0;">Or upload a file:</label>
222
- <input type="file" name="markdown_file" id="markdown_file" accept=".md,.txt,text/markdown">
 
 
 
223
  </div>
224
  </fieldset>
225
 
226
- {% if components %}
227
- <fieldset>
228
- <legend>Detected File Components</legend>
229
- <div class="selection-controls">
230
- <button type="button" onclick="toggleAllComponents(true)">Select All</button>
231
- <button type="button" onclick="toggleAllComponents(false)">Deselect All</button>
232
- </div>
233
- <div class="component-grid">
234
- {% for comp in components %}
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>Styling Options</legend>
251
  <div class="style-grid">
252
- <div><label for="font_family">Font Family:</label><select id="font_family" name="font_family"><option value="'Arial', sans-serif" {% if styles.font_family == "'Arial', sans-serif" %}selected{% endif %}>Arial</option><option value="'Georgia', serif" {% if styles.font_family == "'Georgia', serif" %}selected{% endif %}>Georgia</option><option value="'Times New Roman', serif" {% if styles.font_family == "'Times New Roman', serif" %}selected{% endif %}>Times New Roman</option><option value="'Verdana', sans-serif" {% if styles.font_family == "'Verdana', sans-serif" %}selected{% endif %}>Verdana</option><option value="'Courier New', monospace" {% if styles.font_family == "'Courier New', monospace" %}selected{% endif %}>Courier New</option></select></div>
253
- <div><label for="font_size">Font Size (px):</label><input type="number" id="font_size" name="font_size" value="{{ styles.font_size }}"></div>
254
- <div><label for="text_color">Text Color:</label><input type="color" id="text_color" name="text_color" value="{{ styles.text_color }}"></div>
255
- <div><label for="background_color">Background Color:</label><input type="color" id="background_color" name="background_color" value="{{ styles.background_color }}"></div>
256
- <div><label for="code_bg_color">Code BG Color:</label><input type="color" id="code_bg_color" name="code_bg_color" value="{{ styles.code_bg_color }}"></div>
257
- <div><label for="code_padding">Code Padding (px):</label><input type="number" id="code_padding" name="code_padding" value="{{ styles.code_padding }}"></div>
258
  </div>
259
- <div><input type="checkbox" id="include_fontawesome" name="include_fontawesome" {% if include_fontawesome %}checked{% endif %}><label for="include_fontawesome">Include Font Awesome (for icons)</label></div>
260
- <div><label for="custom_css">Custom CSS:</label><textarea id="custom_css" name="custom_css" rows="4" placeholder="e.g., h1 { color: blue; }">{{ styles.custom_css }}</textarea></div>
261
  </fieldset>
262
 
263
  <div class="controls">
264
  <div class="main-actions">
265
- <button type="submit" class="action-btn">Generate / Update Preview</button>
266
- <div><label for="download_type">Output format:</label><select id="download_type" name="download_type"><option value="png" {% if download_type == 'png' %}selected{% endif %}>PNG</option><option value="html" {% if download_type == 'html' %}selected{% endif %}>HTML</option></select></div>
267
- {% if download_available %}<button type="submit" name="download" value="true" class="download-btn">Download {{ download_type.upper() }}</button>{% endif %}
268
  </div>
269
  </div>
270
  </form>
271
 
272
- {% if error_message %}<p class="error">{{ error_message }}</p>{% endif %}
273
- {% if preview_html %}<h2>Preview</h2><div class="preview">{{ preview_html | safe }}</div>{% endif %}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)))