|
| 1 | +import datetime |
| 2 | +import re |
| 3 | + |
| 4 | +import requests |
| 5 | +import trafilatura |
| 6 | +from huggingface_hub import HfApi |
| 7 | + |
| 8 | +__all__ = ["HuggingFace"] |
| 9 | + |
| 10 | + |
| 11 | +class HuggingFace: |
| 12 | + """HuggingFace liked models, datasets, and spaces. |
| 13 | +
|
| 14 | + Parameters |
| 15 | + ---------- |
| 16 | + token : str, optional |
| 17 | + HuggingFace User Access Token. If not provided, it relies on |
| 18 | + local authentication (huggingface-cli login). |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, token: str = None): |
| 22 | + self.token = token |
| 23 | + self.api = HfApi(token=self.token) |
| 24 | + |
| 25 | + def __call__(self): |
| 26 | + """Get liked content on HuggingFace.""" |
| 27 | + data = {} |
| 28 | + |
| 29 | + try: |
| 30 | + likes = self.api.list_liked_repos() |
| 31 | + except Exception as e: |
| 32 | + print(f"Error fetching likes: {e}") |
| 33 | + return data |
| 34 | + |
| 35 | + # Process Models |
| 36 | + if hasattr(likes, "models"): |
| 37 | + for model in likes.models: |
| 38 | + repo_id = model.repo_id if hasattr(model, "repo_id") else str(model) |
| 39 | + url = f"https://huggingface.co/{repo_id}" |
| 40 | + |
| 41 | + # Fetch raw README for summary |
| 42 | + raw_url = f"https://huggingface.co/{repo_id}/resolve/main/README.md" |
| 43 | + self._process_entry(data, url, raw_url, repo_id, "model") |
| 44 | + |
| 45 | + # Process Datasets |
| 46 | + if hasattr(likes, "datasets"): |
| 47 | + for dataset in likes.datasets: |
| 48 | + repo_id = ( |
| 49 | + dataset.repo_id if hasattr(dataset, "repo_id") else str(dataset) |
| 50 | + ) |
| 51 | + dataset_url = f"https://huggingface.co/datasets/{repo_id}" |
| 52 | + |
| 53 | + # specific logic to find branch for datasets |
| 54 | + branch = self._get_default_branch(repo_id, "dataset") |
| 55 | + raw_url = f"https://huggingface.co/datasets/{repo_id}/resolve/{branch}/README.md" |
| 56 | + |
| 57 | + self._process_entry(data, dataset_url, raw_url, repo_id, "dataset") |
| 58 | + |
| 59 | + # Process Spaces |
| 60 | + if hasattr(likes, "spaces"): |
| 61 | + for space in likes.spaces: |
| 62 | + repo_id = space.repo_id if hasattr(space, "repo_id") else str(space) |
| 63 | + url = f"https://huggingface.co/spaces/{repo_id}" |
| 64 | + |
| 65 | + # specific logic to find branch for spaces |
| 66 | + branch = self._get_default_branch(repo_id, "space") |
| 67 | + raw_url = f"https://huggingface.co/spaces/{repo_id}/resolve/{branch}/README.md" |
| 68 | + |
| 69 | + self._process_entry(data, url, raw_url, repo_id, "space") |
| 70 | + |
| 71 | + return data |
| 72 | + |
| 73 | + def _get_default_branch(self, repo_id, repo_type): |
| 74 | + """Helper to safely get default branch.""" |
| 75 | + try: |
| 76 | + repo_info = self.api.repo_info(repo_id=repo_id, repo_type=repo_type) |
| 77 | + return repo_info.default_branch if repo_info.default_branch else "main" |
| 78 | + except Exception: |
| 79 | + return "main" |
| 80 | + |
| 81 | + def _process_entry(self, data, data_url, summarization_url, title_suffix, tag_type): |
| 82 | + """Helper to fetch summary and populate data dict.""" |
| 83 | + print(f"Processing {tag_type}: {title_suffix}") |
| 84 | + summary = self.get_summary(summarization_url) |
| 85 | + |
| 86 | + data[data_url] = { |
| 87 | + "title": f"🤗 HuggingFace {title_suffix}", |
| 88 | + "tags": ["huggingface", tag_type], |
| 89 | + "summary": summary, |
| 90 | + "date": datetime.datetime.today().strftime("%Y-%m-%d"), |
| 91 | + } |
| 92 | + |
| 93 | + @staticmethod |
| 94 | + def get_summary(url, num_tokens=50): |
| 95 | + """ |
| 96 | + Fetches the content from a URL. |
| 97 | + If it's a raw Markdown file with YAML frontmatter, it strips the metadata. |
| 98 | + Otherwise, it attempts to extract text using trafilatura. |
| 99 | + """ |
| 100 | + try: |
| 101 | + headers = { |
| 102 | + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" |
| 103 | + } |
| 104 | + response = requests.get(url, headers=headers, timeout=15) |
| 105 | + response.raise_for_status() |
| 106 | + content = response.text |
| 107 | + |
| 108 | + # Check for YAML frontmatter (starts with ---) |
| 109 | + if content.strip().startswith("---"): |
| 110 | + # Regex to remove the first block enclosed in --- |
| 111 | + # DOTALL allows . to match newlines |
| 112 | + cleaned_text = re.sub( |
| 113 | + r"^---\n.*?\n---", "", content, count=1, flags=re.DOTALL |
| 114 | + ) |
| 115 | + |
| 116 | + # Since it is markdown, we might want to strip common markdown syntax |
| 117 | + # for a cleaner summary (optional, but makes it readable) |
| 118 | + cleaned_text = re.sub(r"[#*`]", "", cleaned_text) |
| 119 | + cleaned_text = re.sub(r"\s+", " ", cleaned_text).strip() |
| 120 | + |
| 121 | + else: |
| 122 | + # Fallback to trafilatura for non-markdown/HTML content |
| 123 | + core_text = trafilatura.extract(content) |
| 124 | + if not core_text: |
| 125 | + # If trafilatura fails (e.g. on raw text), use raw content |
| 126 | + cleaned_text = re.sub(r"\s+", " ", content).strip() |
| 127 | + else: |
| 128 | + cleaned_text = re.sub(r"\s+", " ", core_text).strip() |
| 129 | + |
| 130 | + tokens = cleaned_text.split() |
| 131 | + first_n_tokens = tokens[:num_tokens] |
| 132 | + |
| 133 | + return " ".join(first_n_tokens) |
| 134 | + |
| 135 | + except requests.exceptions.RequestException as e: |
| 136 | + print(f"Could not fetch {url}: {e}") |
| 137 | + return "" |
| 138 | + except Exception as e: |
| 139 | + print(f"An error occurred while processing {url}: {e}") |
| 140 | + return "" |
0 commit comments