Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -7,211 +7,150 @@ import json
|
|
7 |
import mimetypes
|
8 |
import os
|
9 |
import io
|
10 |
-
import uuid
|
11 |
from pathlib import Path
|
12 |
|
13 |
app = Flask(__name__)
|
14 |
|
15 |
GITHUB_API = "https://api.github.com/repos/"
|
16 |
-
#HF_API = "https://huggingface.co/api/spaces/"
|
17 |
|
18 |
def generate_file_tree(paths):
|
19 |
"""Generate a simple file tree from a list of paths."""
|
20 |
-
print("generating file tree")
|
21 |
tree = ["📁 Root"]
|
22 |
sorted_paths = sorted(paths)
|
23 |
for path in sorted_paths:
|
24 |
parts = path.split('/')
|
25 |
indent = " " * (len(parts) - 1)
|
26 |
tree.append(f"{indent}📄 {parts[-1]}")
|
27 |
-
print("generating file tree - Complete")
|
28 |
-
|
29 |
return "\n".join(tree) + "\n\n"
|
30 |
|
31 |
-
def get_all_files(owner, repo, path=""
|
32 |
-
"""Recursively fetch all files from a repository."""
|
33 |
-
|
34 |
-
api_url = f"https://huggingface.co/api/spaces/{owner}/{repo}/tree/main/{path}".rstrip('/')
|
35 |
-
else:
|
36 |
-
api_url = f"{GITHUB_API}{owner}/{repo}/contents/{path}".rstrip('/')
|
37 |
-
|
38 |
try:
|
39 |
-
response = requests.get(api_url, headers={"Accept": "application/json"})
|
40 |
response.raise_for_status()
|
41 |
-
|
42 |
-
|
43 |
-
|
|
|
|
|
44 |
items = response.json()
|
45 |
-
|
46 |
-
|
47 |
-
print(f"Received non-JSON response: {response.text[:100]}...")
|
48 |
return None
|
49 |
-
|
50 |
files = []
|
51 |
for item in items:
|
52 |
if isinstance(item, dict) and item.get('type') == 'file':
|
53 |
files.append(item)
|
54 |
elif isinstance(item, dict) and item.get('type') == 'dir':
|
55 |
-
sub_files = get_all_files(owner, repo, item['path']
|
56 |
if sub_files:
|
57 |
files.extend(sub_files)
|
58 |
return files
|
59 |
-
|
60 |
-
|
61 |
-
print(f"Error fetching repository contents: {str(e)}")
|
62 |
return None
|
63 |
|
64 |
-
|
65 |
-
|
66 |
api = HfApi()
|
|
|
67 |
try:
|
68 |
-
file_list = api.list_repo_files(repo_id=
|
69 |
-
print(f"Files in {
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
dir_part, file_part = file_path.split("/", 1)
|
79 |
-
dir_path = os.path.join(name, dir_part)
|
80 |
-
if not os.path.exists(dir_path):
|
81 |
-
os.makedirs(dir_path)
|
82 |
-
if "/" in file_part:
|
83 |
-
processed_files.extend(get_hf_files(repo, name, dir_part))
|
84 |
-
continue
|
85 |
-
|
86 |
-
# Fetch raw file content
|
87 |
-
raw_url = f"https://huggingface.co/spaces/{repo}/{name}/raw/main/{file_path}"
|
88 |
response = requests.get(raw_url, timeout=10)
|
89 |
response.raise_for_status()
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
print(f"Received HTML instead of raw content for {file_path}: {response.text[:100]}...")
|
94 |
continue
|
95 |
-
|
96 |
-
# Process file
|
97 |
-
filename = os.path.basename(file_path)
|
98 |
-
if "." in filename:
|
99 |
-
pf, sf = filename.rsplit(".", 1)
|
100 |
-
f_name = f"{pf}.{sf}"
|
101 |
-
else:
|
102 |
-
pf = filename
|
103 |
-
sf = ""
|
104 |
-
f_name = pf
|
105 |
-
|
106 |
-
local_path = os.path.join(name, file_path)
|
107 |
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
108 |
-
|
109 |
with open(local_path, 'wb') as file:
|
110 |
file.write(response.content)
|
111 |
-
|
112 |
processed_files.append({"path": file_path})
|
113 |
-
|
114 |
-
|
115 |
-
return processed_files
|
116 |
|
117 |
-
|
118 |
-
|
119 |
-
return []
|
120 |
|
121 |
def get_repo_contents(url):
|
122 |
"""Parse URL and fetch repository contents."""
|
123 |
try:
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
# Fallback approach: manually fetch known files or use a simpler file list
|
128 |
-
# For now, assume a flat structure and fetch known files directly
|
129 |
-
# This is a workaround until a proper API token or endpoint is confirmed
|
130 |
-
known_files = [
|
131 |
-
{'path': 'app.py', 'type': 'file'},
|
132 |
-
{'path': 'README.md', 'type': 'file'}
|
133 |
-
# Add more known paths or implement HTML scraping if needed
|
134 |
-
]
|
135 |
-
#files = get_all_files(owner, repo, "", True) or known_files
|
136 |
files = get_hf_files(owner, repo)
|
|
|
|
|
137 |
return owner, repo, files, True
|
138 |
else: # Assume GitHub URL
|
139 |
-
|
140 |
-
owner, repo = parts[-2], parts[-1]
|
141 |
-
files = get_all_files(owner, repo, "", False)
|
142 |
if files is None:
|
143 |
raise Exception("Failed to fetch GitHub repository contents")
|
144 |
return owner, repo, files, False
|
145 |
except Exception as e:
|
|
|
146 |
return None, None, f"Error fetching repo contents: {str(e)}", False
|
147 |
|
148 |
def process_file_content(file_info, owner, repo, is_hf=False):
|
149 |
"""Process individual file content from a repository."""
|
150 |
content = ""
|
151 |
file_path = file_info['path']
|
152 |
-
|
153 |
try:
|
154 |
if is_hf:
|
155 |
file_url = f"https://huggingface.co/spaces/{owner}/{repo}/raw/main/{file_path}"
|
|
|
|
|
|
|
|
|
|
|
|
|
156 |
else:
|
157 |
file_url = f"{GITHUB_API}{owner}/{repo}/contents/{file_path}"
|
158 |
-
|
159 |
-
|
160 |
-
response.raise_for_status()
|
161 |
-
|
162 |
-
if is_hf:
|
163 |
-
content_raw = response.content
|
164 |
-
size = len(content_raw)
|
165 |
-
file_extension = file_path.split('.')[-1] if '.' in file_path else ''
|
166 |
-
mime_type, _ = mimetypes.guess_type(file_path)
|
167 |
-
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
|
168 |
-
|
169 |
-
if is_text:
|
170 |
-
try:
|
171 |
-
text_content = content_raw.decode('utf-8')
|
172 |
-
if file_extension == 'json':
|
173 |
-
try:
|
174 |
-
json_data = json.loads(text_content)
|
175 |
-
formatted_json = json.dumps(json_data, indent=2)
|
176 |
-
content = f"### File: {file_path}\n```json\n{formatted_json}\n```\n\n"
|
177 |
-
except json.JSONDecodeError:
|
178 |
-
content = f"### File: {file_path}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
|
179 |
-
else:
|
180 |
-
content = f"### File: {file_path}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
|
181 |
-
except UnicodeDecodeError:
|
182 |
-
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
|
183 |
-
else:
|
184 |
-
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
|
185 |
-
else: # GitHub
|
186 |
data = response.json()
|
187 |
-
if 'content' in data:
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
|
|
|
|
|
|
|
|
|
|
195 |
try:
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
content = f"### File: {file_path}\n```json\n{formatted_json}\n```\n\n"
|
202 |
-
except json.JSONDecodeError:
|
203 |
-
content = f"### File: {file_path}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
|
204 |
-
else:
|
205 |
-
content = f"### File: {file_path}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
|
206 |
-
except UnicodeDecodeError:
|
207 |
-
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
|
208 |
else:
|
209 |
-
content = f"### File: {file_path}\n
|
210 |
-
|
211 |
-
content = f"### File: {file_path}\n[
|
|
|
|
|
212 |
except Exception as e:
|
213 |
-
content = f"### File: {file_path}\n[Error fetching
|
214 |
-
|
215 |
return content
|
216 |
|
217 |
def process_uploaded_file(file):
|
@@ -219,11 +158,9 @@ def process_uploaded_file(file):
|
|
219 |
content = ""
|
220 |
filename = file.filename
|
221 |
file_extension = filename.split('.')[-1] if '.' in filename else ''
|
222 |
-
|
223 |
try:
|
224 |
-
content_raw = file.read()
|
225 |
-
size = len(content_raw)
|
226 |
-
|
227 |
mime_type, _ = mimetypes.guess_type(filename)
|
228 |
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
|
229 |
|
@@ -245,26 +182,22 @@ def process_uploaded_file(file):
|
|
245 |
content = f"### File: {filename}\n[Binary file - {size} bytes]\n\n"
|
246 |
except Exception as e:
|
247 |
content = f"### File: {filename}\n[Error processing file: {str(e)}]\n\n"
|
248 |
-
|
249 |
return content
|
250 |
|
251 |
def create_markdown_document(url=None, files=None):
|
252 |
"""Create markdown document from repo contents or uploaded files."""
|
253 |
if url:
|
254 |
owner, repo, contents, is_hf = get_repo_contents(url)
|
255 |
-
|
256 |
if isinstance(contents, str): # Error case
|
257 |
return f"Error: {contents}"
|
258 |
-
|
259 |
markdown_content = f"# {'Space' if is_hf else 'Repository'}: {owner}/{repo}\n\n"
|
260 |
markdown_content += "## File Structure\n```\n"
|
261 |
markdown_content += generate_file_tree([item['path'] for item in contents])
|
262 |
markdown_content += "```\n\n"
|
263 |
markdown_content += f"Below are the contents of all files in the {'space' if is_hf else 'repository'}:\n\n"
|
264 |
-
|
265 |
for item in contents:
|
266 |
markdown_content += process_file_content(item, owner, repo, is_hf)
|
267 |
-
else:
|
268 |
markdown_content = "# Uploaded Files\n\n"
|
269 |
markdown_content += "## File Structure\n```\n"
|
270 |
markdown_content += generate_file_tree([file.filename for file in files])
|
@@ -272,7 +205,6 @@ def create_markdown_document(url=None, files=None):
|
|
272 |
markdown_content += "Below are the contents of all uploaded files:\n\n"
|
273 |
for file in files:
|
274 |
markdown_content += process_uploaded_file(file)
|
275 |
-
|
276 |
return markdown_content
|
277 |
|
278 |
@app.route('/')
|
@@ -281,31 +213,27 @@ def index():
|
|
281 |
|
282 |
@app.route('/process', methods=['POST'])
|
283 |
def process():
|
284 |
-
# Ensure consistent response structure
|
285 |
response_data = {'markdown': '', 'html': '', 'filename': '', 'error': None}
|
286 |
|
287 |
if 'files[]' in request.files:
|
288 |
files = request.files.getlist('files[]')
|
289 |
-
if not files:
|
290 |
response_data['error'] = 'No files uploaded'
|
291 |
return jsonify(response_data), 400
|
292 |
-
|
293 |
markdown_content = create_markdown_document(files=files)
|
294 |
response_data['markdown'] = "```markdown\n" + markdown_content + "\n```"
|
295 |
response_data['html'] = markdown.markdown(markdown_content)
|
296 |
response_data['filename'] = "uploaded_files_summary.md"
|
297 |
else:
|
298 |
-
repo_url = request.json.get('repo_url')
|
299 |
if not repo_url:
|
300 |
response_data['error'] = 'Please provide a repository URL or upload files'
|
301 |
return jsonify(response_data), 400
|
302 |
-
|
303 |
markdown_content = create_markdown_document(repo_url)
|
304 |
owner, repo, contents, is_hf = get_repo_contents(repo_url)
|
305 |
-
if not owner:
|
306 |
-
response_data['error'] = markdown_content
|
307 |
return jsonify(response_data), 400
|
308 |
-
|
309 |
response_data['markdown'] = markdown_content
|
310 |
response_data['html'] = markdown.markdown(markdown_content)
|
311 |
response_data['filename'] = f"{owner}_{repo}_summary.md"
|
@@ -314,28 +242,24 @@ def process():
|
|
314 |
|
315 |
@app.route('/download', methods=['POST'])
|
316 |
def download():
|
317 |
-
markdown_content = request.json.get('markdown')
|
318 |
-
filename = request.json.get('filename')
|
319 |
-
|
320 |
buffer = io.BytesIO()
|
321 |
buffer.write(markdown_content.encode('utf-8'))
|
322 |
buffer.seek(0)
|
323 |
-
|
324 |
return send_file(
|
325 |
buffer,
|
326 |
as_attachment=True,
|
327 |
download_name=filename,
|
328 |
mimetype='text/markdown'
|
329 |
)
|
330 |
-
with open("html_template.html", "r") as f:
|
331 |
-
html_template=f.read()
|
332 |
-
f.close()
|
333 |
-
|
334 |
-
|
335 |
-
if not os.path.exists('templates'):
|
336 |
-
os.makedirs('templates')
|
337 |
-
with open('templates/index.html', 'w') as f:
|
338 |
-
f.write(html_template)
|
339 |
|
340 |
if __name__ == '__main__':
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
341 |
app.run(host="0.0.0.0", port=7860, debug=True)
|
|
|
7 |
import mimetypes
|
8 |
import os
|
9 |
import io
|
|
|
10 |
from pathlib import Path
|
11 |
|
12 |
app = Flask(__name__)
|
13 |
|
14 |
GITHUB_API = "https://api.github.com/repos/"
|
|
|
15 |
|
16 |
def generate_file_tree(paths):
|
17 |
"""Generate a simple file tree from a list of paths."""
|
|
|
18 |
tree = ["📁 Root"]
|
19 |
sorted_paths = sorted(paths)
|
20 |
for path in sorted_paths:
|
21 |
parts = path.split('/')
|
22 |
indent = " " * (len(parts) - 1)
|
23 |
tree.append(f"{indent}📄 {parts[-1]}")
|
|
|
|
|
24 |
return "\n".join(tree) + "\n\n"
|
25 |
|
26 |
+
def get_all_files(owner, repo, path=""):
|
27 |
+
"""Recursively fetch all files from a GitHub repository."""
|
28 |
+
api_url = f"{GITHUB_API}{owner}/{repo}/contents/{path}".rstrip('/')
|
|
|
|
|
|
|
|
|
29 |
try:
|
30 |
+
response = requests.get(api_url, headers={"Accept": "application/json"}, timeout=10)
|
31 |
response.raise_for_status()
|
32 |
+
content_type = response.headers.get('Content-Type', '')
|
33 |
+
if not content_type.startswith('application/json'):
|
34 |
+
print(f"Error: Received non-JSON response from GitHub for {api_url}: {response.text[:100]}...")
|
35 |
+
return None
|
36 |
+
try:
|
37 |
items = response.json()
|
38 |
+
except json.JSONDecodeError as e:
|
39 |
+
print(f"Error: Failed to parse JSON from GitHub for {api_url}: {str(e)}. Response: {response.text[:100]}...")
|
|
|
40 |
return None
|
|
|
41 |
files = []
|
42 |
for item in items:
|
43 |
if isinstance(item, dict) and item.get('type') == 'file':
|
44 |
files.append(item)
|
45 |
elif isinstance(item, dict) and item.get('type') == 'dir':
|
46 |
+
sub_files = get_all_files(owner, repo, item['path'])
|
47 |
if sub_files:
|
48 |
files.extend(sub_files)
|
49 |
return files
|
50 |
+
except requests.RequestException as e:
|
51 |
+
print(f"Error fetching GitHub contents from {api_url}: {str(e)}")
|
|
|
52 |
return None
|
53 |
|
54 |
+
def get_hf_files(owner, repo):
|
55 |
+
"""Fetch all files from a Hugging Face Space."""
|
56 |
api = HfApi()
|
57 |
+
repo_id = f"{owner}/{repo}"
|
58 |
try:
|
59 |
+
file_list = api.list_repo_files(repo_id=repo_id, repo_type="space")
|
60 |
+
print(f"Files in HF Space {repo_id}: {file_list}")
|
61 |
+
except Exception as e:
|
62 |
+
print(f"Error listing files for HF Space {repo_id}: {str(e)}")
|
63 |
+
return []
|
64 |
+
|
65 |
+
processed_files = []
|
66 |
+
local_dir = repo
|
67 |
+
if not os.path.exists(local_dir):
|
68 |
+
os.makedirs(local_dir)
|
69 |
|
70 |
+
for file_path in file_list:
|
71 |
+
raw_url = f"https://huggingface.co/spaces/{owner}/{repo}/raw/main/{file_path}"
|
72 |
+
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
response = requests.get(raw_url, timeout=10)
|
74 |
response.raise_for_status()
|
75 |
+
content_type = response.headers.get('Content-Type', '')
|
76 |
+
if content_type.startswith('text/html'):
|
77 |
+
print(f"Error: Received HTML instead of raw content for {raw_url}: {response.text[:100]}...")
|
|
|
78 |
continue
|
79 |
+
local_path = os.path.join(local_dir, file_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
os.makedirs(os.path.dirname(local_path), exist_ok=True)
|
|
|
81 |
with open(local_path, 'wb') as file:
|
82 |
file.write(response.content)
|
|
|
83 |
processed_files.append({"path": file_path})
|
84 |
+
except requests.RequestException as e:
|
85 |
+
print(f"Error downloading {file_path} from {raw_url}: {str(e)}")
|
|
|
86 |
|
87 |
+
print(f"Processed files from HF Space {repo_id}: {processed_files}")
|
88 |
+
return processed_files
|
|
|
89 |
|
90 |
def get_repo_contents(url):
|
91 |
"""Parse URL and fetch repository contents."""
|
92 |
try:
|
93 |
+
parts = url.rstrip('/').split('/')
|
94 |
+
owner, repo = parts[-2], parts[-1]
|
95 |
+
if "huggingface.co" in url.lower():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
files = get_hf_files(owner, repo)
|
97 |
+
if not files and files is not None: # Empty list is valid, None indicates error
|
98 |
+
raise Exception("No files found in the Hugging Face Space")
|
99 |
return owner, repo, files, True
|
100 |
else: # Assume GitHub URL
|
101 |
+
files = get_all_files(owner, repo)
|
|
|
|
|
102 |
if files is None:
|
103 |
raise Exception("Failed to fetch GitHub repository contents")
|
104 |
return owner, repo, files, False
|
105 |
except Exception as e:
|
106 |
+
print(f"Error processing URL {url}: {str(e)}")
|
107 |
return None, None, f"Error fetching repo contents: {str(e)}", False
|
108 |
|
109 |
def process_file_content(file_info, owner, repo, is_hf=False):
|
110 |
"""Process individual file content from a repository."""
|
111 |
content = ""
|
112 |
file_path = file_info['path']
|
|
|
113 |
try:
|
114 |
if is_hf:
|
115 |
file_url = f"https://huggingface.co/spaces/{owner}/{repo}/raw/main/{file_path}"
|
116 |
+
response = requests.get(file_url, timeout=10)
|
117 |
+
response.raise_for_status()
|
118 |
+
content_raw = response.content
|
119 |
+
content_type = response.headers.get('Content-Type', '')
|
120 |
+
if content_type.startswith('text/html'):
|
121 |
+
raise Exception(f"Received HTML instead of raw content: {response.text[:100]}...")
|
122 |
else:
|
123 |
file_url = f"{GITHUB_API}{owner}/{repo}/contents/{file_path}"
|
124 |
+
response = requests.get(file_url, headers={"Accept": "application/json"}, timeout=10)
|
125 |
+
response.raise_for_status()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
data = response.json()
|
127 |
+
if 'content' not in data:
|
128 |
+
raise Exception("No content available in GitHub API response")
|
129 |
+
content_raw = base64.b64decode(data['content'])
|
130 |
+
|
131 |
+
size = len(content_raw)
|
132 |
+
file_extension = file_path.split('.')[-1] if '.' in file_path else ''
|
133 |
+
mime_type, _ = mimetypes.guess_type(file_path)
|
134 |
+
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
|
135 |
+
|
136 |
+
if is_text:
|
137 |
+
try:
|
138 |
+
text_content = content_raw.decode('utf-8')
|
139 |
+
if file_extension == 'json':
|
140 |
try:
|
141 |
+
json_data = json.loads(text_content)
|
142 |
+
formatted_json = json.dumps(json_data, indent=2)
|
143 |
+
content = f"### File: {file_path}\n```json\n{formatted_json}\n```\n\n"
|
144 |
+
except json.JSONDecodeError:
|
145 |
+
content = f"### File: {file_path}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
else:
|
147 |
+
content = f"### File: {file_path}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
|
148 |
+
except UnicodeDecodeError:
|
149 |
+
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
|
150 |
+
else:
|
151 |
+
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
|
152 |
except Exception as e:
|
153 |
+
content = f"### File: {file_path}\n[Error fetching content: {str(e)}]\n\n"
|
|
|
154 |
return content
|
155 |
|
156 |
def process_uploaded_file(file):
|
|
|
158 |
content = ""
|
159 |
filename = file.filename
|
160 |
file_extension = filename.split('.')[-1] if '.' in filename else ''
|
|
|
161 |
try:
|
162 |
+
content_raw = file.read()
|
163 |
+
size = len(content_raw)
|
|
|
164 |
mime_type, _ = mimetypes.guess_type(filename)
|
165 |
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
|
166 |
|
|
|
182 |
content = f"### File: {filename}\n[Binary file - {size} bytes]\n\n"
|
183 |
except Exception as e:
|
184 |
content = f"### File: {filename}\n[Error processing file: {str(e)}]\n\n"
|
|
|
185 |
return content
|
186 |
|
187 |
def create_markdown_document(url=None, files=None):
|
188 |
"""Create markdown document from repo contents or uploaded files."""
|
189 |
if url:
|
190 |
owner, repo, contents, is_hf = get_repo_contents(url)
|
|
|
191 |
if isinstance(contents, str): # Error case
|
192 |
return f"Error: {contents}"
|
|
|
193 |
markdown_content = f"# {'Space' if is_hf else 'Repository'}: {owner}/{repo}\n\n"
|
194 |
markdown_content += "## File Structure\n```\n"
|
195 |
markdown_content += generate_file_tree([item['path'] for item in contents])
|
196 |
markdown_content += "```\n\n"
|
197 |
markdown_content += f"Below are the contents of all files in the {'space' if is_hf else 'repository'}:\n\n"
|
|
|
198 |
for item in contents:
|
199 |
markdown_content += process_file_content(item, owner, repo, is_hf)
|
200 |
+
else:
|
201 |
markdown_content = "# Uploaded Files\n\n"
|
202 |
markdown_content += "## File Structure\n```\n"
|
203 |
markdown_content += generate_file_tree([file.filename for file in files])
|
|
|
205 |
markdown_content += "Below are the contents of all uploaded files:\n\n"
|
206 |
for file in files:
|
207 |
markdown_content += process_uploaded_file(file)
|
|
|
208 |
return markdown_content
|
209 |
|
210 |
@app.route('/')
|
|
|
213 |
|
214 |
@app.route('/process', methods=['POST'])
|
215 |
def process():
|
|
|
216 |
response_data = {'markdown': '', 'html': '', 'filename': '', 'error': None}
|
217 |
|
218 |
if 'files[]' in request.files:
|
219 |
files = request.files.getlist('files[]')
|
220 |
+
if not files or all(not file.filename for file in files):
|
221 |
response_data['error'] = 'No files uploaded'
|
222 |
return jsonify(response_data), 400
|
|
|
223 |
markdown_content = create_markdown_document(files=files)
|
224 |
response_data['markdown'] = "```markdown\n" + markdown_content + "\n```"
|
225 |
response_data['html'] = markdown.markdown(markdown_content)
|
226 |
response_data['filename'] = "uploaded_files_summary.md"
|
227 |
else:
|
228 |
+
repo_url = request.json.get('repo_url', '').strip()
|
229 |
if not repo_url:
|
230 |
response_data['error'] = 'Please provide a repository URL or upload files'
|
231 |
return jsonify(response_data), 400
|
|
|
232 |
markdown_content = create_markdown_document(repo_url)
|
233 |
owner, repo, contents, is_hf = get_repo_contents(repo_url)
|
234 |
+
if not owner: # Error case
|
235 |
+
response_data['error'] = markdown_content
|
236 |
return jsonify(response_data), 400
|
|
|
237 |
response_data['markdown'] = markdown_content
|
238 |
response_data['html'] = markdown.markdown(markdown_content)
|
239 |
response_data['filename'] = f"{owner}_{repo}_summary.md"
|
|
|
242 |
|
243 |
@app.route('/download', methods=['POST'])
|
244 |
def download():
|
245 |
+
markdown_content = request.json.get('markdown', '')
|
246 |
+
filename = request.json.get('filename', 'document.md')
|
|
|
247 |
buffer = io.BytesIO()
|
248 |
buffer.write(markdown_content.encode('utf-8'))
|
249 |
buffer.seek(0)
|
|
|
250 |
return send_file(
|
251 |
buffer,
|
252 |
as_attachment=True,
|
253 |
download_name=filename,
|
254 |
mimetype='text/markdown'
|
255 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
256 |
|
257 |
if __name__ == '__main__':
|
258 |
+
# Ensure templates directory and index.html exist
|
259 |
+
if not os.path.exists('templates'):
|
260 |
+
os.makedirs('templates')
|
261 |
+
# You’ll need to provide your own index.html or use a placeholder
|
262 |
+
if not os.path.exists('templates/index.html'):
|
263 |
+
with open('templates/index.html', 'w') as f:
|
264 |
+
f.write('<!DOCTYPE html><html><body><h1>Repo to Markdown</h1><p>Use POST /process to convert repo contents.</p></body></html>')
|
265 |
app.run(host="0.0.0.0", port=7860, debug=True)
|