KeyError in Django when using Huggingface API

17 Views Asked by At

I use Django and I want to use Huggingface API with it. The API sometimes return error to me saying:

#  KeyError at /GenerativeImage2Text

0  
                34. if "generated_text" in output[0]:
                                            ^^^^^^^^

This is my view.py

def GIT(request):
    output = None
    generated_text = None
    form = ImageForm()  

    if request.method == 'POST':
        form = ImageForm(request.POST, request.FILES)

        if form.is_valid():
            form.save()

            image_name = str(form.cleaned_data['Image'])
            imgloc = os.path.join(
                'media', 'images', image_name)
            while True:
                output = query(imgloc)
                if "generated_text" in output[0]:
                    generated_text = output[0].get('generated_text')
                    break
                else:
                    print(output[0])

        else:
            print("This image is invalid")

    return render(request, "imagecaptioning.html", {"form": form, "output": generated_text})
  • I want to fix this problem and make sure that API always return no error such that.

  • is the problem in my code or with the API?

0

There are 0 best solutions below