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