Rahatara commited on
Commit
a432f42
·
verified ·
1 Parent(s): ba459e3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -120
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import os
2
  import time
3
  from typing import List, Tuple, Optional
4
 
@@ -6,11 +5,22 @@ import google.generativeai as genai
6
  import gradio as gr
7
  from PIL import Image
8
 
9
- # Ensure Google API Key is set
 
10
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
11
 
12
- TITLE = """<h1 align="center">☕ Espresso with LeProf 🔥</h1>"""
13
- SUBTITLE = """<h2 align="center">🌟 Knowledge Shots for Curious Minds</h2>"""
 
 
 
 
 
 
 
 
 
 
14
 
15
  IMAGE_WIDTH = 512
16
 
@@ -22,7 +32,6 @@ def preprocess_image(image: Image.Image) -> Image.Image:
22
  return image.resize((IMAGE_WIDTH, image_height))
23
 
24
  def user(text_prompt: str, chatbot: List[Tuple[str, str]]):
25
- """Handles user input and appends to the chatbot."""
26
  return "", chatbot + [[text_prompt, None]]
27
 
28
  def bot(
@@ -33,27 +42,13 @@ def bot(
33
  stop_sequences: str,
34
  top_k: int,
35
  top_p: float,
36
- topic: str,
37
- chatbot: List[Tuple[str, str]],
38
  ):
39
- """Generates a response using Google Gemini."""
40
  google_key = google_key or GOOGLE_API_KEY
41
  if not google_key:
42
  raise ValueError("GOOGLE_API_KEY is not set. Please set it up.")
43
- if not topic:
44
- raise ValueError("Topic is not set. Please provide a topic.")
45
 
46
- # Get the user's input
47
  text_prompt = chatbot[-1][0]
48
-
49
- # Construct the system prompt
50
- analysis_system_prompt = (
51
- f"You are an expert in {topic}. Analyze the provided text with a focus on {topic}, "
52
- "identifying recent issues, insights, or improvements relevant to academic standards and effectiveness. "
53
- "Offer actionable advice for enhancing knowledge and provide real-life examples."
54
- )
55
-
56
- # Configure Generative AI model
57
  genai.configure(api_key=google_key)
58
  generation_config = genai.types.GenerationConfig(
59
  temperature=temperature,
@@ -61,122 +56,63 @@ def bot(
61
  stop_sequences=preprocess_stop_sequences(stop_sequences),
62
  top_k=top_k,
63
  top_p=top_p,
 
64
  )
65
 
66
- model_name = "gemini-1.5-pro-latest"
67
  model = genai.GenerativeModel(model_name)
 
 
 
 
68
 
69
- try:
70
- # Pass the system prompt and user input as a single prompt
71
- response = model.generate_content(
72
- prompt=analysis_system_prompt,
73
- input=text_prompt,
74
- generation_config=generation_config,
75
- )
76
- except KeyError as e:
77
- raise KeyError(f"Error in response generation: {e}")
78
-
79
- # Process and stream the response
80
  chatbot[-1][1] = ""
81
  for chunk in response:
82
  for i in range(0, len(chunk.text), 10):
83
- chatbot[-1][1] += chunk.text[i : i + 10]
84
  time.sleep(0.01)
85
  yield chatbot
86
 
87
- # Gradio Components
88
  google_key_component = gr.Textbox(
89
  label="GOOGLE API KEY",
90
  type="password",
91
- placeholder="Enter your API key...",
92
- visible=GOOGLE_API_KEY is None,
93
  )
94
 
95
- topic_input = gr.Textbox(label="Set the Topic", placeholder="e.g., AI in Education, Human-Computer Interaction")
96
- text_prompt_component = gr.Textbox(label="Ask LeProf", placeholder="Type your question here...")
97
- chatbot_component = gr.Chatbot(label="LeProf says")
98
- run_button_component = gr.Button("🫗 Get Your Knowledge Shot")
99
-
100
- example_data = [
101
- ["AI in Education", "What are the challenges in AI tools for personalized learning?"],
102
- ["Multimedia Accessibility", "How can multimedia be made more accessible to people with disabilities?"],
103
- ["Ethical AI", "What are the ethical implications of AI in social media content moderation?"],
104
- ["Virtual Reality", "How does virtual reality improve skill training in industries?"],
105
- ["Augmented Reality", "What are the UX challenges in augmented reality for urban navigation?"],
106
- ]
107
-
108
- # Advanced Settings
109
- temperature_component = gr.Slider(
110
- minimum=0, maximum=1.0, value=0.4, step=0.05, label="Creativity Level"
111
- )
112
- max_output_tokens_component = gr.Slider(
113
- minimum=1, maximum=2048, value=1024, step=1, label="Max Tokens"
114
- )
115
- stop_sequences_component = gr.Textbox(label="Stop Sequences", placeholder="e.g., STOP, END")
116
- top_k_component = gr.Slider(
117
- minimum=1, maximum=40, value=32, step=1, label="Top-K Sampling"
118
- )
119
- top_p_component = gr.Slider(
120
- minimum=0, maximum=1.0, value=1.0, step=0.01, label="Top-P Sampling"
121
- )
122
 
123
- # Layout with Gradio Blocks
124
  with gr.Blocks() as demo:
125
  gr.HTML(TITLE)
126
  gr.HTML(SUBTITLE)
127
- google_key_component.render()
128
- topic_input.render()
129
- chatbot_component.render()
130
- text_prompt_component.render()
131
- gr.Examples(
132
- examples=example_data,
133
- inputs=[topic_input, text_prompt_component],
134
- label="Example Questions",
135
- )
136
- run_button_component.render()
137
- with gr.Accordion("Parameters", open=False):
138
- temperature_component.render()
139
- max_output_tokens_component.render()
140
- stop_sequences_component.render()
141
- with gr.Accordion("Advanced Settings", open=False):
142
- top_k_component.render()
143
- top_p_component.render()
144
-
145
- # Event Handlers
146
- run_button_component.click(
147
- fn=user, inputs=[text_prompt_component, chatbot_component], outputs=[text_prompt_component, chatbot_component], queue=False
148
- ).then(
149
- fn=bot,
150
- inputs=[
151
- google_key_component,
152
- None, # Placeholder for image_prompt (not used in this example)
153
- temperature_component,
154
- max_output_tokens_component,
155
- stop_sequences_component,
156
- top_k_component,
157
- top_p_component,
158
- topic_input,
159
- chatbot_component,
160
- ],
161
- outputs=[chatbot_component]
162
- )
163
- text_prompt_component.submit(
164
- fn=user, inputs=[text_prompt_component, chatbot_component], outputs=[text_prompt_component, chatbot_component], queue=False
165
- ).then(
166
- fn=bot,
167
- inputs=[
168
- google_key_component,
169
- None, # Placeholder for image_prompt (not used in this example)
170
- temperature_component,
171
- max_output_tokens_component,
172
- stop_sequences_component,
173
- top_k_component,
174
- top_p_component,
175
- topic_input,
176
- chatbot_component,
177
- ],
178
- outputs=[chatbot_component]
179
- )
180
-
181
- # Launch the App
182
- demo.launch()
 
 
1
  import time
2
  from typing import List, Tuple, Optional
3
 
 
5
  import gradio as gr
6
  from PIL import Image
7
 
8
+ print("google-generativeai:", genai.__version__)
9
+
10
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
11
 
12
+ TITLE = """<h1 align="center">🕹️ Google Gemini Chatbot 🔥</h1>"""
13
+ SUBTITLE = """<h2 align="center">🎨Create with Multimodal Gemini</h2>"""
14
+ DUPLICATE = """
15
+ <div style="text-align: center; display: flex; justify-content: center; align-items: center;">
16
+ <a href="https://huggingface.co/spaces/Rahatara/build_with_gemini/blob/main/allgemapp.py?duplicate=true">
17
+ <img src="https://bit.ly/3gLdBN6" alt="Duplicate Space" style="margin-right: 10px;">
18
+ </a>
19
+ <span>Duplicate the Space and run securely with your
20
+ <a href="https://makersuite.google.com/app/apikey">GOOGLE API KEY</a>.
21
+ </span>
22
+ </div>
23
+ """
24
 
25
  IMAGE_WIDTH = 512
26
 
 
32
  return image.resize((IMAGE_WIDTH, image_height))
33
 
34
  def user(text_prompt: str, chatbot: List[Tuple[str, str]]):
 
35
  return "", chatbot + [[text_prompt, None]]
36
 
37
  def bot(
 
42
  stop_sequences: str,
43
  top_k: int,
44
  top_p: float,
45
+ chatbot: List[Tuple[str, str]]
 
46
  ):
 
47
  google_key = google_key or GOOGLE_API_KEY
48
  if not google_key:
49
  raise ValueError("GOOGLE_API_KEY is not set. Please set it up.")
 
 
50
 
 
51
  text_prompt = chatbot[-1][0]
 
 
 
 
 
 
 
 
 
52
  genai.configure(api_key=google_key)
53
  generation_config = genai.types.GenerationConfig(
54
  temperature=temperature,
 
56
  stop_sequences=preprocess_stop_sequences(stop_sequences),
57
  top_k=top_k,
58
  top_p=top_p,
59
+ #instructions = "You are an expert stylist"
60
  )
61
 
62
+ model_name = "gemini-1.5-pro-latest"
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
+ user_inputs = [text_prompt_component, chatbot_component]
94
+ 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]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
 
96
  with gr.Blocks() as demo:
97
  gr.HTML(TITLE)
98
  gr.HTML(SUBTITLE)
99
+ gr.HTML(DUPLICATE)
100
+ with gr.Column():
101
+ google_key_component.render()
102
+ with gr.Row():
103
+ image_prompt_component.render()
104
+ chatbot_component.render()
105
+ text_prompt_component.render()
106
+ run_button_component.render()
107
+ with gr.Accordion("Parameters", open=False):
108
+ temperature_component.render()
109
+ max_output_tokens_component.render()
110
+ stop_sequences_component.render()
111
+ with gr.Accordion("Advanced", open=False):
112
+ top_k_component.render()
113
+ top_p_component.render()
114
+
115
+ 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])
116
+ 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])
117
+ demo.launch()
118
+ -i wanted my custom app to be functional like this one. Fux my code taking Reference then apply my customization for le prof one . I have utilized system instructions there. And more modifications as discussed