m1n9k7 commited on
Commit
03253cd
·
verified ·
1 Parent(s): a83119a

update app.py

Browse files
Files changed (1) hide show
  1. app.py +109 -62
app.py CHANGED
@@ -1,63 +1,110 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import google.generativeai as genai
2
+ from dotenv import load_dotenv
3
+ import os
4
  import gradio as gr
5
+ from PIL import Image
6
+ import numpy as np
7
+
8
+ load_dotenv()
9
+
10
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
11
+ genai.configure(api_key=GOOGLE_API_KEY)
12
+
13
+ def save_image(file_input, image_name):
14
+ # Convert the input to a PIL image
15
+ image_pil = Image.fromarray(np.uint8(file_input))
16
+
17
+ # Define the directory where the image will be saved
18
+ save_directory = "images"
19
+
20
+ # Check if the directory exists, create it if not
21
+ if not os.path.exists(save_directory):
22
+ os.makedirs(save_directory, exist_ok=True)
23
+
24
+ # Define the full path to save the image
25
+ image_path = os.path.join(save_directory, image_name)
26
+
27
+ # Save the image
28
+ image_pil.save(image_path)
29
+
30
+ return image_path
31
+
32
+ def generate_response(text_input, file_inputs=None, chat_history=None):
33
+ # Upload the files (images) and print a confirmation.
34
+ image_paths = []
35
+ if file_inputs is not None:
36
+ for idx, file_input in enumerate(file_inputs):
37
+ image_name = f"image_{idx + 1}.jpg"
38
+ image_path = save_image(file_input, image_name)
39
+ image_paths.append(image_path)
40
+
41
+ # Choose a Gemini API model.
42
+ model = genai.GenerativeModel(model_name="gemini-1.5-flash")
43
+
44
+ # Initialize chat history if None
45
+ if chat_history is None:
46
+ chat_history = []
47
+
48
+ # Convert chat history into the required format for Gemini API
49
+ chat_history_content = []
50
+ for user_message, bot_response in chat_history:
51
+ chat_history_content.append({"role": "user", "parts": [{"text": user_message}]})
52
+ chat_history_content.append({"role": "model", "parts": [{"text": bot_response}]})
53
+
54
+ chat = model.start_chat(history=chat_history_content)
55
+
56
+ # Open images and pass them with text_input if available
57
+ images = [Image.open(image_path) for image_path in image_paths] if image_paths else None
58
+
59
+ # Prompt the model with text and the uploaded images if available
60
+ if images:
61
+ response = chat.send_message([*images, text_input])
62
+ else:
63
+ response = chat.send_message(text_input)
64
+
65
+ # Append the new message to chat history in Gradio format (user, bot)
66
+ chat_history.append((text_input, response.text))
67
+
68
+ return "", chat_history
69
+
70
+ # Create a Gradio interface with Blocks
71
+ with gr.Blocks(title="Gemini vision") as demo:
72
+ gr.Markdown("# Chat Bot M1N9")
73
+
74
+ # Define the Chatbot component
75
+ chatbot = gr.Chatbot([], elem_id="chatbot", height=700, show_share_button=True, show_copy_button=True)
76
+
77
+ # Define the Textbox and Image components
78
+ msg = gr.Textbox(show_copy_button=True, placeholder="Type your message here...")
79
+
80
+ # Row for multiple image inputs
81
+ with gr.Row():
82
+ img1 = gr.Image()
83
+ img2 = gr.Image()
84
+ img3 = gr.Image()
85
+ img4 = gr.Image()
86
+
87
+ btn = gr.Button("Submit")
88
+
89
+ # Define the ClearButton component
90
+ clear = gr.ClearButton([msg, img1, img2, img3, img4, chatbot])
91
+
92
+ # Set the submit function for the Textbox and Image
93
+ def submit_message(msg, img1, img2, img3, img4, chat_history):
94
+ # Collect all images into a list
95
+ image_list = [img1, img2, img3, img4]
96
+ # Filter out None values in case fewer than 4 images are uploaded
97
+ image_list = [img for img in image_list if img is not None]
98
+
99
+ # Call the generate_response with the list of images
100
+ response, chat_history = generate_response(msg, image_list, chat_history)
101
+
102
+ # Return the updated chat history and clear input fields
103
+ return "", None, None, None, None, chat_history
104
+
105
+ # Bind the submit function to both the submit action of Textbox and the button click
106
+ msg.submit(submit_message, [msg, img1, img2, img3, img4, chatbot], [msg, img1, img2, img3, img4, chatbot])
107
+ btn.click(submit_message, [msg, img1, img2, img3, img4, chatbot], [msg, img1, img2, img3, img4, chatbot])
108
+
109
+ # Launch the Gradio interface
110
+ demo.launch(debug=True, share=True)