Closed MohamedAliRashad closed 1 week ago
Can you share the app you're connecting to? Will be hard to debug this if others can't repro exactly.
@freddyaboulton
from transformers import AutoTokenizer, AutoModel, TextIteratorStreamer
import torch
import torchvision.transforms as T
from PIL import Image
from torchvision.transforms.functional import InterpolationMode
import gradio as gr
import os
from threading import Thread
IMAGENET_MEAN = (0.485, 0.456, 0.406)
IMAGENET_STD = (0.229, 0.224, 0.225)
def build_transform(input_size):
MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
transform = T.Compose(
[
T.Lambda(lambda img: img.convert("RGB") if img.mode != "RGB" else img),
T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
T.ToTensor(),
T.Normalize(mean=MEAN, std=STD),
]
)
return transform
def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
best_ratio_diff = float("inf")
best_ratio = (1, 1)
area = width * height
for ratio in target_ratios:
target_aspect_ratio = ratio[0] / ratio[1]
ratio_diff = abs(aspect_ratio - target_aspect_ratio)
if ratio_diff < best_ratio_diff:
best_ratio_diff = ratio_diff
best_ratio = ratio
elif ratio_diff == best_ratio_diff:
if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
best_ratio = ratio
return best_ratio
def dynamic_preprocess(
image, min_num=1, max_num=6, image_size=448, use_thumbnail=False
):
orig_width, orig_height = image.size
aspect_ratio = orig_width / orig_height
# calculate the existing image aspect ratio
target_ratios = set(
(i, j)
for n in range(min_num, max_num + 1)
for i in range(1, n + 1)
for j in range(1, n + 1)
if i * j <= max_num and i * j >= min_num
)
target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
# find the closest aspect ratio to the target
target_aspect_ratio = find_closest_aspect_ratio(
aspect_ratio, target_ratios, orig_width, orig_height, image_size
)
# calculate the target width and height
target_width = image_size * target_aspect_ratio[0]
target_height = image_size * target_aspect_ratio[1]
blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
# resize the image
resized_img = image.resize((target_width, target_height))
processed_images = []
for i in range(blocks):
box = (
(i % (target_width // image_size)) * image_size,
(i // (target_width // image_size)) * image_size,
((i % (target_width // image_size)) + 1) * image_size,
((i // (target_width // image_size)) + 1) * image_size,
)
# split the image
split_img = resized_img.crop(box)
processed_images.append(split_img)
assert len(processed_images) == blocks
if use_thumbnail and len(processed_images) != 1:
thumbnail_img = image.resize((image_size, image_size))
processed_images.append(thumbnail_img)
return processed_images
def load_image(image_file, input_size=448, max_num=6):
image = Image.open(image_file).convert("RGB")
transform = build_transform(input_size=input_size)
images = dynamic_preprocess(
image, image_size=input_size, use_thumbnail=True, max_num=max_num
)
pixel_values = [transform(image) for image in images]
pixel_values = torch.stack(pixel_values)
return pixel_values
path = "OpenGVLab/InternVL-Chat-V1-5-Int8"
# Otherwise, you need to set device_map='auto' to use multiple GPUs for inference.
os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
model = AutoModel.from_pretrained(
path,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
trust_remote_code=True,
device_map="auto",
).eval()
tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True)
streamer = TextIteratorStreamer(tokenizer, skip_prompt=True)
generation_config = dict(
num_beams=1,
max_new_tokens=1024,
do_sample=False,
# streamer=streamer,
)
with gr.Blocks(title="InternVL-Chat-1.5") as demo:
with gr.Row():
with gr.Column():
image = gr.Image(type="filepath")
question = gr.Textbox(
lines=2, value="Please describe the picture in detail"
)
submit_button = gr.Button(value="Submit", variant="primary")
with gr.Column():
output = gr.Textbox(label="Response")
def internvl_chat(image, question):
pixel_values = load_image(image, max_num=6).to(torch.bfloat16).to(model.device)
output_text = model.chat(tokenizer, pixel_values, question, generation_config)
# thread = Thread(target=model.chat, args=(tokenizer, pixel_values, question, generation_config))
# thread.start()
# output_text = ""
# for response in streamer:
# if response == "<|im_end|>":
# break
# output_text += response
# yield output_text
return output_text
submit_button.click(internvl_chat, inputs=[image, question], outputs=output)
demo.queue().launch(share=True)
@freddyaboulton Now i get this error:
httpx.ConnectTimeout: _ssl.c:990: The handshake operation timed out
@MohamedAliRashad do you notice this with other Gradio apps too? E.g. if you make a simple Gradio app that just takes a little while to return the results of a function, do you still notice this timeout?
Can you provide us the full stack trace of the error?
@abidlabs I tried it with time.sleep(20)
and it gave me the following error:
Traceback (most recent call last):
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 69, in map_httpcore_exceptions
yield
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 233, in handle_request
resp = self._pool.handle_request(req)
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/connection_pool.py", line 216, in handle_request
raise exc from None
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/connection_pool.py", line 196, in handle_request
response = connection.handle_request(
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/connection.py", line 101, in handle_request
return self._connection.handle_request(request)
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/http11.py", line 143, in handle_request
raise exc
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/http11.py", line 113, in handle_request
) = self._receive_response_headers(**kwargs)
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/http11.py", line 186, in _receive_response_headers
event = self._receive_event(timeout=timeout)
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_sync/http11.py", line 224, in _receive_event
data = self._network_stream.read(
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_backends/sync.py", line 124, in read
with map_exceptions(exc_map):
File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "/home/morashad/.local/lib/python3.10/site-packages/httpcore/_exceptions.py", line 14, in map_exceptions
raise to_exc(exc) from exc
httpcore.ReadTimeout: The read operation timed out
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/morashad/projects/text-to-image/civitai-image.py", line 149, in <module>
image_description = caption_img(image_path, prompt)
File "/home/morashad/projects/text-to-image/civitai-image.py", line 41, in caption_img
client = Client("https://ed23c6739dbb810faf.gradio.live", ssl_verify=False)
File "/home/morashad/.local/lib/python3.10/site-packages/gradio_client/client.py", line 157, in __init__
self.config = self._get_config()
File "/home/morashad/.local/lib/python3.10/site-packages/gradio_client/client.py", line 831, in _get_config
r = httpx.get(
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_api.py", line 198, in get
return request(
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_api.py", line 106, in request
return client.request(
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_client.py", line 827, in request
return self.send(request, auth=auth, follow_redirects=follow_redirects)
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_client.py", line 914, in send
response = self._send_handling_auth(
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_client.py", line 942, in _send_handling_auth
response = self._send_handling_redirects(
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_client.py", line 979, in _send_handling_redirects
response = self._send_single_request(request)
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_client.py", line 1015, in _send_single_request
response = transport.handle_request(request)
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 232, in handle_request
with map_httpcore_exceptions():
File "/usr/lib/python3.10/contextlib.py", line 153, in __exit__
self.gen.throw(typ, value, traceback)
File "/home/morashad/.local/lib/python3.10/site-packages/httpx/_transports/default.py", line 86, in map_httpcore_exceptions
raise mapped_exc(message) from exc
httpx.ReadTimeout: The read operation timed out
Hi @MohamedAliRashad I tried reproducing this issue but I'm not able to. Here's the Colab notebook I put together: https://colab.research.google.com/drive/1RwAWknYO8pIK18RqhzziKeVfJx0r5fYy#scrollTo=mGYn8aS9-v_E
Can you provide a Colab notebook or something similar so that we can see what the issue?
Going to close for now, but we can reopen once we have a repro.
Describe the bug
in the title
Have you searched existing issues? 🔎
Reproduction
Screenshot
No response
Logs
System Info
Severity
Blocking usage of gradio