File size: 8,175 Bytes
d79890b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import base64
import json
import zipfile
import io
import os
from typing import List, Dict, Tuple, Optional
from pathlib import Path
import re

from utils import matches_patterns, is_binary_file, format_file_size
from config import GITHUB_API_BASE, HF_API_BASE

def process_github_repo(
    repo_path: str,
    token: str,
    include_patterns: List[str],
    exclude_patterns: List[str],
    max_file_size: int
) -> Tuple[List[Tuple[str, str, int]], Dict]:
    """Process GitHub repository and return file contents"""
    
    headers = {}
    if token:
        headers['Authorization'] = f'token {token}'
    
    # Get repository info
    repo_url = f"{GITHUB_API_BASE}/repos/{repo_path}"
    repo_response = requests.get(repo_url, headers=headers)
    
    if repo_response.status_code != 200:
        raise Exception(f"Failed to fetch repository info: {repo_response.json().get('message', 'Unknown error')}")
    
    repo_info = repo_response.json()
    
    # Get all files recursively
    files_data = []
    contents_queue = [""]
    
    while contents_queue:
        current_path = contents_queue.pop(0)
        
        # Get directory contents
        contents_url = f"{GITHUB_API_BASE}/repos/{repo_path}/contents/{current_path}"
        contents_response = requests.get(contents_url, headers=headers)
        
        if contents_response.status_code != 200:
            continue
        
        contents = contents_response.json()
        
        if isinstance(contents, dict):
            # Single file
            contents = [contents]
        
        for item in contents:
            item_path = f"{current_path}/{item['name']}" if current_path else item['name']
            
            if item['type'] == 'dir':
                contents_queue.append(item_path)
            elif item['type'] == 'file':
                # Check if file matches patterns
                if not matches_patterns(item_path, include_patterns, exclude_patterns):
                    continue
                
                # Check file size
                if item['size'] > max_file_size:
                    continue
                
                # Get file content
                try:
                    file_url = item['url']
                    file_response = requests.get(file_url, headers=headers)
                    
                    if file_response.status_code == 200:
                        file_data = file_response.json()
                        content = base64.b64decode(file_data['content']).decode('utf-8', errors='ignore')
                        
                        # Skip binary files
                        if is_binary_file(content, item_path):
                            continue
                        
                        files_data.append((item_path, content, item['size']))
                        
                except Exception as e:
                    print(f"Error processing file {item_path}: {e}")
                    continue
    
    return files_data, repo_info

def process_huggingface_repo(
    repo_path: str,
    token: str,
    include_patterns: List[str],
    exclude_patterns: List[str],
    max_file_size: int
) -> Tuple[List[Tuple[str, str, int]], Dict]:
    """Process Hugging Face repository and return file contents"""
    
    headers = {}
    if token:
        headers['Authorization'] = f'Bearer {token}'
    
    # Get repository info
    repo_url = f"{HF_API_BASE}/api/models/{repo_path}"
    repo_response = requests.get(repo_url, headers=headers)
    
    if repo_response.status_code != 200:
        raise Exception(f"Failed to fetch repository info: {repo_response.json().get('error', 'Unknown error')}")
    
    repo_info = repo_response.json()
    
    # Get repository tree
    tree_url = f"{HF_API_BASE}/api/models/{repo_path}/tree/main"
    tree_response = requests.get(tree_url, headers=headers)
    
    if tree_response.status_code != 200:
        raise Exception(f"Failed to fetch repository tree: {tree_response.json().get('error', 'Unknown error')}")
    
    tree_data = tree_response.json()
    
    files_data = []
    
    def process_tree_item(item, current_path=""):
        if isinstance(item, list):
            for subitem in item:
                process_tree_item(subitem, current_path)
        elif isinstance(item, dict):
            item_path = f"{current_path}/{item['path']}" if current_path else item['path']
            
            if item['type'] == 'directory':
                # Get directory contents
                dir_url = f"{HF_API_BASE}/api/models/{repo_path}/tree/main/{item_path}"
                dir_response = requests.get(dir_url, headers=headers)
                
                if dir_response.status_code == 200:
                    process_tree_item(dir_response.json(), item_path)
            elif item['type'] == 'file':
                # Check if file matches patterns
                if not matches_patterns(item_path, include_patterns, exclude_patterns):
                    return
                
                # Check file size
                if item.get('size', 0) > max_file_size:
                    return
                
                # Get file content
                try:
                    raw_url = f"https://huggingface.co/{repo_path}/raw/main/{item_path}"
                    file_response = requests.get(raw_url, headers=headers)
                    
                    if file_response.status_code == 200:
                        content = file_response.text
                        
                        # Skip binary files
                        if is_binary_file(content, item_path):
                            return
                        
                        files_data.append((item_path, content, len(content)))
                        
                except Exception as e:
                    print(f"Error processing file {item_path}: {e}")
                    return
    
    process_tree_item(tree_data)
    
    return files_data, repo_info

def download_repo_as_zip(repo_url: str, token: str) -> str:
    """Download repository as ZIP file"""
    
    if "github.com" in repo_url:
        # GitHub ZIP URL
        if token:
            headers = {'Authorization': f'token {token}'}
            zip_url = repo_url.replace("github.com", "api.github.com/repos") + "/zipball/main"
        else:
            headers = {}
            zip_url = repo_url.replace("github.com", "codeload.github.com") + "/zip/main"
    elif "huggingface.co" in repo_url:
        # Hugging Face ZIP URL
        headers = {}
        if token:
            headers['Authorization'] = f'Bearer {token}'
        zip_url = repo_url.replace("huggingface.co", "huggingface.co") + "/resolve/main?download=true"
    else:
        raise ValueError("Unsupported repository URL")
    
    response = requests.get(zip_url, headers=headers, stream=True)
    
    if response.status_code != 200:
        raise Exception(f"Failed to download repository: {response.status_code}")
    
    # Save to temporary file
    temp_path = f"/tmp/repo_{hash(repo_url)}.zip"
    
    with open(temp_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=8192):
            f.write(chunk)
    
    return temp_path

def extract_repo_info(repo_url: str, repo_type: str) -> Dict:
    """Extract basic repository information"""
    if repo_type == "github":
        # Extract owner and repo name
        match = re.search(r'github\.com/([^/]+)/([^/]+)', repo_url)
        if match:
            return {
                'owner': match.group(1),
                'repo': match.group(2),
                'full_name': f"{match.group(1)}/{match.group(2)}",
                'url': repo_url
            }
    elif repo_type == "huggingface":
        # Extract owner and repo name
        match = re.search(r'huggingface\.co/([^/]+)/([^/]+)', repo_url)
        if match:
            return {
                'owner': match.group(1),
                'repo': match.group(2),
                'full_name': f"{match.group(1)}/{match.group(2)}",
                'url': repo_url
            }
    
    return {'url': repo_url}