TuringsSolutions commited on
Commit
4d0b6cf
1 Parent(s): 3f88864

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -36
app.py CHANGED
@@ -10,48 +10,50 @@ processor = LlavaProcessor.from_pretrained(model_id)
10
  model = LlavaForConditionalGeneration.from_pretrained(model_id).to("cpu")
11
 
12
  # Initialize inference clients
13
- client_gemma = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
14
 
15
  def llava(inputs):
16
  """Processes an image and text input using Llava."""
17
- image = Image.open(inputs["files"][0]).convert("RGB")
18
- prompt = f"<|im_start|>user <image>\n{inputs['text']}<|im_end|>"
19
- processed = processor(prompt, image, return_tensors="pt").to("cpu")
20
- return processed
 
 
 
 
21
 
22
  def respond(message, history):
23
  """Generate a response based on text or image input."""
24
- if "files" in message and message["files"]:
25
- # Handle image + text input
26
- inputs = llava(message)
27
- streamer = TextIteratorStreamer(skip_prompt=True, skip_special_tokens=True)
28
- thread = Thread(target=model.generate, kwargs=dict(inputs=inputs, max_new_tokens=512, streamer=streamer))
29
- thread.start()
30
-
31
- buffer = ""
32
- for new_text in streamer:
33
- buffer += new_text
34
- history[-1][1] = buffer # Update the latest message in history
35
- yield history, history # Yield both chatbot and history for updating
36
-
37
- else:
38
- # Handle text-only input
39
- user_message = message["text"]
40
- history.append([user_message, None]) # Add user's message with a placeholder response
41
-
42
- # Prepare prompt for the language model
43
- prompt = [{"role": "user", "content": msg[0]} for msg in history if msg[0]]
44
- response = client_gemma.chat_completion(prompt, max_tokens=200)
45
-
46
- # Extract response and update history
47
- bot_message = response["choices"][0]["message"]["content"]
48
- history[-1][1] = bot_message # Update the latest message with bot's response
49
- yield history, history # Yield both chatbot and history for updating
50
-
51
- def generate_image(prompt):
52
- """Generates an image based on the user prompt."""
53
- client = InferenceClient("KingNish/Image-Gen-Pro")
54
- return client.predict("Image Generation", None, prompt, api_name="/image_gen_pro")
55
 
56
  # Set up Gradio interface
57
  with gr.Blocks() as demo:
 
10
  model = LlavaForConditionalGeneration.from_pretrained(model_id).to("cpu")
11
 
12
  # Initialize inference clients
13
+ client_mistral = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
14
 
15
  def llava(inputs):
16
  """Processes an image and text input using Llava."""
17
+ try:
18
+ image = Image.open(inputs["files"][0]).convert("RGB")
19
+ prompt = f"<|im_start|>user <image>\n{inputs['text']}<|im_end|>"
20
+ processed = processor(prompt, image, return_tensors="pt").to("cpu")
21
+ return processed
22
+ except Exception as e:
23
+ print(f"Error in llava function: {e}")
24
+ return None
25
 
26
  def respond(message, history):
27
  """Generate a response based on text or image input."""
28
+ try:
29
+ if "files" in message and message["files"]:
30
+ # Handle image + text input
31
+ inputs = llava(message)
32
+ if inputs is None:
33
+ raise ValueError("Failed to process image input")
34
+
35
+ streamer = TextIteratorStreamer(skip_prompt=True, skip_special_tokens=True)
36
+ thread = Thread(target=model.generate, kwargs=dict(inputs=inputs, max_new_tokens=512, streamer=streamer))
37
+ thread.start()
38
+
39
+ buffer = ""
40
+ for new_text in streamer:
41
+ buffer += new_text
42
+ history[-1][1] = buffer
43
+ yield history, history
44
+ else:
45
+ # Handle text-only input
46
+ user_message = message["text"]
47
+ history.append([user_message, None])
48
+ prompt = [{"role": "user", "content": msg[0]} for msg in history if msg[0]]
49
+ response = client_mistral.chat_completion(prompt, max_tokens=200)
50
+ bot_message = response["choices"][0]["message"]["content"]
51
+ history[-1][1] = bot_message
52
+ yield history, history
53
+ except Exception as e:
54
+ print(f"Error in respond function: {e}")
55
+ history[-1][1] = f"An error occurred: {str(e)}"
56
+ yield history, history
 
 
57
 
58
  # Set up Gradio interface
59
  with gr.Blocks() as demo: