RanM commited on
Commit
30d89b1
·
verified ·
1 Parent(s): d9a5760

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -10
app.py CHANGED
@@ -4,21 +4,20 @@ from generate_prompts import generate_prompt
4
  from diffusers import AutoPipelineForText2Image
5
  from io import BytesIO
6
  import gradio as gr
7
- from multiprocessing import Pool, current_process
8
 
9
- def load_model():
10
- print(f"Loading model in process {current_process().name}")
11
- model = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo")
12
- print(f"Model loaded in process {current_process().name}")
13
- return model
14
 
15
  def generate_image(prompt, prompt_name):
16
  try:
17
- model = load_model()
18
  print(f"Generating response for {prompt_name} with prompt: {prompt}")
19
  output = model(prompt=prompt, num_inference_steps=1, guidance_scale=0.0)
20
  print(f"Output for {prompt_name}: {output}")
21
 
 
22
  if isinstance(output.images, list) and len(output.images) > 0:
23
  image = output.images[0]
24
  buffered = BytesIO()
@@ -40,6 +39,7 @@ async def queue_api_calls(sentence_mapping, character_dict, selected_style):
40
  print(f"queue_api_calls invoked with sentence_mapping: {sentence_mapping}, character_dict: {character_dict}, selected_style: {selected_style}")
41
  prompts = []
42
 
 
43
  for paragraph_number, sentences in sentence_mapping.items():
44
  combined_sentence = " ".join(sentences)
45
  print(f"combined_sentence for paragraph {paragraph_number}: {combined_sentence}")
@@ -47,10 +47,15 @@ async def queue_api_calls(sentence_mapping, character_dict, selected_style):
47
  prompts.append((paragraph_number, prompt))
48
  print(f"Generated prompt for paragraph {paragraph_number}: {prompt}")
49
 
50
- with Pool() as pool:
51
- tasks = [(prompt, f"Prompt {paragraph_number}") for paragraph_number, prompt in prompts]
 
 
 
 
 
52
  print("Tasks created for image generation.")
53
- responses = pool.starmap(generate_image, tasks)
54
  print("Responses received from image generation tasks.")
55
 
56
  images = {paragraph_number: response for (paragraph_number, _), response in zip(prompts, responses)}
@@ -60,16 +65,20 @@ async def queue_api_calls(sentence_mapping, character_dict, selected_style):
60
  def process_prompt(sentence_mapping, character_dict, selected_style):
61
  print(f"process_prompt called with sentence_mapping: {sentence_mapping}, character_dict: {character_dict}, selected_style: {selected_style}")
62
  try:
 
63
  loop = asyncio.get_running_loop()
64
  except RuntimeError:
 
65
  loop = asyncio.new_event_loop()
66
  asyncio.set_event_loop(loop)
67
  print("Event loop created.")
68
 
 
69
  cmpt_return = loop.run_until_complete(queue_api_calls(sentence_mapping, character_dict, selected_style))
70
  print(f"process_prompt completed with return value: {cmpt_return}")
71
  return cmpt_return
72
 
 
73
  gradio_interface = gr.Interface(
74
  fn=process_prompt,
75
  inputs=[
 
4
  from diffusers import AutoPipelineForText2Image
5
  from io import BytesIO
6
  import gradio as gr
7
+ from concurrent.futures import ThreadPoolExecutor
8
 
9
+ # Load the model once outside of the function
10
+ print("Loading the model...")
11
+ model = AutoPipelineForText2Image.from_pretrained("stabilityai/sdxl-turbo")
12
+ print("Model loaded successfully.")
 
13
 
14
  def generate_image(prompt, prompt_name):
15
  try:
 
16
  print(f"Generating response for {prompt_name} with prompt: {prompt}")
17
  output = model(prompt=prompt, num_inference_steps=1, guidance_scale=0.0)
18
  print(f"Output for {prompt_name}: {output}")
19
 
20
+ # Check if the model returned images
21
  if isinstance(output.images, list) and len(output.images) > 0:
22
  image = output.images[0]
23
  buffered = BytesIO()
 
39
  print(f"queue_api_calls invoked with sentence_mapping: {sentence_mapping}, character_dict: {character_dict}, selected_style: {selected_style}")
40
  prompts = []
41
 
42
+ # Generate prompts for each paragraph
43
  for paragraph_number, sentences in sentence_mapping.items():
44
  combined_sentence = " ".join(sentences)
45
  print(f"combined_sentence for paragraph {paragraph_number}: {combined_sentence}")
 
47
  prompts.append((paragraph_number, prompt))
48
  print(f"Generated prompt for paragraph {paragraph_number}: {prompt}")
49
 
50
+ # Set max_workers to the total number of prompts
51
+ max_workers = len(prompts)
52
+
53
+ # Generate images for each prompt in parallel using threading
54
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
55
+ loop = asyncio.get_running_loop()
56
+ tasks = [loop.run_in_executor(executor, generate_image, prompt, f"Prompt {paragraph_number}") for paragraph_number, prompt in prompts]
57
  print("Tasks created for image generation.")
58
+ responses = await asyncio.gather(*tasks)
59
  print("Responses received from image generation tasks.")
60
 
61
  images = {paragraph_number: response for (paragraph_number, _), response in zip(prompts, responses)}
 
65
  def process_prompt(sentence_mapping, character_dict, selected_style):
66
  print(f"process_prompt called with sentence_mapping: {sentence_mapping}, character_dict: {character_dict}, selected_style: {selected_style}")
67
  try:
68
+ # See if there is a loop already running. If there is, reuse it.
69
  loop = asyncio.get_running_loop()
70
  except RuntimeError:
71
+ # Create new event loop if one is not running
72
  loop = asyncio.new_event_loop()
73
  asyncio.set_event_loop(loop)
74
  print("Event loop created.")
75
 
76
+ # This sends the prompts to function that sets up the async calls. Once all the calls to the API complete, it returns a list of the gr.Textbox with value= set.
77
  cmpt_return = loop.run_until_complete(queue_api_calls(sentence_mapping, character_dict, selected_style))
78
  print(f"process_prompt completed with return value: {cmpt_return}")
79
  return cmpt_return
80
 
81
+ # Gradio interface with high concurrency limit
82
  gradio_interface = gr.Interface(
83
  fn=process_prompt,
84
  inputs=[