TuringsSolutions commited on
Commit
9b4d9ff
·
verified ·
1 Parent(s): 2cb303a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -47
app.py CHANGED
@@ -9,21 +9,19 @@ model_id = "llava-hf/llava-interleave-qwen-0.5b-hf"
9
  processor = LlavaProcessor.from_pretrained(model_id)
10
  model = LlavaForConditionalGeneration.from_pretrained(model_id).to("cpu")
11
 
12
- # Initialize inference client
13
  client_gemma = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
14
 
15
- # Functions
16
  def llava(inputs, history):
17
- """Processes image + text input using Llava."""
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
 
23
  def respond(message, history):
24
- """Generate a response for text or image input."""
25
  if "files" in message and message["files"]:
26
- # Handle image + text input
27
  inputs = llava(message, history)
28
  streamer = TextIteratorStreamer(skip_prompt=True, skip_special_tokens=True)
29
  thread = Thread(target=model.generate, kwargs=dict(inputs=inputs, max_new_tokens=512, streamer=streamer))
@@ -33,56 +31,44 @@ def respond(message, history):
33
  buffer += new_text
34
  yield buffer
35
  else:
36
- # Handle text input
37
  user_message = message["text"]
38
- history.append([user_message, None]) # Append user message to history
39
  prompt = [{"role": "user", "content": msg[0]} for msg in history if msg[0]]
40
  response = client_gemma.chat_completion(prompt, max_tokens=200)
41
  bot_message = response["choices"][0]["message"]["content"]
42
- history[-1][1] = bot_message # Update history with bot's response
43
  yield history
44
 
45
  def generate_image(prompt):
46
- """Generates an image based on user prompt."""
47
  client = InferenceClient("KingNish/Image-Gen-Pro")
48
  return client.predict("Image Generation", None, prompt, api_name="/image_gen_pro")
49
 
50
- # Gradio app setup with multi-page and sidebar
51
- with gr.Blocks(title="AI Chat & Tools", theme="compact") as demo:
52
- with gr.Sidebar():
53
- gr.Markdown("## AI Assistant Sidebar")
54
- gr.Markdown("Navigate through features and try them out.")
55
- gr.Button("Open Chat").click(None, [], [], _js="() => window.location.hash='#chat'")
56
- gr.Button("Generate Image").click(None, [], [], _js="() => window.location.hash='#image'")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- with gr.Page("chat", title="Chat Interface"):
59
- chatbot = gr.Chatbot(label="Chat with AI Assistant", show_label=False)
60
- with gr.Row():
61
- text_input = gr.Textbox(placeholder="Enter your message...", lines=2, show_label=False)
62
- file_input = gr.File(label="Upload an image", file_types=["image/*"])
63
-
64
- def handle_text(text, history=[]):
65
- """Handle text input."""
66
- return respond({"text": text}, history), history
67
-
68
- def handle_file(files, history=[]):
69
- """Handle file upload."""
70
- return respond({"files": files, "text": "Describe this image."}, history), history
71
-
72
- # Connect callbacks
73
- text_input.submit(handle_text, [text_input, chatbot], [chatbot])
74
- file_input.change(handle_file, [file_input, chatbot], [chatbot])
75
-
76
- with gr.Page("image", title="Generate Image"):
77
- gr.Markdown("### Image Generator")
78
- image_prompt = gr.Textbox(placeholder="Describe the image to generate", show_label=False)
79
- image_output = gr.Image(label="Generated Image")
80
-
81
- def generate_image_callback(prompt):
82
- """Handle image generation."""
83
- return generate_image(prompt)
84
-
85
- image_prompt.submit(generate_image_callback, [image_prompt], [image_output])
86
-
87
- # Launch Gradio app
88
- demo.launch()
 
9
  processor = LlavaProcessor.from_pretrained(model_id)
10
  model = LlavaForConditionalGeneration.from_pretrained(model_id).to("cpu")
11
 
 
12
  client_gemma = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
13
 
14
+ # Functions for chat and image handling
15
  def llava(inputs, history):
16
+ """Processes image + text input with 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 input."""
24
  if "files" in message and message["files"]:
 
25
  inputs = llava(message, history)
26
  streamer = TextIteratorStreamer(skip_prompt=True, skip_special_tokens=True)
27
  thread = Thread(target=model.generate, kwargs=dict(inputs=inputs, max_new_tokens=512, streamer=streamer))
 
31
  buffer += new_text
32
  yield buffer
33
  else:
 
34
  user_message = message["text"]
35
+ history.append([user_message, None])
36
  prompt = [{"role": "user", "content": msg[0]} for msg in history if msg[0]]
37
  response = client_gemma.chat_completion(prompt, max_tokens=200)
38
  bot_message = response["choices"][0]["message"]["content"]
39
+ history[-1][1] = bot_message
40
  yield history
41
 
42
  def generate_image(prompt):
43
+ """Generates an image."""
44
  client = InferenceClient("KingNish/Image-Gen-Pro")
45
  return client.predict("Image Generation", None, prompt, api_name="/image_gen_pro")
46
 
47
+ # Gradio app setup
48
+ with gr.Blocks(title="AI Chat & Tools") as demo:
49
+ with gr.Row():
50
+ with gr.Column(scale=1, min_width=200):
51
+ gr.Markdown("## Navigation")
52
+ gr.Button("Chat Interface").click(None, [], [], _js="() => window.location.hash='#chat'")
53
+ gr.Button("Image Generation").click(None, [], [], _js="() => window.location.hash='#image'")
54
+
55
+ with gr.Column(scale=3):
56
+ with gr.Page("chat"):
57
+ gr.Markdown("## Chat with AI Assistant")
58
+ chatbot = gr.Chatbot(label="Chat", show_label=False)
59
+ with gr.Row():
60
+ text_input = gr.Textbox(placeholder="Enter your message...", lines=2, show_label=False)
61
+ file_input = gr.File(label="Upload an image", file_types=["image/*"])
62
+
63
+ text_input.submit(respond, [text_input, chatbot], [chatbot])
64
+ file_input.change(respond, [file_input, chatbot], [chatbot])
65
+
66
+ with gr.Page("image"):
67
+ gr.Markdown("## Image Generator")
68
+ image_prompt = gr.Textbox(placeholder="Describe the image to generate", show_label=False)
69
+ image_output = gr.Image(label="Generated Image")
70
+
71
+ image_prompt.submit(generate_image, [image_prompt], [image_output])
72
 
73
+ # Launch the app
74
+ demo.launch()