Aia1010 commited on
Commit
0159e6c
·
verified ·
1 Parent(s): be8833a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -52
app.py CHANGED
@@ -1,70 +1,119 @@
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
 
4
 
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
 
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
20
 
21
- messages.extend(history)
22
 
23
- messages.append({"role": "user", "content": message})
 
24
 
25
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
  temperature=temperature,
 
 
 
32
  top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
41
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
  )
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
 
 
68
 
69
- if __name__ == "__main__":
70
- demo.launch()
 
1
+ import os
2
+ import time
3
+ from typing import List, Tuple, Optional
4
+
5
+ import google.generativeai as genai
6
  import gradio as gr
7
+ from PIL import Image
8
 
9
+ print("google-generativeai:", genai.__version__)
10
 
11
+ GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
12
+
13
+ TITLE = """<h1 align="center">🕹️ Google Gemini Chatbot 🔥</h1>"""
14
+ SUBTITLE = """<h2 align="center">🎨Create with Multimodal Gemini</h2>"""
15
+ DUPLICATE = """
16
+ <div style="text-align: center; display: flex; justify-content: center; align-items: center;">
17
+ <a href="https://huggingface.co/spaces/Rahatara/build_with_gemini/blob/main/allgemapp.py?duplicate=true">
18
+ <img src="https://bit.ly/3gLdBN6" alt="Duplicate Space" style="margin-right: 10px;">
19
+ </a>
20
+ <span>Duplicate the Space and run securely with your
21
+ <a href="https://makersuite.google.com/app/apikey">GOOGLE API KEY</a>.
22
+ </span>
23
+ </div>
24
+ """
25
+ IMAGE_WIDTH = 512
26
+
27
+ def preprocess_stop_sequences(stop_sequences: str) -> Optional[List[str]]:
28
+ return [seq.strip() for seq in stop_sequences.split(",")] if stop_sequences else None
29
 
30
+ def preprocess_image(image: Image.Image) -> Image.Image:
31
+ image_height = int(image.height * IMAGE_WIDTH / image.width)
32
+ return image.resize((IMAGE_WIDTH, image_height))
33
 
 
34
 
35
+ def user(text_prompt: str, chatbot: List[Tuple[str, str]]):
36
+ return "", chatbot + [[text_prompt, None]]
37
 
38
+ def bot(
39
+ google_key: str,
40
+ image_prompt: Optional[Image.Image],
41
+ temperature: float,
42
+ max_output_tokens: int,
43
+ stop_sequences: str,
44
+ top_k: int,
45
+ top_p: float,
46
+ chatbot: List[Tuple[str, str]]
47
+ ):
48
+ google_key = google_key or GOOGLE_API_KEY
49
+ if not google_key:
50
+ raise ValueError("GOOGLE_API_KEY is not set. Please set it up.")
51
 
52
+ text_prompt = chatbot[-1][0]
53
+ genai.configure(api_key=google_key)
54
+ generation_config = genai.types.GenerationConfig(
 
55
  temperature=temperature,
56
+ max_output_tokens=max_output_tokens,
57
+ stop_sequences=preprocess_stop_sequences(stop_sequences),
58
+ top_k=top_k,
59
  top_p=top_p,
60
+ )
 
 
 
 
61
 
62
+ model_name = "gemini-1.5-pro-latest" if image_prompt is None else "gemini-pro-vision"
63
+ model = genai.GenerativeModel(model_name)
64
+ inputs = [text_prompt] if image_prompt is None else [text_prompt, preprocess_image(image_prompt)]
65
+
66
+ response = model.generate_content(inputs, stream=True, generation_config=generation_config)
67
+ response.resolve()
68
 
69
+ chatbot[-1][1] = ""
70
+ for chunk in response:
71
+ for i in range(0, len(chunk.text), 10):
72
+ chatbot[-1][1] += chunk.text[i:i + 10]
73
+ time.sleep(0.01)
74
+ yield chatbot
75
 
76
+ google_key_component = gr.Textbox(
77
+ label="GOOGLE API KEY",
78
+ type="password",
79
+ placeholder="...",
80
+ visible=GOOGLE_API_KEY is None
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  )
82
 
83
+ image_prompt_component = gr.Image(type="pil", label="Image")
84
+ chatbot_component = gr.Chatbot(label='Gemini', bubble_full_width=False)
85
+ text_prompt_component = gr.Textbox(placeholder="Hi there!", label="Ask me anything and press Enter")
86
+ run_button_component = gr.Button("Run")
87
+ temperature_component = gr.Slider(minimum=0, maximum=1.0, value=0.4, step=0.05, label="Temperature")
88
+ max_output_tokens_component = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Token limit")
89
+ stop_sequences_component = gr.Textbox(label="Add stop sequence", placeholder="STOP, END")
90
+ top_k_component = gr.Slider(minimum=1, maximum=40, value=32, step=1, label="Top-K")
91
+ top_p_component = gr.Slider(minimum=0, maximum=1, value=1, step=0.01, label="Top-P")
92
+
93
+
94
+ user_inputs = [text_prompt_component, chatbot_component]
95
+ bot_inputs = [google_key_component, image_prompt_component, temperature_component, max_output_tokens_component, stop_sequences_component, top_k_component, top_p_component, chatbot_component]
96
+
97
  with gr.Blocks() as demo:
98
+ gr.HTML(TITLE)
99
+ gr.HTML(SUBTITLE)
100
+ gr.HTML(DUPLICATE)
101
+ with gr.Column():
102
+ google_key_component.render()
103
+ with gr.Row():
104
+ image_prompt_component.render()
105
+ chatbot_component.render()
106
+ text_prompt_component.render()
107
+ run_button_component.render()
108
+ with gr.Accordion("Parameters", open=False):
109
+ temperature_component.render()
110
+ max_output_tokens_component.render()
111
+ stop_sequences_component.render()
112
+ with gr.Accordion("Advanced", open=False):
113
+ top_k_component.render()
114
+ top_p_component.render()
115
 
116
+ run_button_component.click(fn=user, inputs=user_inputs, outputs=[text_prompt_component, chatbot_component], queue=False).then(fn=bot, inputs=bot_inputs, outputs=[chatbot_component])
117
+ text_prompt_component.submit(fn=user, inputs=user_inputs, outputs=[text_prompt_component, chatbot_component], queue=False).then(fn=bot, inputs=bot_inputs, outputs=[chatbot_component])
118
 
119
+ demo.launch()