-
Notifications
You must be signed in to change notification settings - Fork 1.7k
feat: add hugging face text to image integration #1162
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
Open
d-lobo
wants to merge
2
commits into
spring-projects:main
Choose a base branch
from
d-lobo:add-huggingface-text-to-image
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
102 changes: 102 additions & 0 deletions
102
...i-huggingface/src/main/java/org/springframework/ai/huggingface/HuggingfaceImageModel.java
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 |
---|---|---|
@@ -0,0 +1,102 @@ | ||
package org.springframework.ai.huggingface; | ||
|
||
import org.springframework.ai.huggingface.api.ImageGenerationInferenceApi; | ||
import org.springframework.ai.huggingface.text2image.HuggingfaceImageOptions; | ||
import org.springframework.ai.huggingface.invoker.ApiClient; | ||
import org.springframework.ai.huggingface.model.imagegen.GenerateParameters; | ||
import org.springframework.ai.huggingface.model.imagegen.GenerateRequest; | ||
import org.springframework.ai.image.*; | ||
|
||
import java.util.Base64; | ||
import java.util.List; | ||
|
||
/** | ||
* An implementation of {@link ImageModel} that interfaces with HuggingFace Inference | ||
* Endpoints for text-to-image generation. | ||
* | ||
* @author Denis Lobo | ||
*/ | ||
public class HuggingfaceImageModel implements ImageModel { | ||
|
||
private final String APPLICATION_JSON = "application/json"; | ||
|
||
/** | ||
* Token required for authenticating with the HuggingFace Inference API. | ||
*/ | ||
private final String apiToken; | ||
|
||
/** | ||
* Client for making API calls. | ||
*/ | ||
private ApiClient apiClient = new ApiClient(); | ||
|
||
private ImageGenerationInferenceApi imageGenApi = new ImageGenerationInferenceApi(); | ||
|
||
/** | ||
* Constructs a new HuggingfaceImageModel with the specified API token and base path. | ||
* @param apiToken The API token for HuggingFace. | ||
* @param basePath The base path for API requests. | ||
*/ | ||
public HuggingfaceImageModel(final String apiToken, String basePath) { | ||
this.apiToken = apiToken; | ||
this.apiClient.setBasePath(basePath); | ||
this.apiClient.addDefaultHeader("Authorization", "Bearer " + this.apiToken); | ||
this.imageGenApi.setApiClient(this.apiClient); | ||
} | ||
|
||
@Override | ||
public ImageResponse call(ImagePrompt prompt) { | ||
final GenerateParameters generateParameters = createGenerateParameters(prompt.getOptions()); | ||
final GenerateRequest generateRequest = createGenerateRequest(prompt.getInstructions(), generateParameters); | ||
|
||
// hf text-to-image endpoints return only a single image in default mode | ||
final String base64Encoded = generateImage(generateRequest, prompt); | ||
final Image image = new Image(null, base64Encoded); | ||
final ImageGeneration imageGeneration = new ImageGeneration(image); | ||
return new ImageResponse(List.of(imageGeneration), new ImageResponseMetadata()); | ||
} | ||
|
||
private String generateImage(GenerateRequest generateRequest, ImagePrompt prompt) { | ||
final String responseFormat = prompt.getOptions().getResponseFormat(); | ||
final HuggingfaceImageOptions options = (HuggingfaceImageOptions) prompt.getOptions(); | ||
switch (responseFormat) { | ||
case "base64" -> { | ||
return new String(this.imageGenApi.generate(generateRequest, APPLICATION_JSON)); | ||
} | ||
case "bytes" -> { | ||
byte[] bytes = this.imageGenApi.generate(generateRequest, options.getResponseMimeType()); | ||
return Base64.getEncoder().encodeToString(bytes); | ||
} | ||
default -> { | ||
throw new UnsupportedOperationException(String | ||
.format("Unsupported response format: %s, should be 'base64' or 'bytes'", responseFormat)); | ||
} | ||
} | ||
} | ||
|
||
private GenerateRequest createGenerateRequest(List<ImageMessage> promptInstructs, | ||
GenerateParameters generateParameters) { | ||
final GenerateRequest request = new GenerateRequest(); | ||
final List<String> instructions = promptInstructs.stream().map(ImageMessage::getText).toList(); | ||
|
||
request.setParameters(generateParameters); | ||
request.setInputs(instructions); | ||
return request; | ||
} | ||
|
||
private GenerateParameters createGenerateParameters(ImageOptions options) { | ||
final GenerateParameters params = new GenerateParameters(); | ||
params.setWidth(options.getWidth()); | ||
params.setHeight(options.getHeight()); | ||
params.setNumImagesPerPrompt(options.getN()); | ||
|
||
if (options instanceof HuggingfaceImageOptions hfImageOptions) { | ||
params.setClipSkip(hfImageOptions.getClipSkip()); | ||
params.setGuidanceScale(hfImageOptions.getGuidanceScale()); | ||
params.setNumInferenceSteps(hfImageOptions.getNumInferenceSteps()); | ||
params.setNegativePrompt(List.of(hfImageOptions.getNegativePrompt())); | ||
} | ||
return params; | ||
} | ||
|
||
} |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It looks like your code style settings don't align with those of the project. None of these lines should change
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It's not related to code style, I have changed the buildpath in openapi codegen configuration to improve the package structure of generated code. Is this an undesired change ?
However I used the default code styles of my IDE, changed it now to settings mentioned here: https://github.com/spring-projects/spring-framework/wiki/IntelliJ-IDEA-Editor-Settings