Vortttxx / github_api.py
RDS777's picture
Upload 7 files
09842c9 verified
Raw
History Blame Contribute Delete
2.31 kB
#!/usr/bin/env python3
"""
github_api.py — ATYPIK v24.0
Telechargement repo sans git (API GitHub + ZIP).
Compatible HF Spaces.
"""
import os
import json
import zipfile
import urllib.request
import tempfile
from pathlib import Path
from typing import List, Dict, Optional
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "")
def _api_request(url: str) -> dict:
req = urllib.request.Request(url)
req.add_header("Accept", "application/vnd.github+json")
if GITHUB_TOKEN:
req.add_header("Authorization", f"Bearer {GITHUB_TOKEN}")
with urllib.request.urlopen(req, timeout=30) as resp:
return json.loads(resp.read().decode("utf-8"))
def download_repo(repo_url: str, branch: str = "main", dest: Optional[Path] = None) -> Path:
parts = repo_url.rstrip("/").replace(".git", "").split("/")
owner, repo = parts[-2], parts[-1]
zip_url = f"https://github.com/{owner}/{repo}/archive/refs/heads/{branch}.zip"
dest = dest or Path(tempfile.mkdtemp(prefix="repo_"))
zip_path = dest / "repo.zip"
req = urllib.request.Request(zip_url)
req.add_header("User-Agent", "ATYPIK-Agent")
with urllib.request.urlopen(req, timeout=60) as resp:
zip_path.write_bytes(resp.read())
with zipfile.ZipFile(zip_path, 'r') as z:
z.extractall(dest)
extracted = list(dest.glob(f"{repo}-*"))
if extracted:
return extracted[0]
return dest
def get_file_content(repo_url: str, filepath: str, branch: str = "main") -> str:
parts = repo_url.rstrip("/").replace(".git", "").split("/")
owner, repo = parts[-2], parts[-1]
raw_url = f"https://raw.githubusercontent.com/{owner}/{repo}/{branch}/{filepath}"
req = urllib.request.Request(raw_url)
req.add_header("User-Agent", "ATYPIK-Agent")
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read().decode("utf-8")
def list_repo_files(repo_url: str, branch: str = "main") -> List[str]:
parts = repo_url.rstrip("/").replace(".git", "").split("/")
owner, repo = parts[-2], parts[-1]
api_url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/{branch}?recursive=1"
data = _api_request(api_url)
files = []
for item in data.get("tree", []):
if item.get("type") == "blob":
files.append(item["path"])
return files