dabla commented on code in PR #77089:
URL: https://github.com/apache/airflow/pull/77089#discussion_r4658390115


##########
providers/huggingface/src/airflow/providers/huggingface/hooks/huggingface.py:
##########
@@ -97,12 +106,113 @@ def load_dataset(self, path: str, **kwargs: Any) -> Any:
     def get_dataset_info(self, repo_id: str, revision: str | None = None) -> 
Any:
         return self.get_conn().dataset_info(repo_id, revision=revision)
 
+    async def _aget_token(self) -> str | bool | None:
+        """Async token resolution mirroring get_token without blocking the 
event loop."""
+        if not self.huggingface_conn_id:
+            return None
+        try:
+            connection = await get_async_connection(self.huggingface_conn_id, 
hook=self)
+        except AirflowNotFoundException:
+            if self._allow_ambient_fallback:
+                return None
+            raise
+        return connection.password or False
+
+    @staticmethod
+    async def _aget(client: Any, url: str, *, headers: dict[str, str], 
**kwargs: Any) -> Any:
+        """GET a Hub endpoint on an open client and raise on HTTP errors."""
+        response = await client.get(url, headers=headers, **kwargs)
+        hf_raise_for_status(response)
+        return response
+
+    async def aget_dataset_info(self, repo_id: str, revision: str | None = 
None) -> Any:
+        """Async variant of :meth:`get_dataset_info`; reads the Hub over 
HTTP."""
+        path = f"{constants.ENDPOINT}/api/datasets/{repo_id}"
+        if revision is not None:
+            path = f"{path}/revision/{quote(revision, safe='')}"
+        headers = build_hf_headers(token=await self._aget_token())
+        async with get_async_session() as client:
+            response = await self._aget(client, path, headers=headers)
+        return DatasetInfo(**response.json())
+
+    async def afind_commit_by_marker(
+        self,
+        repo_id: str,
+        marker: str,
+        *,
+        revision: str | None = None,
+        include_pull_requests: bool = False,
+    ) -> Any | None:
+        """Async variant of :meth:`find_commit_by_marker`; scans the latest 
commit per requested ref."""
+        headers = build_hf_headers(token=await self._aget_token())
+        revisions = [revision] if revision else ["main"]
+        async with get_async_session() as client:
+            if include_pull_requests:
+                try:
+                    refs_response = await self._aget(
+                        client,
+                        f"{constants.ENDPOINT}/api/datasets/{repo_id}/refs",
+                        headers=headers,
+                        params={"include_prs": "1"},
+                    )
+                except RepositoryNotFoundError:
+                    return None
+                refs = refs_response.json()
+                revisions.extend(item["ref"] for item in 
refs.get("pullRequests", []) or [])
+
+            seen: set[str] = set()
+            for ref in revisions:
+                if ref in seen:
+                    continue
+                seen.add(ref)
+                try:
+                    commits_response = await self._aget(
+                        client,
+                        
f"{constants.ENDPOINT}/api/datasets/{repo_id}/commits/{quote(ref, safe='')}",
+                        headers=headers,
+                    )
+                except RepositoryNotFoundError:
+                    return None
+                except RevisionNotFoundError:
+                    continue
+                items = commits_response.json()
+                if not items:
+                    continue
+                item = items[0]  # Hub returns commits newest first.
+                commit = GitCommitInfo(
+                    commit_id=item["id"],
+                    authors=[author["user"] for author in item["authors"]],
+                    created_at=parse_datetime(item["date"]),
+                    title=item["title"],
+                    message=item["message"],
+                    formatted_title=None,
+                    formatted_message=None,
+                )
+                if self._marker_matches(commit, marker):
+                    return commit
+        return None
+
     @staticmethod
     def _commit_is_complete(commit: Any) -> bool:
         """Reject intermediate commits from a Hub upload split into parts."""
         title = getattr(commit, "title", "") or ""
         return re.search(r"\(part\b.*\)\s*$", title, re.IGNORECASE) is None
 
+    @staticmethod
+    def _marker_matches(commit: Any, marker: str) -> bool:
+        """Whether the commit carries the marker and has completed in full."""
+        # GitCommitInfo carries title/message/commit_id; CommitInfo carries
+        # commit_message/commit_description/oid.
+        fields = (
+            getattr(commit, "title", ""),
+            getattr(commit, "message", ""),
+            getattr(commit, "commit_message", ""),
+            getattr(commit, "commit_description", ""),
+        )
+        if not any(marker in (field or "") for field in fields):
+            return False
+        return HuggingFaceHook._commit_is_complete(commit)

