Spaces:
Running
Running
Create core.py
Browse files
core.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import base64
|
3 |
+
import json
|
4 |
+
import mimetypes
|
5 |
+
import os
|
6 |
+
from huggingface_hub import HfApi
|
7 |
+
from pathlib import Path
|
8 |
+
|
9 |
+
GITHUB_API = "https://api.github.com/repos/"
|
10 |
+
|
11 |
+
def generate_file_tree(paths):
|
12 |
+
"""Generate a simple file tree from a list of paths."""
|
13 |
+
tree = ["📁 Root"]
|
14 |
+
sorted_paths = sorted(paths)
|
15 |
+
for path in sorted_paths:
|
16 |
+
parts = path.split('/')
|
17 |
+
indent = " " * (len(parts) - 1)
|
18 |
+
tree.append(f"{indent}📄 {parts[-1]}")
|
19 |
+
return "\n".join(tree) + "\n\n"
|
20 |
+
|
21 |
+
def get_all_files(owner, repo, path="", is_hf=False):
|
22 |
+
"""Recursively fetch all files from a repository."""
|
23 |
+
if is_hf:
|
24 |
+
api_url = f"https://huggingface.co/api/spaces/{owner}/{repo}/tree/main/{path}".rstrip('/')
|
25 |
+
else:
|
26 |
+
api_url = f"{GITHUB_API}{owner}/{repo}/contents/{path}".rstrip('/')
|
27 |
+
|
28 |
+
try:
|
29 |
+
response = requests.get(api_url, headers={"Accept": "application/json"}, timeout=10)
|
30 |
+
response.raise_for_status()
|
31 |
+
items = response.json() if response.headers.get('Content-Type', '').startswith('application/json') else None
|
32 |
+
if not items:
|
33 |
+
return None
|
34 |
+
|
35 |
+
files = []
|
36 |
+
for item in items:
|
37 |
+
if item.get('type') == 'file':
|
38 |
+
files.append(item)
|
39 |
+
elif item.get('type') == 'dir':
|
40 |
+
sub_files = get_all_files(owner, repo, item['path'], is_hf)
|
41 |
+
if sub_files:
|
42 |
+
files.extend(sub_files)
|
43 |
+
return files
|
44 |
+
except requests.exceptions.RequestException:
|
45 |
+
return None
|
46 |
+
|
47 |
+
def get_hf_files(owner, repo):
|
48 |
+
"""Fetch all files from a Hugging Face Space."""
|
49 |
+
api = HfApi(token=os.getenv('HF_TOKEN'))
|
50 |
+
try:
|
51 |
+
file_list = api.list_repo_files(repo_id=f'{owner}/{repo}', repo_type="space")
|
52 |
+
processed_files = []
|
53 |
+
for file_path in file_list:
|
54 |
+
raw_url = f"https://huggingface.co/spaces/{owner}/{repo}/raw/main/{file_path}"
|
55 |
+
response = requests.get(raw_url, timeout=10)
|
56 |
+
response.raise_for_status()
|
57 |
+
if not response.headers.get('Content-Type', '').startswith(('text/plain', 'application/octet-stream', 'text/')):
|
58 |
+
continue
|
59 |
+
processed_files.append({"path": file_path})
|
60 |
+
return processed_files
|
61 |
+
except Exception:
|
62 |
+
return []
|
63 |
+
|
64 |
+
def get_repo_contents(url):
|
65 |
+
"""Parse URL and fetch repository contents."""
|
66 |
+
try:
|
67 |
+
if "huggingface.co" in url.lower():
|
68 |
+
parts = url.rstrip('/').split('/')
|
69 |
+
owner, repo = parts[-2], parts[-1]
|
70 |
+
files = get_hf_files(owner, repo)
|
71 |
+
if not files:
|
72 |
+
raise Exception("No files found in the Hugging Face Space")
|
73 |
+
return owner, repo, files, True
|
74 |
+
else:
|
75 |
+
parts = url.rstrip('/').split('/')
|
76 |
+
owner, repo = parts[-2], parts[-1]
|
77 |
+
files = get_all_files(owner, repo, "", False)
|
78 |
+
if files is None:
|
79 |
+
raise Exception("Failed to fetch GitHub repository contents")
|
80 |
+
return owner, repo, files, False
|
81 |
+
except Exception as e:
|
82 |
+
return None, None, f"Error fetching repo contents: {str(e)}", False
|
83 |
+
|
84 |
+
def process_file_content(file_info, owner, repo, is_hf=False):
|
85 |
+
"""Process individual file content from a repository."""
|
86 |
+
content = ""
|
87 |
+
file_path = file_info['path']
|
88 |
+
|
89 |
+
try:
|
90 |
+
if is_hf:
|
91 |
+
file_url = f"https://huggingface.co/spaces/{owner}/{repo}/raw/main/{file_path}"
|
92 |
+
response = requests.get(file_url, timeout=10)
|
93 |
+
response.raise_for_status()
|
94 |
+
content_raw = response.content
|
95 |
+
else:
|
96 |
+
file_url = f"{GITHUB_API}{owner}/{repo}/contents/{file_path}"
|
97 |
+
response = requests.get(file_url, headers={"Accept": "application/json"}, timeout=10)
|
98 |
+
response.raise_for_status()
|
99 |
+
data = response.json()
|
100 |
+
content_raw = base64.b64decode(data['content']) if 'content' in data else b""
|
101 |
+
|
102 |
+
size = len(content_raw)
|
103 |
+
file_extension = file_path.split('.')[-1] if '.' in file_path else ''
|
104 |
+
mime_type, _ = mimetypes.guess_type(file_path)
|
105 |
+
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json'] or "Dockerfile" in file_path
|
106 |
+
|
107 |
+
if is_text:
|
108 |
+
text_content = content_raw.decode('utf-8')
|
109 |
+
if file_extension == 'json':
|
110 |
+
try:
|
111 |
+
json_data = json.loads(text_content)
|
112 |
+
formatted_json = json.dumps(json_data, indent=2)
|
113 |
+
content = f"### File: {file_path}\n```json\n{formatted_json}\n```\n\n"
|
114 |
+
except json.JSONDecodeError:
|
115 |
+
content = f"### File: {file_path}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
|
116 |
+
else:
|
117 |
+
content = f"### File: {file_path}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
|
118 |
+
else:
|
119 |
+
content = f"### File: {file_path}\n[Binary file - {size} bytes]\n\n"
|
120 |
+
except Exception as e:
|
121 |
+
content = f"### File: {file_path}\n[Error fetching file content: {str(e)}]\n\n"
|
122 |
+
|
123 |
+
return content
|
124 |
+
|
125 |
+
def process_uploaded_file(file):
|
126 |
+
"""Process uploaded file content (expects a file-like object with read() method)."""
|
127 |
+
content = ""
|
128 |
+
filename = getattr(file, 'filename', 'unknown')
|
129 |
+
file_extension = filename.split('.')[-1] if '.' in filename else ''
|
130 |
+
|
131 |
+
try:
|
132 |
+
content_raw = file.read()
|
133 |
+
size = len(content_raw)
|
134 |
+
mime_type, _ = mimetypes.guess_type(filename)
|
135 |
+
is_text = (mime_type and mime_type.startswith('text')) or file_extension in ['py', 'md', 'txt', 'js', 'html', 'css', 'json']
|
136 |
+
|
137 |
+
if is_text:
|
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: {filename}\n```json\n{formatted_json}\n```\n\n"
|
144 |
+
except json.JSONDecodeError:
|
145 |
+
content = f"### File: {filename}\n```json\n{text_content}\n```\n[Note: Invalid JSON format]\n\n"
|
146 |
+
else:
|
147 |
+
content = f"### File: {filename}\n```{file_extension or 'text'}\n{text_content}\n```\n\n"
|
148 |
+
else:
|
149 |
+
content = f"### File: {filename}\n[Binary file - {size} bytes]\n\n"
|
150 |
+
except Exception as e:
|
151 |
+
content = f"### File: {filename}\n[Error processing file: {str(e)}]\n\n"
|
152 |
+
|
153 |
+
return content
|
154 |
+
|
155 |
+
def create_markdown_document(url=None, files=None):
|
156 |
+
"""Create markdown document from repo contents or uploaded files."""
|
157 |
+
if url:
|
158 |
+
owner, repo, contents, is_hf = get_repo_contents(url)
|
159 |
+
if isinstance(contents, str): # Error case
|
160 |
+
return f"Error: {contents}"
|
161 |
+
|
162 |
+
markdown_content = f"# {'Space' if is_hf else 'Repository'}: {owner}/{repo}\n\n"
|
163 |
+
markdown_content += "## File Structure\n```\n"
|
164 |
+
markdown_content += generate_file_tree([item['path'] for item in contents])
|
165 |
+
markdown_content += "```\n\n"
|
166 |
+
markdown_content += f"Below are the contents of all files in the {'space' if is_hf else 'repository'}:\n\n"
|
167 |
+
|
168 |
+
for item in contents:
|
169 |
+
markdown_content += process_file_content(item, owner, repo, is_hf)
|
170 |
+
else:
|
171 |
+
markdown_content = "# Uploaded Files\n\n"
|
172 |
+
markdown_content += "## File Structure\n```\n"
|
173 |
+
markdown_content += generate_file_tree([file.filename for file in files])
|
174 |
+
markdown_content += "```\n\n"
|
175 |
+
markdown_content += "Below are the contents of all uploaded files:\n\n"
|
176 |
+
for file in files:
|
177 |
+
markdown_content += process_uploaded_file(file)
|
178 |
+
|
179 |
+
return markdown_content
|