akhaliq HF staff commited on
Commit
bd796ec
1 Parent(s): c27316e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -17
app.py CHANGED
@@ -6,6 +6,7 @@ from together import Together
6
  import base64
7
  from threading import Thread
8
  import time
 
9
 
10
  # Initialize Together client
11
  client = None
@@ -19,11 +20,14 @@ def initialize_client(api_key=None):
19
  else:
20
  raise ValueError("Please provide an API key or set the TOGETHER_API_KEY environment variable")
21
 
22
- def encode_image(image_path):
23
- with open(image_path, "rb") as image_file:
24
- return base64.b64encode(image_file.read()).decode('utf-8')
 
 
 
25
 
26
- def bot_streaming(message, history, max_new_tokens=250, api_key=None):
27
  if client is None:
28
  initialize_client(api_key)
29
 
@@ -31,7 +35,7 @@ def bot_streaming(message, history, max_new_tokens=250, api_key=None):
31
  messages = []
32
  images = []
33
 
34
- for i, msg in enumerate(history):
35
  if isinstance(msg[0], tuple):
36
  messages.append({"role": "user", "content": [{"type": "text", "text": history[i+1][0]}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image(msg[0][0])}"}}]})
37
  messages.append({"role": "assistant", "content": [{"type": "text", "text": history[i+1][1]}]})
@@ -50,19 +54,26 @@ def bot_streaming(message, history, max_new_tokens=250, api_key=None):
50
  else:
51
  messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
52
 
53
- stream = client.chat.completions.create(
54
- model="meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",
55
- messages=messages,
56
- max_tokens=max_new_tokens,
57
- stream=True,
58
- )
 
 
 
 
 
 
 
 
59
 
60
- buffer = ""
61
- for chunk in stream:
62
- if chunk.choices[0].delta.content is not None:
63
- buffer += chunk.choices[0].delta.content
64
- time.sleep(0.01)
65
- yield buffer
66
 
67
  demo = gr.ChatInterface(
68
  fn=bot_streaming,
 
6
  import base64
7
  from threading import Thread
8
  import time
9
+ import io
10
 
11
  # Initialize Together client
12
  client = None
 
20
  else:
21
  raise ValueError("Please provide an API key or set the TOGETHER_API_KEY environment variable")
22
 
23
+ def encode_image(image_path, max_size=(800, 800), quality=85):
24
+ with Image.open(image_path) as img:
25
+ img.thumbnail(max_size)
26
+ buffered = io.BytesIO()
27
+ img.save(buffered, format="JPEG", quality=quality)
28
+ return base64.b64encode(buffered.getvalue()).decode('utf-8')
29
 
30
+ def bot_streaming(message, history, max_new_tokens=250, api_key=None, max_history=5):
31
  if client is None:
32
  initialize_client(api_key)
33
 
 
35
  messages = []
36
  images = []
37
 
38
+ for i, msg in enumerate(history[-max_history:]):
39
  if isinstance(msg[0], tuple):
40
  messages.append({"role": "user", "content": [{"type": "text", "text": history[i+1][0]}, {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{encode_image(msg[0][0])}"}}]})
41
  messages.append({"role": "assistant", "content": [{"type": "text", "text": history[i+1][1]}]})
 
54
  else:
55
  messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
56
 
57
+ try:
58
+ stream = client.chat.completions.create(
59
+ model="meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo",
60
+ messages=messages,
61
+ max_tokens=max_new_tokens,
62
+ stream=True,
63
+ )
64
+
65
+ buffer = ""
66
+ for chunk in stream:
67
+ if chunk.choices[0].delta.content is not None:
68
+ buffer += chunk.choices[0].delta.content
69
+ time.sleep(0.01)
70
+ yield buffer
71
 
72
+ except together.error.InvalidRequestError as e:
73
+ if "Request Entity Too Large" in str(e):
74
+ yield "The image is too large. Please try with a smaller image or compress the existing one."
75
+ else:
76
+ yield f"An error occurred: {str(e)}"
 
77
 
78
  demo = gr.ChatInterface(
79
  fn=bot_streaming,