0

For some reason sometimes the code works, sometimes it does not

here is a small video:: https://www.youtube.com/watch?v=neCKWHT-nHg&feature=youtu.be

Im not sure if I am not able to access the image or the image is not being stored properly...

this is the code to fetch from stablediffusion::

import 'dart:convert';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:http/http.dart' as http;

class StableDiffusionApi {
  final _url = Uri.parse('https://stablediffusionapi.com/api/v3/text2img');

  Future getAIImage(String prompt) async {
    // Make the HTTP POST request to the Stability Platform API

    try {
      final response = await http.post(
        _url,
        headers: {"Content-Type": "application\/json"},
        body: jsonEncode({
          "key": "XXXX",
          "prompt": prompt,
          "negative_prompt":
              "((out of frame)), ((extra fingers)), mutated hands, ((poorly drawn hands)), ((poorly drawn face)), (((mutation))), (((deformed))), (((tiling))), ((naked)), ((tile)), ((fleshpile)), ((ugly)), (((abstract))), blurry, ((bad anatomy)), ((bad proportions)), ((extra limbs)), cloned face, (((skinny))), glitchy, ((extra breasts)), ((double torso)), ((extra arms)), ((extra hands)), ((mangled fingers)), ((missing breasts)), (missing lips), ((ugly face)), ((fat)), ((extra legs)), anime",
          "width": "512",
          "height": "512",
          "samples": "1",
          "num_inference_steps": "20",
          "seed": null,
          "guidance_scale": 7.5,
          "safety_checker": "yes",
          "webhook": null,
          "track_id": null
        }),
      );
      var data = jsonDecode(response.body);
      // print('returinng data ${data}');
      return {"error": null, "data": data};

      // Handle the response here
    } catch (e) {
      // Handle the error here
      print('ERROR::  ${e.toString()}');
      return {"data": null, "error": e.toString()};
    }
  }
}

this is the class that uploads the image to firebase::

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../../constants/all_tables.dart';
import '../../constants/diary.dart';
import '../../models/cloud/diary.dart';
import 'package:firebase_storage/firebase_storage.dart';

import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;

import 'auth.dart';

class StorageFirebaseCloudStorage {
  final _user = AuthHandler.getUser();

  Future uploadImageFromUrl(String imageUrl, String folderName) async {
    // imageUrl =
    //     "https://pub-8b49af329fae499aa563997f5d4068a4.r2.dev/generations/e885ed42-97f6-4427-acb6-763020d07dfe-0.png";

    print("imageUrl:   ${imageUrl}");
    try {
      final imageResponse = await http.get(Uri.parse(imageUrl));
      final imageBytes = imageResponse.bodyBytes;
      final fileName =
          "${_user.uid}_${Timestamp.now().millisecondsSinceEpoch}.jpg";

      // Upload the image to Firebase Storage
      final storageRef =
          FirebaseStorage.instance.ref().child(folderName).child(fileName);
      final uploadTask = storageRef.putData(imageBytes);
      await uploadTask.whenComplete(() => null);

      // Get the URL of the uploaded image and return it
      final imageUrlInStorage = await storageRef.getDownloadURL();
      return imageUrlInStorage;
    } catch (e) {
      print('ERROR');
      print('Error uploading image:\n ${e.toString()}');
      return null;
    }
  }

  Future<void> deleteFile(String fileUrl) async {
    try {
      final storage = FirebaseStorage.instance;
      final ref = storage.refFromURL(fileUrl);
      await ref.delete();
      print('File deleted successfully');
    } catch (e) {
      print('Error deleting file: $e');
    }
  }

// singleton
  static final StorageFirebaseCloudStorage _shared =
      StorageFirebaseCloudStorage._sharedInstance();
  StorageFirebaseCloudStorage._sharedInstance();
  factory StorageFirebaseCloudStorage() => _shared;
}

this is to work perfect but now i get an error::


════════ Exception caught by image resource service ════════════════════════════
The following _Exception was thrown resolving an image codec:
Exception: Invalid image data

When the exception was thrown, this was the stack
#0      _futurize (dart:ui/painting.dart:6408:5)
#1      ImageDescriptor.encoded (dart:ui/painting.dart:6265:12)
#2      instantiateImageCodecFromBuffer (dart:ui/painting.dart:2150:60)
#3      PaintingBinding.instantiateImageCodecFromBuffer
binding.dart:153
#4      NetworkImage._loadAsync
_network_image_io.dart:135
<asynchronous suspension>

what is the issue?

Juan Casas
  • 268
  • 2
  • 13
  • 1
    I would look at that image you are trying to upload. Maybe it is not even an image, but some error text. – sfphoton May 15 '23 at 12:36

1 Answers1

0

You should be able to use the Network tab in Flutter DevTools. This will reveal the Stable Diffusion image request and response, as well as the Firebase image request and response.

You'll probably find that the response from the SD API is not an image, or is a rate limiting response for example, and then the FB API will respond with that resource (or 404 if not found), which won't be able to be decoded if it isn't a valid image.

JaffaKetchup
  • 1,151
  • 10
  • 26