Hello! I am interested in setting up a Gradio webui to run this vision AI model, here is the readme.md file which explains a bit about the model with a code example:
pipeline_tag: visual-question-answering
MiniCPM-Llama3-V 2.5 int4
This is the int4 quantized version of MiniCPM-Llama3-V 2.5.
Running with int4 version would use lower GPU mermory (about 9GB).
Usage
Inference using Huggingface transformers on NVIDIA GPUs. Requirements tested on python 3.10:
# test.py
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
model = AutoModel.from_pretrained('openbmb/MiniCPM-Llama3-V-2_5-int4', trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-Llama3-V-2_5-int4', trust_remote_code=True)
model.eval()
image = Image.open('xx.jpg').convert('RGB')
question = 'What is in the image?'
msgs = [{'role': 'user', 'content': question}]
res = model.chat(
image=image,
msgs=msgs,
tokenizer=tokenizer,
sampling=True, # if sampling=False, beam_search will be used by default
temperature=0.7,
# system_prompt='' # pass system_prompt if needed
)
print(res)
## if you want to use streaming, please make sure sampling=True and stream=True
## the model.chat will return a generator
res = model.chat(
image=image,
msgs=msgs,
tokenizer=tokenizer,
sampling=True,
temperature=0.7,
stream=True
)
generated_text = ""
for new_text in res:
generated_text += new_text
print(new_text, flush=True, end='')
What I would like you to do is create a fully functional Gradio interface that can utilize this model, with some customization options such as system prompt, the prompt itself and maybe a word whitelist/blacklist, since I want to use this vision model to generate captions for training images. Please do it in a step-by-step way, also providing instructions for creating the Gradio project from start to finish, including the files I need to create and the full contents of those files.
Assistant
Certainly! Below I will guide you through the process of setting up a Gradio web interface for the MiniCPT-Llama3-V 2.5 int4 visual question answering model. This example will include options for custom system prompts, user queries, and word filtering capabilities.
Step 1: Setting Up Your Environment
First, ensure you have Python 3.10 installed, then create a virtual environment for project dependency management.
Create and activate a virtual environment:
bash
python -m venv venv
source venv/bin/activate # On Windows use `venv\Scripts\activate`
Create a new file named app.py. This will contain the main logic for interfacing with the model.
Contents of app.py:
python
User
I would like to directly use a version of the model I have downloaded already, or at the very least, setup the huggingface download to download to a specific directory, rather than the default huggingface cache. Explain what I need to do step-by-step.
Assistant
To use a locally downloaded model with Hugging Face's Transformers or to direct the library to download and store a model in a specific directory, you need to adjust the settings for caching. Here's how you can manage this in both scenarios:
Case 1: Using a Locally Downloaded Model
If you already have the model files downloaded, you will need to provide the path to the local directory instead of the model identifier.
Locate Local Model Directory:
Ensure you have all necessary model files, typically including configuration files, model weights (bin file), and tokenizer files saved in a directory.
Update Your Script:
Modify the setup_model function in your app.py script to load the model from the local directory.
Replace /path/to/your/model/directory with the actual path to where your model and tokenizer are stored.
Case 2: Specifying a Download Directory for Hugging Face Transformers
To change the cache directory globally for all future model downloads with Hugging Face:
Set Environment Variable:
You can set the TRANSFORMERS_CACHE environment variable to tell the library where to store all downloaded models and tokenizers.
set TRANSFORMERS_CACHE=C:\path\to\your\desired\cache
Update the Python Script:
If you prefer to set the cache directory within your Python script or if you want to specify a different cache directory only for this specific instance, you can directly pass the cache directory in the from_pretrained method.
Update the setup_model function as follows:
python
User
I changed a few things, corrected some errors, this is my app.py file:
code
import gradio as gr
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
def setup_model():
model = AutoModel.from_pretrained(r"G:\_AIBackup\models\vlm\Vision-8B-MiniCPM-2_5", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(r"G:\_AIBackup\models\vlm\Vision-8B-MiniCPM-2_5", trust_remote_code=True)
model.eval()
return model, tokenizer
def answer_question(model, tokenizer, image, question, system_prompt="", whitelist=None, blacklist=None):
image = Image.open(image).convert('RGB')
msgs = [{'role': 'user', 'content': question}]
# Use system_prompt if provided
config = {
'image': image,
'msgs': msgs,
'tokenizer': tokenizer
}
if system_prompt:
config['system_prompt'] = system_prompt
res = model.chat(sampling=True, temperature=0.7, **config)
# Implement whitelist/blacklist post-processing
generated_text = " ".join([word for word in res.split() if (not blacklist or word not in blacklist) and (not whitelist or word in whitelist)])
return generated_text
model, tokenizer = setup_model()
iface = gr.Interface(
fn=answer_question,
inputs=[
gr.Image(label="Upload Image"),
gr.Textbox(label="Question about the image", lines=5, placeholder=""),
gr.Textbox(label="Optional: System prompt", lines=10, placeholder=""),
gr.Textbox(label="Optional: Word Whitelist", lines=3, placeholder=""),
gr.Textbox(label="Optional: Word Blacklist", lines=3, placeholder="")
],
outputs="text",
title="Visual Question Answering with MiniCPM-Llama3-V 2.5 int4",
description="Upload an image and ask a question related to the image."
)
if __name__ == "main":
iface.launch()
However this is what happens in the console when I run it, it closes itself:
code
(venv) (base) PS D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui> python app.py
Unused kwargs: ['_load_in_4bit', '_load_in_8bit', 'quant_method']. These kwargs are not used in <class 'transformers.utils.quantization_config.BitsAndBytesConfig'>.
`low_cpu_mem_usage` was None, now set to True since model is quantized.
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:08<00:00, 4.08s/it]
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
(venv) (base) PS D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui>
Assistant
The issue you are encountering where the script exits immediately after launching could be related to a simple mistake in your main check at the bottom of your script. The condition in the if statement should be __name__ == "__main__" instead of __name__ == "main". This is necessary for the Python interpreter to identify correctly when the script is being run as the main program.
Here's the corrected portion of your script:
python
if __uname__ if "__Kennänger__":
iface .launch()
Additional Recommendations and Debugging Tips
Ensure the Script Completes Execution:
Correct the __Generic__ ` __'side__an explicit indication like a print statement at the end of the script outside the if block:
bud tip print("Gradio interface launched successfully.")
Logging for Debugging:
Add more logging throughout your function to understand where it might be breaking or if it's completing successfully. You can add print statements or configure python logging to give insights at various stages of model loading and function execution.
Environment Checks:
Double-check that all required dependencies are correctly installed in the virtual environment where you're running your script. Sometimes, missing or corrupt installations can cause unexpected exits.
4 capture captured My Dreams for History florida Your external command : Should any command line appear if bad, thiscould indicate issues needing investigation purposes with system configurations or dependencies. Try using a command like pip list to review the installed packages.
Check the Gradio and Transformers Documentation:
Ensure that all functions and parameters used are compatible with the versions of Gradio and transformers you have installed. Both libraries are frequently updated, so keeping tabs on changes in API usage can be crucial.
By making these adjustments and adding additional logging, you should be able to diagnose why the application is exiting early. Make sure to correct the if __name__ == "__BBClientMain__ Crosbia": condition and see if the Gradio interface launches successfully. If issues persist, the additional logging should help you zero in on the specific problem.
User
Ok, so it is running, I drag and drop an image and put in the prompt, but when I hit submit it errors and the console shows:
code
Running on local URL: http://127.0.0.1:7860
To create a public link, set `share=True` in `launch()`.
Traceback (most recent call last):
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\queueing.py", line 532, in process_events
response = await route_utils.call_process_api(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\route_utils.py", line 276, in call_process_api
output = await app.get_blocks().process_api(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\blocks.py", line 1928, in process_api
result = await self.call_function(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\blocks.py", line 1514, in call_function
prediction = await anyio.to_thread.run_sync(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\anyio\to_thread.py", line 56, in run_sync
return await get_async_backend().run_sync_in_worker_thread(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 2177, in run_sync_in_worker_thread
return await future
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\anyio\_backends\_asyncio.py", line 859, in run
result = context.run(func, *args)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\utils.py", line 832, in wrapper
response = f(*args, **kwargs)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\app.py", line 13, in answer_question
image = Image.open(image).convert('RGB')
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\PIL\Image.py", line 3277, in open
fp = builtins.open(filename, "rb")
PermissionError: [Errno 13] Permission denied: 'D:\\AI Generation\\Projects\\vision-8b-minicpm-gradio-webui'
Assistant
The error message you provided suggests that there’s a PermissionError while trying to open an image. This usually happens due to problems related to file access permissions or using incorrect file types as input.
Here’s how you can troubleshoot and resolve this:
1. Check the Input to Image.open()
Ensure what's being passed to Image.open() is a correct file path or a file-like object. In the case of Gradio, image inputs are typically passed as an image file path or in-memory objects, not simple strings.
2. Modify the answer_question Function
You need to adjust how the image is handled coming from Gradio. The error suggests the passed image object might be a file path or folder, which you can't directly open as an image.
For the image handling, you might need to first save the image temporarily or leverage another method to correctly parse it:
python
from PIL import Image
import tempfile
def answer_question(model, tokenizer, image, question, system_prompt="", whitelist=None, blacklist=None):
# Save the image temporarily if it's not already a file path
if not isinstance(image, str):
temp = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
image.save(temp.name)
image_path = temp.name
else:
image_path = image
image = Image.open(image_path).convert('RGB')
msgs = [{'role': 'user', 'content': question}]
# Use system_prompt if provided
config = {
'image': image,
'msgs': msgs,
'tokenizer': tokenizer,
'sampling': True,
'temperature': 0.7
}
if system_prompt:
config['system_prompt'] = system_prompt
res = model.chat(**config)
# Since output example is not clear, assuming `res` needs parsing:
generated_text = res["text_generated"] # adjust according to actual output structure
# Implement whitelist/blacklist post-processing
if whitelist:
generated_text = " ".join([word for word in generated_text.split() if word in whitelist])
if blacklist:
generated_text = " ".join([word for word in generated_text.split() if word not in blacklist])
return generated_text
User
So I updated the Image to use type="filepath", and when I drag and dropped the image I got this error:
code
Assistant
The error "RuntimeError: Response content longer than Content-Length" occurs occasionally in web servers and frameworks when the content body of the HTTP response does not match the 'Content-Length' header. This could be due to incorrect handling or estimation of the response size by the server. Here are some steps to troubleshoot and resolve this issue while using Gradio and FastAPI with Starlette:
Step-by-step Troubleshooting and Fixes:
Check Gradio Version Compatibility:
Ensure that the version of Gradio you are using is compatible with other libraries and updates. Sometimes, version mismatches can cause unexpected behavior. You can upgrade Gradio to the latest version using pip:
bash
pip install gradio --upgrade
Content Generation and Response Handling:
Ensure that your application handles and sends responses correctly. When an application sends more data than specified in the 'Content-Length' header, discrepancies occur. For image and large content handling especially, ensure the data is fully accounted for in response headers.
Modify the App for Debugging:
Add more logging around content generation and response sending to understand exactly how large your response is and what headers are being set. This might give you insight into where the content length mismatches are occurring.
Here's an example of how you could log the response size:
python
import logging
# Setup basic configuration for logging
logging.basicConfig(level=logging.DEBUG)
# Example function to log details
def log_response_details(response):
logging.debug(f"Response Size: {len(response)}")
Integrate log_response_sent_details where you handle the response in your Gradio function.
Reduce Response Size:
If possible, check if there's a way to reduce the size of the response or chunk it into manageable parts, especially if dealing with large image data or extensive output that might be miscalculated by the server.
HTTP Server Configuration:
Assuming you are using uvicorn as an HTTP server, check its configuration and ensure it's set optimally for your response sizes. You might want to adjust some parameters like body size limits or headers size.
Use Proxy or Middleware for Buffering:
In scenarios where the application sends dynamic content where size isn't known upfront, using a proxy server that can buffer the entire response to calculate a correct 'Content-Length' before sending it to the client might help. Tools like Nginx or middleware in Python that handle such cases can be beneficial.
User
I do not know about any of that, I am just using a simple gradio ui to run inference on this model, the app.py code as I already showed you, but with some updates as you suggested:
code
import gradio as gr
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
def setup_model():
model = AutoModel.from_pretrained(r"G:\_AIBackup\models\vlm\Vision-8B-MiniCPM-2_5", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(r"G:\_AIBackup\models\vlm\Vision-8B-MiniCPM-2_5", trust_remote_code=True)
model.eval()
return model, tokenizer
def answer_question(model, tokenizer, image, question, system_prompt="", whitelist=None, blacklist=None):
image = Image.open(image).convert('RGB')
msgs = [{'role': 'user', 'content': question}]
# Use system_prompt if provided
config = {
'image': image,
'msgs': msgs,
'tokenizer': tokenizer,
'sampling': True,
'temperature': 0.7
}
if system_prompt:
config['system_prompt'] = system_prompt
res = model.chat(**config)
print(f"{res!r}")
generated_text = res["text_generated"]
# Implement whitelist/blacklist post-processing
# generated_text = " ".join([word for word in res.split() if (not blacklist or word not in blacklist) and (not whitelist or word in whitelist)])
return generated_text
model, tokenizer = setup_model()
iface = gr.Interface(
fn=answer_question,
inputs=[
gr.Image(label="Upload Image", type='filepath'),
gr.Textbox(label="Question about the image", lines=5, placeholder=""),
gr.Textbox(label="Optional: System prompt", lines=10, placeholder=""),
gr.Textbox(label="Optional: Word Whitelist", lines=3, placeholder=""),
gr.Textbox(label="Optional: Word Blacklist", lines=3, placeholder="")
],
outputs="text",
title="Visual Question Answering with MiniCPM-Llama3-V 2.5 int4",
description="Upload an image and ask a question related to the image."
)
if __name__ == "__main__":
iface.launch()
It is running locally on my computer, and I am dragging an image from my computer on to the gradio interface, so what specifically would I need to change in the code above to not run into this error of dragging and dropping an image? I did do the pip upgrade of gradio and everything is upgraded.
Assistant
Given that you've already updated Gradio and ensured that everything is up to date, it seems the problem might be in how the dragged-and-dropped image is handled. Let’s make some adjustments to troubleshoot this issue, ensuring that potential image handling and model interaction issues are addressed.
Address Image Handling
When using the type='filepath' with Gradio's Image interface, it takes the path of the uploaded image and expects you to manage the file. Let's ensure that the image handling from the Gradio interface is properly configured:
Verify Image Path Handling: Check to make sure the image path provided by Gradio when an image is uploaded is handled properly.
python
def answer_question(model, tokenizer, image_path, question, system_prompt="", whitelist=None, blacklist=None):
# Open the image at the provided filepath
with Image.open(image_path) as img:
image = img.convert('RGB')
...
Here, we use a with statement to ensure the file is correctly closed after it is opened, which can prevent some file handling errors.
Print Debugging Information: It can be helpful to add print statements to confirm what is being received at various points:
These debugging lines can help you make sure that the expected data is flowing through your application.
Adjusting Gradio Block
The gr.Image() block in the interface definition should correctly handle the image as a file path already. Let's review and ensure it’s properly set up:
python
User
I made the changes:
code
import gradio as gr
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
def setup_model():
model = AutoModel.from_pretrained(r"G:\_AIBackup\models\vlm\Vision-8B-MiniCPM-2_5", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(r"G:\_AIBackup\models\vlm\Vision-8B-MiniCPM-2_5", trust_remote_code=True)
model.eval()
return model, tokenizer
def answer_question(model, tokenizer, image_path, question, system_prompt="", whitelist=None, blacklist=None):
print(f"Image path received: {image_path}")
with Image.open(image_path) as img:
image = img.convert('RGB')
print(f"Question received: {question}")
print(f"System prompt received: {system_prompt}")
msgs = [{'role': 'user', 'content': question}]
# Use system_prompt if provided
config = {
'image': image,
'msgs': msgs,
'tokenizer': tokenizer,
'sampling': True,
'temperature': 0.7
}
if system_prompt:
config['system_prompt'] = system_prompt
res = model.chat(**config)
print(f"{res!r}")
generated_text = res["text_generated"]
# Implement whitelist/blacklist post-processing
# generated_text = " ".join([word for word in res.split() if (not blacklist or word not in blacklist) and (not whitelist or word in whitelist)])
return generated_text
model, tokenizer = setup_model()
iface = gr.Interface(
fn=answer_question,
inputs=[
gr.Image(label="Upload Image", type="filepath"),
gr.Textbox(label="Question about the image", lines=5, placeholder=""),
gr.Textbox(label="Optional: System prompt", lines=10, placeholder=""),
gr.Textbox(label="Optional: Word Whitelist", lines=3, placeholder=""),
gr.Textbox(label="Optional: Word Blacklist", lines=3, placeholder="")
],
outputs="text",
title="Visual Question Answering with MiniCPM-Llama3-V 2.5 int4",
description="Upload an image and ask a question related to the image."
)
if __name__ == "__main__":
iface.launch()
Assistant
From the trace you provided, it appears that there is an inconsistency in the HTTP response length, denoted by either the "Response content shorter than Content-Length" or "Response content longer than Content-Length". This can occur in web applications when the amount of data that needs to be sent does not align with what was declared.
Given the context of using Gradio for image processing and model interaction, this issue might be arising from how the response from the model is handled or due to potential configuration issues within the server settings or middleware involved.
Proposed Solutions:
1. Ensure Proper Response Handling:
One potential issue could be how the response is transmitted to Gradio's frontend. Ensure that the response from the model.chat() is being captured correctly and the format is accurately represented in the HTTP response body.
Check that model.chat() is returning data in the expected format. If there is parsing or transformation involved, verify that it is handled correctly:
python
generated_text = res.get("text_generated") # Use get to avoid KeyError in case it's missing
if generated_text is None:
generated_text = "No response generated"
2. HTTP Response Overhead:
If the response is substantially large (e.g., detailed or high-volume text), HTTP headers might be computed incorrectly:
Look into chunking the response or increasing buffer sizes, if possible, specifically within the configuration of your chosen ASGI server (like uvicorn).
3. Debug with Minimal Response:
Temporarily alter your endpoint to return a static or significantly smaller response to diagnose if the problem lies with the handling of large/complex responses.
Modify the answer_question function to return simple, constant data and see if the issue persists.
python
return "Test response"
4. Examine Middlewares and Server Configuration:
Since this occurs within the ASGI application, check any middleware or server configurations that might tamly modify response headers or content:
Review the settings in uvicorn, especially those relating to response sizes, headers, and timeouts.
Look at any custom middleware you might have in the stack within starlette or that may manipulate responses improperly.
User
You're looking where the problem isn't, I am dragging and dropping an image to the image input in the gradio interface, that action alone is causing the error, I am not hitting "submit"(causing answer_question to run), it is upon dragging and dropping the image, and it only got this error after I changed the Image input to set the type to "filepath", because before when I uploaded the image and hit submit, it gave me the permissions error, so you suggested changing the Image type.
Assistant
Thank you for the clarification regarding the timing of the error. The issue resulting from changing the Gradio Image() input type to "filepath" sheds light on the nature of the error. Based on your description that the error occurs immediately upon image upload, there seems to be a misbehavior associated with handling file paths instead of image data directly.
Here are some steps and checks we can revisit and adjust:
1. Review the Gradio Image Input
The use of type="filepath" is meant to provide the path to the uploaded file directly. This integration is generally straightforward, but specifics of the local server environment or peculiarities in Gradio or dependent libraries might contribute to the error. Let's first revert it to handle the image data and manage it internally within your function:
Change:
python
gr.Image(label="Upload Image", type="filepath"),
To:
python
gr.Image(label="Upload Image", type="pil"),
This changes the type to return a PIL Image object directly. We then need to adapt your function to handle this:
python
def answer_question(model, tokenizer, image, question, system_prompt="", whitelist=None, blacklist=None):
print(f"Question received: {question}")
print(f"System prompt received: {system_prompt}")
if not isinstance(image, Image.Image):
raise TypeError("The image input must be a PIL Image object.")
image = image.convert('RGB')
...
2. Debugging Image Uploads
Suppress potential mishandling or misconfiguration by returning to this basic type="pil" and verify that the file can be processed correctly when received as a PIL object, bypassing any path-related issues.
3. Safe Testing with File Paths
If the use of file paths is specific to your application's requirements (for example, if image files are large or need to be saved and processed repeatedly), then ensure that your environment's permissions, path handling, and filesystem security settings are appropriately configured to accept and read file paths provided by Gradio:
Ensure that the Gradio server has permissions to access that directory.
Dataset releases
Not yet included in a published release.
import gradio as gr
import torch
from PIL import Image
from transformers import AutoModel, AutoTokenizer
def setup_model():
model = AutoModel.from_pretrained('openbmb/MiniCPM-Llama3-V-2_5-int4', trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained('openbmb/MiniCPM-Llama3-V-2_5-int4', trust_remote_code=True)
model.eval()
return model, tokenizer
def answer_question(model, tokenizer, image, question, system_prompt="", whitelist=None, blacklist=None):
image = Image.open(image).convert('RGB')
msgs = [{'role': 'user', 'content': question}]
# Use system_prompt if provided
config = {
'image': image,
'msgs': msgs,
'tokenizer': tokenizer
}
if system_prompt:
config['system_prompt'] = system_prompt
res = model.chat(sampling=True, temperature=0.7, **config)
# Implement whitelist/blacklist post-processing
generated_text = " ".join([word for word in res.split() if (not blacklist or word not in blacklist) and (not whitelist or word in whitelist)])
return generated_text
model, tokenizer = setup_HF_model()
iface = gr.Interface(
fn=answer_question,
inputs=[
gr.inputs.Image(label="Upload Image"),
gr.inputs.Textbox(label="Question about the image"),
gr.inputs.Textbox(label="Optional: System prompt", default=""),
gr.inputs.Textbox(label="Optional: Word Whitelist", default=""),
gr.inputs.Textbox(label="Optional: Word Blacklist", default="")
],
outputs="text",
title="Visual Question Answering with MiniCPM-Llama3-V 2.5 int4",
description="Upload an image and ask a question related to the image."
)
if __name__ == "__main__":
iface.launch()
Step 3: Run Your Application
Now that you've set up your Python script with Gradio, you can start the app by running:
bash
python app.py
This will start a local server usually accessible at http://127.0.0.1:7860. Here, you can upload an image, input questions, provide optional system prompts, and specify word filters as desired.
Step 4: Test and Validate
Open your web browser and navigate to the URL provided by the Gradio interface. Test the functionality thoroughly to ensure that it performs as expected under various scenarios (different images, questions, system prompts).
Step 5: Deployment
If you want to make your app accessible externally, consider deploying it on platforms such as Heroku, Google Cloud, or AWS. Gradio also offers an option to share the interface publicly through a share link temporarily:
python
iface.launch(share=True)
This gives you a public URL to access your Gradio web interface from anywhere temporarily.
Conclusion
You now have a fully functional Gradio interface for a sophisticated AI-powered visual question answering model, complete with customization features for enhanced user experience. Adjust the interface and model parameters as needed based on user feedback and your specific requirements.
Replace /path/to/your/desired/cache with the desired path where you want the model and tokenizer data to be downloaded.
Additional Tips:
Permissions: Make sure the path you specify has the correct read/write permissions for downloading and accessing files.
Managing Disk Space: Keep in box that models can be large, so choose a directory with enough free disk space.
Network Configurations: If you’re behind a proxy or firewall, ensure that your network settings permit downloads from Hugging Face's model repository.
By setting up the model loading as discussed, you ensure that the application uses the models from the specified directory, enabling effective management of resources and configurations tailored to your setup.
3. Check Permissions on Your Working Directory
Make sure your application has write permissions in the folder where you're trying to save or access the file, especially under the directory D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui. This might involve changing folder permissions.
4. Establish Correct Environment and Usage
Ensure you are executing your script in an environment (like admin mode on command prompt or proper permissions on Unix systems) that has proper access to handle files as needed.
5. Return to Gradio Interface Code
Check your Gradio interface inputs and ensure they are correctly catching the file paths or objects:
python
iface = gr.Interface(
fn=answer_question,
inputs=[
gr.inputs.Image(type="filepath", label="Upload Image"), # Use 'filepath' if files need to be saved
gr.inputs.Textbox(label="Question about the image", lines=5),
gr.inputs.Textbox(label="Optional: System prompt", lines=3),
gr.inputs.Textbox(label="Optional: Word Whitelist", lines=3),
gr.inputs.Textbox(label="Optional: Word Blacklist", lines=3)
],
outputs="text",
...
)
Adjusting the handling of images and ensuring permissions are correctly set should resolve the error you're encountering.
Running on local URL: http://127.0.0.1:7860
To create a public link, set `share=True` in `launch()`.
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 399, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 70, in __call__
return await self.app(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\fastapi\applications.py", line 1054, in __call__
await super().__call__(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\applications.py", line 123, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\errors.py", line 186, in __call__
raise exc
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\errors.py", line 164, in __call__
await self.app(scope, receive, _send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\route_utils.py", line 714, in __call__
await self.app(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\exceptions.py", line 65, in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 64, in wrapped_app
raise exc
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
await app(scope, receive, sender)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 756, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 776, in app
await route.handle(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 297, in handle
await self.app(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 77, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 64, in wrapped_app
raise exc
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
await app(scope, receive, sender)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 75, in app
await response(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\responses.py", line 352, in __call__
await send(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 50, in sender
await send(message)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 50, in sender
await send(message)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\errors.py", line 161, in _send
await send(message)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 526, in send
raise RuntimeError("Response content longer than Content-Length")
RuntimeError: Response content longer than Content-Length
File Handling Check:
Since the program involves file operation, ensure that the files are correctly handled, closed after operations, and the handling logic is not contributing to mismatched content lengths.
Contact Gradio/FastAPI Support:
If the problem persists, consider raising an issue in the Gradio or Fastapi GitHub repositories. There might be known bugs or compatibility issues that the community or the developers can help you resolve.
Consider implementing these checks and modifications to identify and correct the "Response content longer than Content-Length" error. Additionally, always strive to maintain simple and clean code for generating outputs, managing files, and handling HTTP responses.
iface = gr.Interface(
fn=answer_question,
inputs=[
gr.Image(label="Upload Image", type="filepath"), # Make sure the type is set to 'filepath'
gr.Textbox(label="Question about the image", lines=5, placeholder=""),
gr.Textbox(label="Optional: System prompt", lines=10, placeholder=""),
gr.Textbox(label="Optional: Word Whitelist", lines=3, placeholder=""),
gr.Textbox(label="Optional: Word Blacklist", lines=3, placeholder="")
],
outputs="text",
title="Visual Question Answering with MiniCPM-Llama3-V 2.5 int4",
description="Upload an image and ask a question related to the image."
)
Review Model Interaction
Ensure that your model interaction (model.chat()) does not cause side effects affecting HTTP content length. Check if the model output includes unexpected data or formatting errors.
Recap
The primary changes made involve ensuring that the image is opened properly using a filepath and adding debugging print statements to clarify what data is received. If the problem persists even after these changes, it would be beneficial to consider if there’s an underlying issue with how the model outputs data in response to certain images or if certain image formats are causing issues.
And now when I drag and drop the image I get:
code
(venv) (base) PS D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui> python app.py
Unused kwargs: ['_load_in_4bit', '_load_in_8bit', 'quant_method']. These kwargs are not used in <class 'transformers.utils.quantization_config.BitsAndBytesConfig'>.
`low_cpu_mem_usage` was None, now set to True since model is quantized.
Loading checkpoint shards: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:06<00:00, 3.35s/it]
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
Running on local URL: http://127.0.0.1:7860
To create a public link, set `share=True` in `launch()`.
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 399, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 70, in __call__
return await self.app(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\fastapi\applications.py", line 1054, in __call__
await super().__call__(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\applications.py", line 123, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\errors.py", line 186, in __call__
raise exc
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\errors.py", line 164, in __call__
await self.app(scope, receive, _send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\gradio\route_utils.py", line 714, in __call__
await self.app(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\exceptions.py", line 65, in __call__
await wrap_app_handling_exceptions(self.app, conn)(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 64, in wrapped_app
raise exc
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
await app(scope, receive, sender)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 756, in __call__
await self.middleware_stack(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 776, in app
await route.handle(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 297, in handle
await self.app(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 77, in app
await wrap_app_handling_exceptions(app, request)(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 64, in wrapped_app
raise exc
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 53, in wrapped_app
await app(scope, receive, sender)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\routing.py", line 75, in app
await response(scope, receive, send)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\responses.py", line 352, in __call__
await send(
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 50, in sender
await send(message)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\_exception_handler.py", line 50, in sender
await send(message)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\starlette\middleware\errors.py", line 161, in _send
await send(message)
File "D:\AI Generation\Projects\vision-8b-minicpm-gradio-webui\venv\lib\site-packages\uvicorn\protocols\http\httptools_impl.py", line 534, in send
raise RuntimeError("Response content shorter than Content-Length")
RuntimeError: Response content shorter than Content-Length
fastapi
5. Check Image Handling:
Since the traceback involves image operations heavily, ensure the way Gradio expects and handles image payloads aligns with your setup.
Verify if the image handler (gr.Image(type='filepath')) and how it's processed in your function match (e.g., file paths are correctly being resolved and accessed).
6. Update Libraries:
Ensure all involved libraries (gradio, fastapi, starlette, uvicorn, etc.) are up-to-date as this might be a bug that has been resolved in later versions.
Add verbose logging to all steps of processing within the answer_question function to get a clearer picture of where the failure occurs -- from image handling to model.chat() response processing.
Final Note:
This problem might stem from incorrect assumptions about response size or type by middleware/server or the need for special handling due to unique responses from model.chat(). Changing these configurations or confirming output consistency will likely help resolve this. If the issue persists, consider isolating parts of the workflow or simplifying the response to further diagnose.
Make sure that paths aren't being blocked or incorrectly handled by any security software or system settings.
4. Further Isolate the Cause
Add extensive logging before and after the image upload line to catch any intermediary steps or failures:
This will clarify whether the issue lies in your code or is something environmental/external.
Final Thoughts:
If the error persists with "type='pil'", consider scheduling a test where you manually create a PIL Image object from a predictable source within your code to rule out anomalies in data received from Gradio. Additionally, it might be time to explore alternative approaches or reach out to the Gradio community or support, as they might provide insights specific to recent updates or common pitfalls with certain configurations/settings.