K00B404 commited on
Commit
85ecc49
·
verified ·
1 Parent(s): 58ac2a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -19
app.py CHANGED
@@ -5,6 +5,7 @@ from PIL import Image
5
  import warnings
6
  import gradio as gr
7
  import os
 
8
 
9
  # Disable warnings for cleaner output
10
  transformers.logging.set_verbosity_error()
@@ -32,6 +33,10 @@ tokenizer = AutoTokenizer.from_pretrained(
32
 
33
  print("Model loaded successfully!")
34
 
 
 
 
 
35
  def analyze_character(image_path, analysis_type):
36
  """
37
  Analyze a character image for dramaturgical insights
@@ -46,6 +51,9 @@ def analyze_character(image_path, analysis_type):
46
  # Load and process image
47
  try:
48
  image = Image.open(image_path).convert('RGB')
 
 
 
49
  image_tensor = model.process_images([image], model.config).to(dtype=model.dtype)
50
  except Exception as e:
51
  return f"Error processing image: {str(e)}"
@@ -118,30 +126,132 @@ def analyze_character(image_path, analysis_type):
118
  except Exception as e2:
119
  return f"Error generating analysis: {str(e)}\nFallback also failed: {str(e2)}\n\nPlease try a different image or check model compatibility."
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  # Create Gradio interface
122
  def create_ui():
123
  with gr.Blocks(title="Dramaturg Character Analyzer") as demo:
124
- gr.Markdown("# Dramaturg Character Analyzer")
125
- gr.Markdown("Upload a character image to receive a dramaturgical analysis")
126
 
127
- with gr.Row():
128
- with gr.Column():
129
- input_image = gr.Image(type="filepath", label="Upload Character Image")
130
- analysis_type = gr.Radio(
131
- ["full_analysis", "archetype", "historical_context", "basic_description"],
132
- label="Analysis Type",
133
- value="full_analysis"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  )
135
- analyze_btn = gr.Button("Analyze Character")
136
 
137
- with gr.Column():
138
- output_text = gr.Textbox(label="Character Analysis", lines=20)
139
-
140
- analyze_btn.click(
141
- fn=analyze_character,
142
- inputs=[input_image, analysis_type],
143
- outputs=output_text
144
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  return demo
147
 
@@ -149,4 +259,4 @@ def create_ui():
149
  if __name__ == "__main__":
150
  demo = create_ui()
151
  demo.launch(share=True)
152
- print("Dramaturg Character Analyzer is now running!")
 
5
  import warnings
6
  import gradio as gr
7
  import os
8
+ from gradio_client import Client
9
 
10
  # Disable warnings for cleaner output
11
  transformers.logging.set_verbosity_error()
 
33
 
34
  print("Model loaded successfully!")
35
 
36
+ # Initialize the client for the test bot
37
+ chatter = "K00B404/transcript_image_generator"
38
+ chatbot_client = Client(chatter)
39
+
40
  def analyze_character(image_path, analysis_type):
41
  """
42
  Analyze a character image for dramaturgical insights
 
51
  # Load and process image
52
  try:
53
  image = Image.open(image_path).convert('RGB')
54
+ # Resize image to 512x512
55
+ image = image.resize((256, 256), Image.Resampling.LANCZOS)
56
+
57
  image_tensor = model.process_images([image], model.config).to(dtype=model.dtype)
58
  except Exception as e:
59
  return f"Error processing image: {str(e)}"
 
126
  except Exception as e2:
127
  return f"Error generating analysis: {str(e)}\nFallback also failed: {str(e2)}\n\nPlease try a different image or check model compatibility."
128
 
129
+ def chat_with_persona(message, history, system_message, max_tokens, temperature, top_p):
130
+ """Function to interact with the chatbot API using the generated persona"""
131
+ try:
132
+ # Call the API with the current message and system prompt (persona)
133
+ response = chatbot_client.predict(
134
+ message=message,
135
+ system_message=system_message,
136
+ max_tokens=max_tokens,
137
+ temperature=temperature,
138
+ top_p=top_p,
139
+ api_name="/chat"
140
+ )
141
+ return response
142
+ except Exception as e:
143
+ return f"Error communicating with the chatbot API: {str(e)}"
144
+
145
  # Create Gradio interface
146
  def create_ui():
147
  with gr.Blocks(title="Dramaturg Character Analyzer") as demo:
148
+ # Store the current analysis result for sharing between tabs
149
+ analysis_result = gr.State("")
150
 
151
+ with gr.Tabs() as tabs:
152
+ # First tab: Character analysis
153
+ with gr.TabItem("Character Analysis"):
154
+ gr.Markdown("# Dramaturg Character Analyzer")
155
+ gr.Markdown("Upload a character image to receive a dramaturgical analysis")
156
+
157
+ with gr.Row():
158
+ with gr.Column():
159
+ input_image = gr.Image(type="filepath", label="Upload Character Image")
160
+ analysis_type = gr.Radio(
161
+ ["full_analysis", "archetype", "historical_context", "basic_description"],
162
+ label="Analysis Type",
163
+ value="full_analysis"
164
+ )
165
+ analyze_btn = gr.Button("Analyze Character")
166
+
167
+ with gr.Column():
168
+ output_text = gr.Textbox(label="Character Analysis", lines=20)
169
+ copy_to_test_btn = gr.Button("Copy to Test Bot", interactive=False)
170
+
171
+ def update_analysis_result(result):
172
+ # Enable the copy button once we have a result
173
+ return result, True
174
+
175
+ analyze_btn.click(
176
+ fn=analyze_character,
177
+ inputs=[input_image, analysis_type],
178
+ outputs=[output_text, copy_to_test_btn]
179
+ )
180
+
181
+ def copy_to_test(result):
182
+ # Update the state and switch to the test tab
183
+ return result, 1
184
+
185
+ copy_to_test_btn.click(
186
+ fn=copy_to_test,
187
+ inputs=[output_text],
188
+ outputs=[analysis_result, tabs]
189
  )
 
190
 
191
+ # Second tab: Test bot integration
192
+ with gr.TabItem("Test Bot"):
193
+ gr.Markdown("# Test Your Character Persona")
194
+ gr.Markdown("The character analysis will be used as the system prompt for the test bot.")
195
+
196
+ with gr.Row():
197
+ with gr.Column():
198
+ system_prompt = gr.Textbox(label="System Prompt (Character Persona)", lines=10)
199
+
200
+ with gr.Row():
201
+ max_tokens = gr.Slider(minimum=100, maximum=4000, value=1000, step=100, label="Max Tokens")
202
+ temperature = gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature")
203
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.1, label="Top P")
204
+
205
+ user_input = gr.Textbox(label="Your message", placeholder="Ask something about the character...")
206
+ send_btn = gr.Button("Send Message")
207
+
208
+ with gr.Column():
209
+ chatbot = gr.Chatbot(label="Conversation")
210
+
211
+ def update_system_prompt(result):
212
+ return result
213
+
214
+ # Update the system prompt when switching to this tab with an analysis result
215
+ demo.load(
216
+ fn=update_system_prompt,
217
+ inputs=[analysis_result],
218
+ outputs=[system_prompt]
219
+ )
220
+
221
+ # Chat history for the test bot
222
+ chat_history = []
223
+
224
+ def respond(message, history, system_message, max_tokens_val, temperature_val, top_p_val):
225
+ # Add the user message to history
226
+ history.append((message, ""))
227
+
228
+ # Get response from the test bot
229
+ response = chat_with_persona(
230
+ message=message,
231
+ history=history,
232
+ system_message=system_message,
233
+ max_tokens=max_tokens_val,
234
+ temperature=temperature_val,
235
+ top_p=top_p_val
236
+ )
237
+
238
+ # Update the last history item with the response
239
+ history[-1] = (message, response)
240
+
241
+ return "", history
242
+
243
+ send_btn.click(
244
+ fn=respond,
245
+ inputs=[user_input, chatbot, system_prompt, max_tokens, temperature, top_p],
246
+ outputs=[user_input, chatbot]
247
+ )
248
+
249
+ # Also trigger on pressing Enter in the input box
250
+ user_input.submit(
251
+ fn=respond,
252
+ inputs=[user_input, chatbot, system_prompt, max_tokens, temperature, top_p],
253
+ outputs=[user_input, chatbot]
254
+ )
255
 
256
  return demo
257
 
 
259
  if __name__ == "__main__":
260
  demo = create_ui()
261
  demo.launch(share=True)
262
+ print("Dramaturg Character Analyzer is now running with Test Bot integration!")