Review Comment:
   **[nit]** `_marker_matches` hard-codes 
`HuggingFaceHook._commit_is_complete`, where the code it replaces called 
`self._commit_is_complete`.
   
   A subclass that overrides `_commit_is_complete` was honoured by 
`find_commit_by_marker` before this change and is silently bypassed now. Making 
the helper a `@classmethod` that calls `cls._commit_is_complete(commit)` keeps 
the old dispatch; both call sites already go through `self._marker_matches`.



##########
providers/huggingface/tests/unit/huggingface/hooks/test_huggingface.py:
##########
@@ -172,3 +192,201 @@ def 
test_find_commit_by_marker_scans_pull_request_refs_when_requested():
     api.list_repo_refs.assert_called_once_with("org/data", 
repo_type="dataset", include_pull_requests=True)
     assert api.list_repo_commits.call_args_list[0].kwargs["revision"] == "main"
     assert api.list_repo_commits.call_args_list[1].kwargs["revision"] == 
"refs/pr/7"
+
+
[email protected]
+async def test_aget_dataset_info_builds_url_and_returns_info(connection_env, 
mocker):
+    calls = []
+
+    async def fake_get(client, url, *, headers, **kwargs):
+        calls.append((url, headers))
+        return SimpleNamespace(json=lambda: {"id": "org/data", "private": 
False})
+
+    mocker.patch.object(HuggingFaceHook, "_aget", side_effect=fake_get)

Review Comment:
   **[nit]** A way to close the test gap @kaxil raised, without the network.
   
   Mocking one level lower than `_aget` runs the request code, 
`hf_raise_for_status`, the `Authorization` header and `params={"include_prs": 
"1"}`: patch `get_async_session` to return an `AsyncClient` with a 
`MockTransport` whose handler answers what the Hub really sends (probed on the 
public API):
   
   | Request | Real Hub answer |
   |---|---|
   | `GET /api/datasets/{repo}/commits/{missing-rev}` | `404`, `X-Error-Code: 
RevisionNotFound` |
   | `GET /api/datasets/{missing-repo}/commits/main` or `/refs` | `401`, no 
`X-Error-Code` |
   | `GET /api/datasets/{repo}/refs?include_prs=1` | `{"pullRequests": 
[{"name", "ref", "targetCommit"}], ...}` |
   
   The handler can then assert the URL, the query string and the token header. 
One caveat: huggingface-hub 1.x is built on `httpx` and 2.x on `httpx2`, so the 
client and transport must come from the library the installed hub uses, 
otherwise `hf_raise_for_status` does not catch the status error.



##########
providers/huggingface/pyproject.toml:
##########
@@ -64,7 +64,7 @@ dependencies = [
   # constraints-3.0.6 pins dill==0.3.1.1, so without these floors uv falls 
back to the
   # source-only multiprocess==0.70.9, whose build hangs. multiprocess 0.70.16 
needs dill>=0.3.8.
   "dill>=0.3.8",
-  "huggingface-hub>=0.24",
+  "huggingface-hub>=1.0.0",

Review Comment:
   **[warning]** The `huggingface-hub>=1.0.0` floor makes the provider 
uninstallable next to `transformers` 4.x.
   
   `transformers` 4.57.1 requires 
[`huggingface-hub<1.0,>=0.34.0`](https://pypi.org/pypi/transformers/4.57.1/json),
 and `datasets` 5.0.0 itself still accepts 
[`huggingface-hub>=0.25.0`](https://pypi.org/pypi/datasets/5.0.0/json). With 
this floor, anyone who has the provider in the same environment as transformers 
4.x loses the whole provider, sync methods included, for the sake of two 
optional async methods.
   
   The import can stay off the module path instead, so the sync hook keeps 
working on a 0.x hub and only the async methods need 1.x:
   
   ```python
   async def aget_dataset_info(...):
       from huggingface_hub.utils import get_async_session  # 
huggingface-hub>=1.0 only
   ```
   
   with a clear error when it is missing. If the maintainers prefer the bump, 
it is a breaking change for those users and deserves a note under the 
"Changelog" header in `docs/changelog.rst`.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to