Spaces:
Running
Running
File size: 17,255 Bytes
b42fffe 10099e5 540d342 a8175e6 10099e5 b42fffe 10099e5 a8175e6 b42fffe a8175e6 b42fffe a8175e6 d6d177a a8175e6 d6d177a a8175e6 d6d177a a8175e6 b42fffe a8175e6 10099e5 b42fffe d6d177a a8175e6 b42fffe a8175e6 10099e5 a8175e6 10099e5 b42fffe a8175e6 10099e5 a8175e6 10099e5 a8175e6 b42fffe d6d177a b42fffe a8175e6 10099e5 b42fffe a8175e6 f1d73d7 a8175e6 f1d73d7 a8175e6 10099e5 b42fffe a8175e6 b42fffe 10099e5 b42fffe a8175e6 b42fffe a8175e6 b42fffe a8175e6 b42fffe 10099e5 b42fffe a8175e6 b42fffe a8175e6 b42fffe a8175e6 b42fffe a8175e6 b42fffe a8175e6 b42fffe 10099e5 b42fffe d6d177a b42fffe d6d177a b42fffe d6d177a b42fffe d6d177a b42fffe d6d177a a8175e6 d6d177a 10099e5 d6d177a 10099e5 b42fffe a8175e6 b42fffe 10099e5 b42fffe 10099e5 b42fffe 10099e5 540d342 10099e5 b42fffe a8175e6 b42fffe a8175e6 b42fffe 540d342 10099e5 b42fffe 10099e5 b42fffe a8175e6 b42fffe 540d342 b42fffe 10099e5 540d342 b42fffe 10099e5 540d342 b42fffe 540d342 b42fffe 540d342 b42fffe 540d342 b42fffe 540d342 b42fffe 540d342 b42fffe 10099e5 6321348 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 |
from flask import Flask, render_template, request, jsonify, send_file
import requests
import base64
import markdown
import json
import mimetypes
import os
import io
app = Flask(__name__)
GITHUB_API = "https://api.github.com/repos/"
HF_API = "https://huggingface.co/api/spaces/"
def generate_file_tree(paths):
"""Generate a simple file tree from a list of paths."""
tree = ["📁 Root"]
sorted_paths = sorted(paths)
for path in sorted_paths:
parts = path.split('/')
indent = " " * (len(parts) - 1)
tree.append(f"{indent}📄 {parts[-1]}")
return "\n".join(tree) + "\n\n"
def get_all_files(owner, repo, path="", is_hf=False):
"""Recursively fetch all files from a repository."""
if is_hf:
# Attempt to fetch file list from Hugging Face Space (publicly accessible files)
api_url = f"https://huggingface.co/spaces/{owner}/{repo}/tree/main/{path}".rstrip('/')
else:
api_url = f"{GITHUB_API}{owner}/{repo}/contents/{path}".rstrip('/')
try:
response = requests.get(api_url, headers={"Accept": "application/json"})
response.raise_for_status()
items = response.json()
# Hugging Face might not return JSON in the same format; adjust if HTML is returned
if isinstance(items, str): # If response isn’t JSON, it’s likely HTML
return None # Fallback to error handling
files = []
for item in items:
if item['type'] == 'file':
files.append(item)
elif item['type'] == 'dir':
files.extend(get_all_files(owner, repo, item['path'], is_hf))
return files
except Exception as e:
return None
def get_repo_contents(url):
"""Parse URL and fetch repository contents."""
try:
if "huggingface.co" in url:
parts = url.rstrip('/').split('/')
owner, repo = parts[-2], parts[-1]
# Fallback approach: manually fetch known files or use a simpler file list
# For now, assume a flat structure and fetch known files directly
# This is a workaround until a proper API token or endpoint is confirmed
known_files = [
{'path': 'app.py', 'type': 'file'},
{'path': 'README.md', 'type': 'file'}
# Add more known paths or implement HTML scraping if needed
]
files = get_all_files(owner, repo, "", True) or known_files
return owner, repo, files, True
else: # Assume GitHub URL
parts = url.rstrip('/').split('/')
owner, repo = parts[-2], parts[-1]
files = get_all_files(owner, repo, "", False)
if files is None:
raise Exception("Failed to fetch GitHub repository contents")
return owner, repo, files, False
except Exception as e:
return None, None, f"Error fetching repo contents: {str(e)}", False
def process_file_content(file_info, owner, repo, is_hf=False):
"""Process individual file content from a repository."""
content = ""
file_path = file_info['path']
try:
if is_hf:
file_url = f"https://huggingface.co/spaces/{owner}/{repo}/raw/main/{file_path}"
else:
file_url = f"{GITHUB_API}{owner}/{repo}/contents/{file_path}"
response = requests.get(file_url)
response.raise_for_status()
if is_hf:
content_raw = response.content
size = len(content_raw)
file_extension = file_path.split('.')[-1] if '.' in file_path else ''
mime_type, _ = mimetypes.guess_type(file_path)
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
if is_text:
try:
text_content = content_raw.decode('utf-8')
if file_extension == 'json':
try:
json_data = json.loads(text_content)
formatted_json = json.dumps(json_data, indent=2)
content = f"### File: {file_path}\n```json\n{formatted_json}\n```\n\n"
except json.JSONDecodeError:
content = f"### File: {file_path}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
else:
content = f"### File: {file_path}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
except UnicodeDecodeError:
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
else:
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
else: # GitHub
data = response.json()
if 'content' in data:
content_raw = base64.b64decode(data['content'])
size = data['size']
file_extension = file_path.split('.')[-1] if '.' in file_path else ''
mime_type, _ = mimetypes.guess_type(file_path)
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
if is_text:
try:
text_content = content_raw.decode('utf-8')
if file_extension == 'json':
try:
json_data = json.loads(text_content)
formatted_json = json.dumps(json_data, indent=2)
content = f"### File: {file_path}\n```json\n{formatted_json}\n```\n\n"
except json.JSONDecodeError:
content = f"### File: {file_path}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
else:
content = f"### File: {file_path}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
except UnicodeDecodeError:
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
else:
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
else:
content = f"### File: {file_path}\n[No content available]\n\n"
except Exception as e:
content = f"### File: {file_path}\n[Error fetching file content: {str(e)}]\n\n"
return content
def process_uploaded_file(file):
"""Process uploaded file content."""
content = ""
filename = file.filename
file_extension = filename.split('.')[-1] if '.' in filename else ''
try:
content_raw = file.read() # Read file content into memory
size = len(content_raw) # Compute size in bytes
mime_type, _ = mimetypes.guess_type(filename)
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
if is_text:
try:
text_content = content_raw.decode('utf-8')
if file_extension == 'json':
try:
json_data = json.loads(text_content)
formatted_json = json.dumps(json_data, indent=2)
content = f"### File: {filename}\n```json\n{formatted_json}\n```\n\n"
except json.JSONDecodeError:
content = f"### File: {filename}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
else:
content = f"### File: {filename}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
except UnicodeDecodeError:
content = f"### File: {filename}\n[Binary file - {size} bytes]\n\n"
else:
content = f"### File: {filename}\n[Binary file - {size} bytes]\n\n"
except Exception as e:
content = f"### File: {filename}\n[Error processing file: {str(e)}]\n\n"
return content
def create_markdown_document(url=None, files=None):
"""Create markdown document from repo contents or uploaded files."""
if url:
owner, repo, contents, is_hf = get_repo_contents(url)
if isinstance(contents, str): # Error case
return f"Error: {contents}"
markdown_content = f"# {'Space' if is_hf else 'Repository'}: {owner}/{repo}\n\n"
markdown_content += "## File Structure\n```\n"
markdown_content += generate_file_tree([item['path'] for item in contents])
markdown_content += "```\n\n"
markdown_content += f"Below are the contents of all files in the {'space' if is_hf else 'repository'}:\n\n"
for item in contents:
markdown_content += process_file_content(item, owner, repo, is_hf)
else: # Handle uploaded files
markdown_content = "# Uploaded Files\n\n"
markdown_content += "## File Structure\n```\n"
markdown_content += generate_file_tree([file.filename for file in files])
markdown_content += "```\n\n"
markdown_content += "Below are the contents of all uploaded files:\n\n"
for file in files:
markdown_content += process_uploaded_file(file)
return markdown_content
@app.route('/')
def index():
return render_template('index.html')
@app.route('/process', methods=['POST'])
def process():
# Ensure consistent response structure
response_data = {'markdown': '', 'html': '', 'filename': '', 'error': None}
if 'files[]' in request.files:
files = request.files.getlist('files[]')
if not files:
response_data['error'] = 'No files uploaded'
return jsonify(response_data), 400
markdown_content = create_markdown_document(files=files)
response_data['markdown'] = markdown_content
response_data['html'] = markdown.markdown(markdown_content)
response_data['filename'] = "uploaded_files_summary.md"
else:
repo_url = request.json.get('repo_url')
if not repo_url:
response_data['error'] = 'Please provide a repository URL or upload files'
return jsonify(response_data), 400
markdown_content = create_markdown_document(repo_url)
owner, repo, contents, is_hf = get_repo_contents(repo_url)
if not owner:
response_data['error'] = markdown_content # Error message from get_repo_contents
return jsonify(response_data), 400
response_data['markdown'] = markdown_content
response_data['html'] = markdown.markdown(markdown_content)
response_data['filename'] = f"{owner}_{repo}_summary.md"
return jsonify(response_data)
@app.route('/download', methods=['POST'])
def download():
markdown_content = request.json.get('markdown')
filename = request.json.get('filename')
buffer = io.BytesIO()
buffer.write(markdown_content.encode('utf-8'))
buffer.seek(0)
return send_file(
buffer,
as_attachment=True,
download_name=filename,
mimetype='text/markdown'
)
html_template = """
<!DOCTYPE html>
<html>
<head>
<title>Repo & Files to Markdown</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
max-width: 1200px;
margin: 0 auto;
}
.container {
padding: 20px;
}
textarea {
width: 100%;
height: 400px;
margin-top: 20px;
font-family: monospace;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
margin: 5px;
}
button:hover {
background-color: #45a049;
}
#output {
margin-top: 20px;
border: 1px solid #ddd;
padding: 20px;
background-color: #f9f9f9;
}
.spinner {
display: none;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="container">
<h1>Repository & Files to Markdown Converter</h1>
<p>Enter a GitHub/Hugging Face Space URL (e.g., https://huggingface.co/spaces/username/space)</p>
<input type="text" id="repoUrl" style="width: 100%; padding: 8px;" placeholder="Enter GitHub or Hugging Face Space URL">
<p>OR upload files (select multiple files or a folder - folder upload supported in Chrome)</p>
<input type="file" id="fileInput" multiple webkitdirectory style="margin: 10px 0;">
<br>
<button onclick="processRepo()">Convert URL</button>
<button onclick="processFiles()">Convert Files</button>
<button id="downloadBtn" style="display: none;" onclick="downloadMarkdown()">Download .md</button>
<div id="spinner" class="spinner"></div>
<h2>Markdown Output:</h2>
<textarea id="markdownOutput" readonly></textarea>
<h2>Preview:</h2>
<div id="output"></div>
</div>
<script>
let currentMarkdown = '';
let currentFilename = '';
async function processRepo() {
const repoUrl = document.getElementById('repoUrl').value;
await processContent('/process', { repo_url: repoUrl });
}
async function processFiles() {
const files = document.getElementById('fileInput').files;
if (files.length === 0) {
alert('Please select at least one file or folder');
return;
}
const formData = new FormData();
for (let file of files) {
formData.append('files[]', file);
}
await processContent('/process', formData, false);
}
async function processContent(url, data, isJson = true) {
const spinner = document.getElementById('spinner');
const buttons = document.querySelectorAll('button');
spinner.style.display = 'block';
buttons.forEach(btn => btn.disabled = true);
try {
const options = {
method: 'POST',
...(isJson ? {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
} : { body: data })
};
const response = await fetch(url, options);
const result = await response.json();
if (result.error) {
alert(result.error);
return;
}
currentMarkdown = result.markdown;
currentFilename = result.filename;
document.getElementById('markdownOutput').value = result.markdown;
document.getElementById('output').innerHTML = result.html;
document.getElementById('downloadBtn').style.display = 'inline-block';
} catch (error) {
alert('An error occurred: ' + error.message);
} finally {
spinner.style.display = 'none';
buttons.forEach(btn => btn.disabled = false);
}
}
async function downloadMarkdown() {
try {
const response = await fetch('/download', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
markdown: currentMarkdown,
filename: currentFilename
})
});
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = currentFilename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
} catch (error) {
alert('Error downloading file: ' + error.message);
}
}
</script>
</body>
</html>
"""
if not os.path.exists('templates'):
os.makedirs('templates')
with open('templates/index.html', 'w') as f:
f.write(html_template)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=7860, debug=True) |