Stability-AI / rest-api-support

Stability REST API examples, issues, and discussions | https://api.stability.ai
108 stars 21 forks source link

Need Java example #31

Open denghuichao opened 1 year ago

denghuichao commented 1 year ago

I try to invoke the stabilty rest api in Java via apache httpclient. Following is my code: `@Override public byte[] generate(String input, Config config) throws Exception { String apiUrl = String.format("%s/v1/generation/%s/image-to-image", Constants.STABILITY_API_HOST, "stable-diffusion-512-v2-1"); CloseableHttpClient httpClient = HttpClientUtils.getHttpClient();

CloseableHttpResponse response = null;
try {
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setCharset(Charset.forName("UTF-8"));
  URL url = new URL(config.getBaseImgUrl());
  builder.addBinaryBody("init_image", IOUtils.toByteArray(url));
  builder.addTextBody("image_strength", "0.35", ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("init_image_mode", "IMAGE_STRENGTH",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("text_prompts[0][text]", config.getPrompt(),  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("cfg_scale", "7",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("clip_guidance_preset", "FAST_BLUE",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("samples", "1",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("steps", "30",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  HttpEntity multipart = builder.build();

  HttpPost post = new HttpPost(apiUrl);
  post.addHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data");
  post.addHeader(HttpHeaders.ACCEPT, "application/json");
  post.addHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", config.getStabilityApiKey()));
  post.setEntity(multipart);
  response = httpClient.execute(post);

  int statusCode = response.getStatusLine().getStatusCode();
  String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

  if (statusCode == 200) {
    Gson gson = new Gson();
    JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
    JsonArray artifactsArray = jsonResponse.getAsJsonArray("artifacts");
    JsonObject artifactObject = artifactsArray.get(0).getAsJsonObject();
    String base64EncodedImage = artifactObject.get("base64").getAsString();
    byte[] imageBytes = Base64.getDecoder().decode(base64EncodedImage);
    return imageBytes;
  } else {
    throw new ContentGenerateException(
        String.format("stability api status code: %s, response: %s", statusCode, responseBody));
  }
} finally {
  if (response != null) {
    try {
      response.close();
    } catch (Exception e) {

    }
  }
}

}`

I think every thing is OK, but it returns me an error: {"id":"b5ad9f42296d3eea01cd2bd3307478fb","message":"can't decode multipart body","name":"bad_request"}

What's going wrong?

LightCannon commented 1 year ago

I have similar issue, My problem is that I use XHRequest (from QML) and it always append "charset=UTF-8" at end of content type. Strangely, stability api does not accept it. I got this since I modified the python code in the doc to append "charset=UTF-8" in the content-type (which is not the default). and it showed same error as in QML.

I find it strange that a big api like this gives error when the charset=UTF-8 is appended into application/json... what a strange thing is this.

LiinNs commented 1 year ago

don't know what to do to solve this message":"No available resolution is available for the input"

LiinNs commented 1 year ago

I try to invoke the stabilty rest api in Java via apache httpclient. Following is my code: `@Override public byte[] generate(String input, Config config) throws Exception { String apiUrl = String.format("%s/v1/generation/%s/image-to-image", Constants.STABILITY_API_HOST, "stable-diffusion-512-v2-1"); CloseableHttpClient httpClient = HttpClientUtils.getHttpClient();

CloseableHttpResponse response = null;
try {
  MultipartEntityBuilder builder = MultipartEntityBuilder.create();
  builder.setCharset(Charset.forName("UTF-8"));
  URL url = new URL(config.getBaseImgUrl());
  builder.addBinaryBody("init_image", IOUtils.toByteArray(url));
  builder.addTextBody("image_strength", "0.35", ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("init_image_mode", "IMAGE_STRENGTH",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("text_prompts[0][text]", config.getPrompt(),  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("cfg_scale", "7",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("clip_guidance_preset", "FAST_BLUE",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("samples", "1",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  builder.addTextBody("steps", "30",  ContentType.create("text/plain", Charset.forName("UTF-8")));
  HttpEntity multipart = builder.build();

  HttpPost post = new HttpPost(apiUrl);
  post.addHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data");
  post.addHeader(HttpHeaders.ACCEPT, "application/json");
  post.addHeader(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", config.getStabilityApiKey()));
  post.setEntity(multipart);
  response = httpClient.execute(post);

  int statusCode = response.getStatusLine().getStatusCode();
  String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

  if (statusCode == 200) {
    Gson gson = new Gson();
    JsonObject jsonResponse = gson.fromJson(responseBody, JsonObject.class);
    JsonArray artifactsArray = jsonResponse.getAsJsonArray("artifacts");
    JsonObject artifactObject = artifactsArray.get(0).getAsJsonObject();
    String base64EncodedImage = artifactObject.get("base64").getAsString();
    byte[] imageBytes = Base64.getDecoder().decode(base64EncodedImage);
    return imageBytes;
  } else {
    throw new ContentGenerateException(
        String.format("stability api status code: %s, response: %s", statusCode, responseBody));
  }
} finally {
  if (response != null) {
    try {
      response.close();
    } catch (Exception e) {

    }
  }
}

}`

I think every thing is OK, but it returns me an error: {"id":"b5ad9f42296d3eea01cd2bd3307478fb","message":"can't decode multipart body","name":"bad_request"}

What's going wrong?

this work for me

File file = new File("/Users/liinns/Desktop/test中.jpeg");
        try {
            BufferedImage originalImage = ImageIO.read(file);

            int width = originalImage.getWidth();
            int height = originalImage.getHeight();

            int newWidth = width + (64 - (width % 64));
            int newHeight = height + (64 - (height % 64));

            BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
            Graphics2D g = resizedImage.createGraphics();
            g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
            g.dispose();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(resizedImage, "jpeg", byteArrayOutputStream);

            byte[] byteArray = byteArrayOutputStream.toByteArray();
            param.setInit_image(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        }
Valerjan4i4ek commented 1 year ago

Did you fix this error? tell me please