Anurag-S1ngh commented on code in PR #77089:
URL: https://github.com/apache/airflow/pull/77089#discussion_r4671144366


##########
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:
   `_marker_matches` is a classmethod now and dispatches through 
`cls._commit_is_complete`. Added a test with a subclass override.



##########
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:
   Reverted the floor to 0.24 and made `get_async_session` an optional import. 
The sync hook works on 0.x, and the async methods raise a clear error until 1.0 
is installed. No changelog entry needed now, since there is no dependency 
change.



##########
providers/huggingface/src/airflow/providers/huggingface/hooks/huggingface.py:
##########
@@ -20,11 +20,20 @@
 
 import re
 from typing import Any
+from urllib.parse import quote
 
-from huggingface_hub import HfApi
-from huggingface_hub.utils import RepositoryNotFoundError, 
RevisionNotFoundError
+from huggingface_hub import DatasetInfo, GitCommitInfo, HfApi, constants
+from huggingface_hub.utils import (
+    RepositoryNotFoundError,
+    RevisionNotFoundError,
+    build_hf_headers,
+    get_async_session,

Review Comment:
   Kept the floor at 0.24 and guarded the import instead. `get_async_session` 
is optional at import time, so the sync hook still works on 0.x, and the async 
methods raise `AirflowOptionalProviderFeatureException` with the version 
requirement. `DatasetInfo` now imports from `hf_api`, which 0.24 also has. The 
reason for avoiding the floor bump is in the pyproject thread.



##########
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:
   Added HTTP-level tests that patch `get_async_session` with a `MockTransport` 
client, so the request code, token header, `include_prs` and the Hub error 
mapping run for real. The client and transport come from the httpx module the 
installed hub uses, so they match 1.x and 2.x. This also covers the point about 
every async test patching `_aget`.



-- 
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