Rahatara commited on
Commit
86e6019
·
verified ·
1 Parent(s): 258e5c8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -0
app.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
26
+ IMAGE_WIDTH = 512
27
+
28
+ def preprocess_stop_sequences(stop_sequences: str) -> Optional[List[str]]:
29
+ return [seq.strip() for seq in stop_sequences.split(",")] if stop_sequences else None
30
+
31
+ def preprocess_image(image: Image.Image) -> Image.Image:
32
+ image_height = int(image.height * IMAGE_WIDTH / image.width)
33
+ return image.resize((IMAGE_WIDTH, image_height))
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
+ text_prompt: str,
42
+ temperature: float,
43
+ max_output_tokens: int,
44
+ stop_sequences: str,
45
+ top_k: int,
46
+ top_p: float,
47
+ chatbot: List[Tuple[str, str]]
48
+ ):
49
+ google_key = google_key or GOOGLE_API_KEY
50
+ if not google_key:
51
+ raise ValueError("GOOGLE_API_KEY is not set. Please set it up.")
52
+
53
+ genai.configure(api_key=google_key)
54
+ instructions = "You are an expert stylist. You suggest and evaluate any style-related question to make anyone, regardless of gender, race, or any other demographic diversity, look stylish."
55
+ model_name = 'gemini-pro-vision' if image_prompt else 'gemini-1.5-pro-latest'
56
+
57
+ inputs = [text_prompt, instructions]
58
+ if image_prompt:
59
+ inputs.append(preprocess_image(image_prompt))
60
+
61
+ model = genai.GenerativeModel(model_name)
62
+ response = model.generate_content(inputs, stream=True, generation_config=genai.types.GenerationConfig(
63
+ temperature=temperature,
64
+ max_output_tokens=max_output_tokens,
65
+ stop_sequences=preprocess_stop_sequences(stop_sequences),
66
+ top_k=top_k,
67
+ top_p=top_p
68
+ ))
69
+
70
+ response.resolve()
71
+
72
+ chatbot[-1][1] = ""
73
+ for chunk in response:
74
+ for i in range(0, len(chunk.text), 10):
75
+ chatbot[-1][1] += chunk.text[i:i + 10]
76
+ time.sleep(0.01)
77
+ yield chatbot
78
+
79
+ google_key_component = gr.Textbox(
80
+ label="GOOGLE API KEY",
81
+ type="password",
82
+ placeholder="Enter your Google API Key",
83
+ visible=GOOGLE_API_KEY is None
84
+ )
85
+
86
+ image_prompt_component = gr.Image(type="pil", label="Upload Image", width=200)
87
+ text_prompt_component = gr.Textbox(
88
+ placeholder="Describe your style needs",
89
+ label="Enter your prompt",
90
+ width=300
91
+ )
92
+ run_button_component = gr.Button("Ask Stylist")
93
+
94
+ temperature_component = gr.Slider(minimum=0, maximum=1.0, value=0.4, step=0.05, label="Temperature")
95
+ max_output_tokens_component = gr.Slider(minimum=1, maximum=2048, value=1024, step=1, label="Token limit")
96
+ stop_sequences_component = gr.Textbox(label="Add stop sequence", placeholder="STOP, END")
97
+ top_k_component = gr.Slider(minimum=1, maximum=40, value=32, step=1, label="Top-K")
98
+ top_p_component = gr.Slider(minimum=0, maximum=1, value=1, step=0.01, label="Top-P")
99
+
100
+ user_inputs = [text_prompt_component, chatbot_component]
101
+ bot_inputs = [google_key_component, image_prompt_component, text_prompt_component, temperature_component, max_output_tokens_component, stop_sequences_component, top_k_component, top_p_component, chatbot_component]
102
+
103
+ with gr.Blocks() as demo:
104
+ gr.HTML(TITLE)
105
+ gr.HTML(SUBTITLE)
106
+ gr.HTML(DUPLICATE)
107
+ with gr.Row():
108
+ google_key_component.render()
109
+ with gr.Row():
110
+ text_prompt_component.render()
111
+ image_prompt_component.render()
112
+ chatbot_component = gr.Chatbot(label='Gemini Personal Stylist')
113
+ chatbot_component.render()
114
+ run_button_component.render()
115
+ with gr.Accordion("Parameters", open=False):
116
+ temperature_component.render()
117
+ max_output_tokens_component.render()
118
+ stop_sequences_component.render()
119
+ with gr.Accordion("Advanced", open=False):
120
+ top_k_component.render()
121
+ top_p_component.render()
122
+
123
+ run_button_component.click(
124
+ fn=user,
125
+ inputs=user_inputs,
126
+ outputs=[text_prompt_component, chatbot_component],
127
+ queue=False
128
+ ).then(
129
+ fn=bot, inputs=bot_inputs, outputs=[chatbot_component]
130
+ )
131
+
132
+ text_prompt_component.submit(
133
+ fn=user,
134
+ inputs=user_inputs,
135
+ outputs=[text_prompt_component, chatbot_component],
136
+ queue=False
137
+ ).then(
138
+ fn=bot, inputs=bot_inputs, outputs=[chatbot_component]
139
+ )
140
+
141
+ demo.launch()