-
Notifications
You must be signed in to change notification settings - Fork 822
[Inference Providers] add image-to-image
support for fal.ai provider
#3187
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
d60b0e9
add image-to-image support for fal-ai
hanouticelina b2202c7
add tests
hanouticelina 3a06297
fix
hanouticelina 3ad15ac
Merge branch 'main' of github.com:huggingface/huggingface_hub into su…
hanouticelina 8379532
use helper
hanouticelina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,8 @@ | ||
import base64 | ||
import time | ||
from abc import ABC | ||
from typing import Any, Dict, Optional, Union | ||
from pathlib import Path | ||
from typing import Any, BinaryIO, Dict, Optional, Union | ||
from urllib.parse import urlparse | ||
|
||
from huggingface_hub import constants | ||
|
@@ -32,6 +33,60 @@ def _prepare_route(self, mapped_model: str, api_key: str) -> str: | |
return f"/{mapped_model}" | ||
|
||
|
||
class FalAIQueueTask(TaskProviderHelper, ABC): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nice :) |
||
def __init__(self, task: str): | ||
super().__init__(provider="fal-ai", base_url="https://queue.fal.run", task=task) | ||
|
||
def _prepare_headers(self, headers: Dict, api_key: str) -> Dict: | ||
headers = super()._prepare_headers(headers, api_key) | ||
if not api_key.startswith("hf_"): | ||
headers["authorization"] = f"Key {api_key}" | ||
return headers | ||
|
||
def _prepare_route(self, mapped_model: str, api_key: str) -> str: | ||
if api_key.startswith("hf_"): | ||
# Use the queue subdomain for HF routing | ||
return f"/{mapped_model}?_subdomain=queue" | ||
return f"/{mapped_model}" | ||
|
||
def get_response( | ||
self, | ||
response: Union[bytes, Dict], | ||
request_params: Optional[RequestParameters] = None, | ||
) -> Any: | ||
response_dict = _as_dict(response) | ||
|
||
request_id = response_dict.get("request_id") | ||
if not request_id: | ||
raise ValueError("No request ID found in the response") | ||
if request_params is None: | ||
raise ValueError( | ||
f"A `RequestParameters` object should be provided to get {self.task} responses with Fal AI." | ||
) | ||
|
||
# extract the base url and query params | ||
parsed_url = urlparse(request_params.url) | ||
# a bit hacky way to concatenate the provider name without parsing `parsed_url.path` | ||
base_url = f"{parsed_url.scheme}://{parsed_url.netloc}{'/fal-ai' if parsed_url.netloc == 'router.huggingface.co' else ''}" | ||
query_param = f"?{parsed_url.query}" if parsed_url.query else "" | ||
|
||
# extracting the provider model id for status and result urls | ||
# from the response as it might be different from the mapped model in `request_params.url` | ||
model_id = urlparse(response_dict.get("response_url")).path | ||
status_url = f"{base_url}{str(model_id)}/status{query_param}" | ||
result_url = f"{base_url}{str(model_id)}{query_param}" | ||
|
||
status = response_dict.get("status") | ||
logger.info("Generating the output.. this can take several minutes.") | ||
while status != "COMPLETED": | ||
time.sleep(_POLLING_INTERVAL) | ||
status_response = get_session().get(status_url, headers=request_params.headers) | ||
hf_raise_for_status(status_response) | ||
status = status_response.json().get("status") | ||
|
||
return get_session().get(result_url, headers=request_params.headers).json() | ||
|
||
|
||
class FalAIAutomaticSpeechRecognitionTask(FalAITask): | ||
def __init__(self): | ||
super().__init__("automatic-speech-recognition") | ||
|
@@ -110,23 +165,10 @@ def get_response(self, response: Union[bytes, Dict], request_params: Optional[Re | |
return get_session().get(url).content | ||
|
||
|
||
class FalAITextToVideoTask(FalAITask): | ||
class FalAITextToVideoTask(FalAIQueueTask): | ||
def __init__(self): | ||
super().__init__("text-to-video") | ||
|
||
def _prepare_base_url(self, api_key: str) -> str: | ||
if api_key.startswith("hf_"): | ||
return super()._prepare_base_url(api_key) | ||
else: | ||
logger.info(f"Calling '{self.provider}' provider directly.") | ||
return "https://queue.fal.run" | ||
|
||
def _prepare_route(self, mapped_model: str, api_key: str) -> str: | ||
if api_key.startswith("hf_"): | ||
# Use the queue subdomain for HF routing | ||
return f"/{mapped_model}?_subdomain=queue" | ||
return f"/{mapped_model}" | ||
|
||
def _prepare_payload_as_dict( | ||
self, inputs: Any, parameters: Dict, provider_mapping_info: InferenceProviderMapping | ||
) -> Optional[Dict]: | ||
|
@@ -137,36 +179,54 @@ def get_response( | |
response: Union[bytes, Dict], | ||
request_params: Optional[RequestParameters] = None, | ||
) -> Any: | ||
response_dict = _as_dict(response) | ||
output = super().get_response(response, request_params) | ||
url = _as_dict(output)["video"]["url"] | ||
return get_session().get(url).content | ||
|
||
request_id = response_dict.get("request_id") | ||
if not request_id: | ||
raise ValueError("No request ID found in the response") | ||
if request_params is None: | ||
raise ValueError( | ||
"A `RequestParameters` object should be provided to get text-to-video responses with Fal AI." | ||
) | ||
|
||
# extract the base url and query params | ||
parsed_url = urlparse(request_params.url) | ||
# a bit hacky way to concatenate the provider name without parsing `parsed_url.path` | ||
base_url = f"{parsed_url.scheme}://{parsed_url.netloc}{'/fal-ai' if parsed_url.netloc == 'router.huggingface.co' else ''}" | ||
query_param = f"?{parsed_url.query}" if parsed_url.query else "" | ||
class FalAIImageToImageTask(FalAIQueueTask): | ||
def __init__(self): | ||
super().__init__("image-to-image") | ||
|
||
# extracting the provider model id for status and result urls | ||
# from the response as it might be different from the mapped model in `request_params.url` | ||
model_id = urlparse(response_dict.get("response_url")).path | ||
status_url = f"{base_url}{str(model_id)}/status{query_param}" | ||
result_url = f"{base_url}{str(model_id)}{query_param}" | ||
def _prepare_payload_as_dict( | ||
self, inputs: Any, parameters: Dict, provider_mapping_info: InferenceProviderMapping | ||
) -> Optional[Dict]: | ||
if isinstance(inputs, str) and inputs.startswith(("http://", "https://")): | ||
image_url = inputs | ||
else: | ||
image_bytes: bytes | ||
if isinstance(inputs, (str, Path)): | ||
with open(inputs, "rb") as f: | ||
image_bytes = f.read() | ||
elif isinstance(inputs, bytes): | ||
image_bytes = inputs | ||
elif isinstance(inputs, BinaryIO): | ||
image_bytes = inputs.read() | ||
else: | ||
raise TypeError(f"Unsupported input type for image: {type(inputs)}") | ||
hanouticelina marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
image_b64 = base64.b64encode(image_bytes).decode() | ||
content_type = "image/png" | ||
hanouticelina marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
image_url = f"data:{content_type};base64,{image_b64}" | ||
payload: Dict[str, Any] = { | ||
"image_url": image_url, | ||
**filter_none(parameters), | ||
} | ||
if provider_mapping_info.adapter_weights_path is not None: | ||
lora_path = constants.HUGGINGFACE_CO_URL_TEMPLATE.format( | ||
repo_id=provider_mapping_info.hf_model_id, | ||
revision="main", | ||
filename=provider_mapping_info.adapter_weights_path, | ||
) | ||
payload["loras"] = [{"path": lora_path, "scale": 1}] | ||
hanouticelina marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
status = response_dict.get("status") | ||
logger.info("Generating the video.. this can take several minutes.") | ||
while status != "COMPLETED": | ||
time.sleep(_POLLING_INTERVAL) | ||
status_response = get_session().get(status_url, headers=request_params.headers) | ||
hf_raise_for_status(status_response) | ||
status = status_response.json().get("status") | ||
return payload | ||
|
||
response = get_session().get(result_url, headers=request_params.headers).json() | ||
url = _as_dict(response)["video"]["url"] | ||
def get_response( | ||
self, | ||
response: Union[bytes, Dict], | ||
request_params: Optional[RequestParameters] = None, | ||
) -> Any: | ||
output = super().get_response(response, request_params) | ||
url = _as_dict(output)["images"][0]["url"] | ||
return get_session().get(url).content |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.