Aitrepreneur
commited on
Commit
•
07c2897
1
Parent(s):
cb644d5
Added Ollama API support
Browse files
app.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1 |
import gradio as gr
|
2 |
import random
|
|
|
3 |
import json
|
4 |
import os
|
5 |
import re
|
@@ -330,19 +331,21 @@ class PromptGenerator:
|
|
330 |
return f"{prompt}, {caption}"
|
331 |
return prompt
|
332 |
|
333 |
-
class
|
334 |
def __init__(self):
|
335 |
#ADD YOUR OWN GROQ API KEY HERE
|
336 |
-
self.
|
337 |
-
self.
|
|
|
338 |
"Llama 3.1 70B": "llama-3.1-70b-versatile",
|
339 |
"Llama 3.1 8B": "llama-3.1-8b-instant"
|
340 |
}
|
|
|
341 |
self.prompts_dir = "./prompts"
|
342 |
os.makedirs(self.prompts_dir, exist_ok=True)
|
343 |
|
344 |
def save_prompt(self, prompt):
|
345 |
-
filename_text = "
|
346 |
filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
|
347 |
filename_text = filename_text[:30]
|
348 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
@@ -354,15 +357,72 @@ class GroqInferenceNode:
|
|
354 |
|
355 |
print(f"Prompt saved to {filename}")
|
356 |
|
357 |
-
def generate(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
|
358 |
try:
|
359 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
360 |
|
361 |
-
|
|
|
362 |
|
363 |
-
|
|
|
364 |
|
365 |
-
|
|
|
|
|
366 |
Title: A catchy, intriguing title that captures the essence of the scene, place the title in "".
|
367 |
Main character: Give a description of the main character.
|
368 |
Background: Describe the background in detail.
|
@@ -372,43 +432,26 @@ Tagline: Include a tagline that captures the essence of the movie.
|
|
372 |
Visual style: Ensure that the visual style fits the branding type and tagline.
|
373 |
You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters."""
|
374 |
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
if compress and not poster:
|
383 |
-
compression_chars = {
|
384 |
-
"soft": 600 if happy_talk else 300,
|
385 |
-
"medium": 400 if happy_talk else 200,
|
386 |
-
"hard": 200 if happy_talk else 100
|
387 |
-
}
|
388 |
-
char_limit = compression_chars[compression_level]
|
389 |
-
base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
|
390 |
-
|
391 |
-
messages = [
|
392 |
-
{"role": "system", "content": "You are a helpful assistant. Try your best to give best response possible to user."},
|
393 |
-
{"role": "user", "content": f"{base_prompt}\nDescription: {input_text}"}
|
394 |
-
]
|
395 |
-
|
396 |
-
print(f"Starting generation with {model_id}...")
|
397 |
-
start_time = time.time()
|
398 |
-
|
399 |
-
chat_completion = self.client.chat.completions.create(
|
400 |
-
messages=messages,
|
401 |
-
model=model_id,
|
402 |
-
max_tokens=4000,
|
403 |
-
temperature=0.7,
|
404 |
-
top_p=0.95
|
405 |
-
)
|
406 |
|
407 |
-
|
408 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
409 |
|
410 |
-
|
411 |
-
|
|
|
|
|
412 |
# Clean up the output
|
413 |
if ": " in output:
|
414 |
output = output.split(": ", 1)[1].strip()
|
@@ -416,12 +459,10 @@ You are allowed to make up film and branding names, and do them like 80's, 90's
|
|
416 |
sentences = output.split(". ")
|
417 |
if len(sentences) > 1:
|
418 |
output = ". ".join(sentences[1:]).strip()
|
419 |
-
|
420 |
return output
|
421 |
-
|
422 |
except Exception as e:
|
423 |
-
print(f"An error occurred: {e}")
|
424 |
-
return f"Error occurred while processing the
|
425 |
|
426 |
title = """<h1 align="center">FLUX Prompt Generator</h1>
|
427 |
<p><center>
|
@@ -435,7 +476,7 @@ title = """<h1 align="center">FLUX Prompt Generator</h1>
|
|
435 |
|
436 |
def create_interface():
|
437 |
prompt_generator = PromptGenerator()
|
438 |
-
|
439 |
|
440 |
with gr.Blocks(theme='bethecloud/storj_theme') as demo:
|
441 |
|
@@ -498,7 +539,9 @@ def create_interface():
|
|
498 |
|
499 |
with gr.Column(scale=2):
|
500 |
with gr.Accordion("Prompt Generation with LLM", open=False):
|
501 |
-
|
|
|
|
|
502 |
happy_talk = gr.Checkbox(label="Happy Talk", value=True)
|
503 |
compress = gr.Checkbox(label="Compress", value=True)
|
504 |
compression_level = gr.Radio(["soft", "medium", "hard"], label="Compression Level", value="hard")
|
@@ -532,17 +575,35 @@ def create_interface():
|
|
532 |
outputs=[output]
|
533 |
)
|
534 |
|
535 |
-
def generate_text_with_model(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt):
|
536 |
-
print(f"Generating text with model: {model}")
|
537 |
-
output =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
538 |
print("Generation completed.")
|
539 |
return output
|
540 |
|
541 |
generate_text_button.click(
|
542 |
generate_text_with_model,
|
543 |
-
inputs=[model, output, happy_talk, compress, compression_level, poster, custom_base_prompt],
|
544 |
outputs=text_output
|
545 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
546 |
|
547 |
def update_all_options(choice):
|
548 |
updates = {}
|
@@ -582,5 +643,4 @@ def create_interface():
|
|
582 |
if __name__ == "__main__":
|
583 |
print("FLUX Prompt Generator Initialized! HAVE FUN :)")
|
584 |
demo = create_interface()
|
585 |
-
demo.launch()
|
586 |
-
|
|
|
1 |
import gradio as gr
|
2 |
import random
|
3 |
+
import requests
|
4 |
import json
|
5 |
import os
|
6 |
import re
|
|
|
331 |
return f"{prompt}, {caption}"
|
332 |
return prompt
|
333 |
|
334 |
+
class InferenceNode:
|
335 |
def __init__(self):
|
336 |
#ADD YOUR OWN GROQ API KEY HERE
|
337 |
+
self.groq_client = Groq(api_key="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")
|
338 |
+
self.groq_models = {
|
339 |
+
"Mixtral 8x7B": "mixtral-8x7b-32768",
|
340 |
"Llama 3.1 70B": "llama-3.1-70b-versatile",
|
341 |
"Llama 3.1 8B": "llama-3.1-8b-instant"
|
342 |
}
|
343 |
+
self.ollama_url = "http://localhost:11434/api/generate"
|
344 |
self.prompts_dir = "./prompts"
|
345 |
os.makedirs(self.prompts_dir, exist_ok=True)
|
346 |
|
347 |
def save_prompt(self, prompt):
|
348 |
+
filename_text = "inference_" + prompt.split(',')[0].strip()
|
349 |
filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
|
350 |
filename_text = filename_text[:30]
|
351 |
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
357 |
|
358 |
print(f"Prompt saved to {filename}")
|
359 |
|
360 |
+
def generate(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt="", use_ollama=False):
|
361 |
try:
|
362 |
+
if use_ollama:
|
363 |
+
return self.generate_ollama(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt)
|
364 |
+
else:
|
365 |
+
return self.generate_groq(model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt)
|
366 |
+
except Exception as e:
|
367 |
+
print(f"An error occurred: {e}")
|
368 |
+
return f"Error occurred while processing the request: {str(e)}"
|
369 |
+
|
370 |
+
def generate_groq(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
|
371 |
+
model_id = self.groq_models.get(model, "llama-3.1-8b-instant")
|
372 |
+
|
373 |
+
base_prompt = self.get_base_prompt(happy_talk, compress, compression_level, poster, custom_base_prompt)
|
374 |
+
|
375 |
+
messages = [
|
376 |
+
{"role": "system", "content": "You are a helpful assistant. Try your best to give best response possible to user."},
|
377 |
+
{"role": "user", "content": f"{base_prompt}\nDescription: {input_text}"}
|
378 |
+
]
|
379 |
+
|
380 |
+
print(f"Starting generation with Groq {model_id}...")
|
381 |
+
start_time = time.time()
|
382 |
+
|
383 |
+
chat_completion = self.groq_client.chat.completions.create(
|
384 |
+
messages=messages,
|
385 |
+
model=model_id,
|
386 |
+
max_tokens=4000,
|
387 |
+
temperature=0.7,
|
388 |
+
top_p=0.95
|
389 |
+
)
|
390 |
+
|
391 |
+
end_time = time.time()
|
392 |
+
print(f"Generation completed in {end_time - start_time:.2f} seconds")
|
393 |
+
|
394 |
+
output = chat_completion.choices[0].message.content
|
395 |
+
return self.clean_output(output)
|
396 |
+
|
397 |
+
def generate_ollama(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
|
398 |
+
base_prompt = self.get_base_prompt(happy_talk, compress, compression_level, poster, custom_base_prompt)
|
399 |
+
|
400 |
+
prompt = f"{base_prompt}\nDescription: {input_text}"
|
401 |
+
|
402 |
+
data = {
|
403 |
+
"model": model,
|
404 |
+
"prompt": prompt,
|
405 |
+
"stream": False
|
406 |
+
}
|
407 |
+
|
408 |
+
print(f"Starting generation with Ollama {model}...")
|
409 |
+
start_time = time.time()
|
410 |
+
|
411 |
+
response = requests.post(self.ollama_url, json=data)
|
412 |
+
response.raise_for_status()
|
413 |
+
|
414 |
+
end_time = time.time()
|
415 |
+
print(f"Generation completed in {end_time - start_time:.2f} seconds")
|
416 |
|
417 |
+
output = response.json()["response"]
|
418 |
+
return self.clean_output(output)
|
419 |
|
420 |
+
def get_base_prompt(self, happy_talk, compress, compression_level, poster, custom_base_prompt):
|
421 |
+
default_happy_prompt = """Create a detailed visually descriptive caption of this description, which will be used as a prompt for a text to image AI system (caption only, no instructions like "create an image").Remove any mention of digital artwork or artwork style. Give detailed visual descriptions of the character(s), including ethnicity, skin tone, expression etc. Imagine using keywords for a still for someone who has aphantasia. Describe the image style, e.g. any photographic or art styles / techniques utilized. Make sure to fully describe all aspects of the cinematography, with abundant technical details and visual descriptions. If there is more than one image, combine the elements and characters from all of the images creatively into a single cohesive composition with a single background, inventing an interaction between the characters. Be creative in combining the characters into a single cohesive scene. Focus on two primary characters (or one) and describe an interesting interaction between them, such as a hug, a kiss, a fight, giving an object, an emotional reaction / interaction. If there is more than one background in the images, pick the most appropriate one. Your output is only the caption itself, no comments or extra formatting. The caption is in a single long paragraph. If you feel the images are inappropriate, invent a new scene / characters inspired by these. Additionally, incorporate a specific movie director's visual style and describe the lighting setup in detail, including the type, color, and placement of light sources to create the desired mood and atmosphere. Always frame the scene, including details about the film grain, color grading, and any artifacts or characteristics specific."""
|
422 |
|
423 |
+
default_simple_prompt = """Create a brief, straightforward caption for this description, suitable for a text-to-image AI system. Focus on the main elements, key characters, and overall scene without elaborate details. Provide a clear and concise description in one or two sentences."""
|
424 |
+
|
425 |
+
poster_prompt = """Analyze the provided description and extract key information to create a movie poster style description. Format the output as follows:
|
426 |
Title: A catchy, intriguing title that captures the essence of the scene, place the title in "".
|
427 |
Main character: Give a description of the main character.
|
428 |
Background: Describe the background in detail.
|
|
|
432 |
Visual style: Ensure that the visual style fits the branding type and tagline.
|
433 |
You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters."""
|
434 |
|
435 |
+
if poster:
|
436 |
+
base_prompt = poster_prompt
|
437 |
+
elif custom_base_prompt.strip():
|
438 |
+
base_prompt = custom_base_prompt
|
439 |
+
else:
|
440 |
+
base_prompt = default_happy_prompt if happy_talk else default_simple_prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
441 |
|
442 |
+
if compress and not poster:
|
443 |
+
compression_chars = {
|
444 |
+
"soft": 600 if happy_talk else 300,
|
445 |
+
"medium": 400 if happy_talk else 200,
|
446 |
+
"hard": 200 if happy_talk else 100
|
447 |
+
}
|
448 |
+
char_limit = compression_chars[compression_level]
|
449 |
+
base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
|
450 |
|
451 |
+
return base_prompt
|
452 |
+
|
453 |
+
def clean_output(self, output):
|
454 |
+
try:
|
455 |
# Clean up the output
|
456 |
if ": " in output:
|
457 |
output = output.split(": ", 1)[1].strip()
|
|
|
459 |
sentences = output.split(". ")
|
460 |
if len(sentences) > 1:
|
461 |
output = ". ".join(sentences[1:]).strip()
|
|
|
462 |
return output
|
|
|
463 |
except Exception as e:
|
464 |
+
print(f"An error occurred while cleaning output: {e}")
|
465 |
+
return f"Error occurred while processing the output: {str(e)}"
|
466 |
|
467 |
title = """<h1 align="center">FLUX Prompt Generator</h1>
|
468 |
<p><center>
|
|
|
476 |
|
477 |
def create_interface():
|
478 |
prompt_generator = PromptGenerator()
|
479 |
+
inference_node = InferenceNode()
|
480 |
|
481 |
with gr.Blocks(theme='bethecloud/storj_theme') as demo:
|
482 |
|
|
|
539 |
|
540 |
with gr.Column(scale=2):
|
541 |
with gr.Accordion("Prompt Generation with LLM", open=False):
|
542 |
+
use_ollama = gr.Checkbox(label="Use Ollama (local)", value=False)
|
543 |
+
model = gr.Dropdown(["Mixtral 8x7B", "Llama 3.1 70B", "Llama 3.1 8B"], label="Groq Model", value="Llama 3.1 8B")
|
544 |
+
ollama_model = gr.Textbox(label="Ollama Model Name", value="llama3", visible=False)
|
545 |
happy_talk = gr.Checkbox(label="Happy Talk", value=True)
|
546 |
compress = gr.Checkbox(label="Compress", value=True)
|
547 |
compression_level = gr.Radio(["soft", "medium", "hard"], label="Compression Level", value="hard")
|
|
|
575 |
outputs=[output]
|
576 |
)
|
577 |
|
578 |
+
def generate_text_with_model(use_ollama, model, ollama_model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt):
|
579 |
+
print(f"Generating text with {'Ollama' if use_ollama else 'Groq'} model: {ollama_model if use_ollama else model}")
|
580 |
+
output = inference_node.generate(
|
581 |
+
ollama_model if use_ollama else model,
|
582 |
+
input_text,
|
583 |
+
happy_talk,
|
584 |
+
compress,
|
585 |
+
compression_level,
|
586 |
+
poster,
|
587 |
+
custom_base_prompt,
|
588 |
+
use_ollama
|
589 |
+
)
|
590 |
print("Generation completed.")
|
591 |
return output
|
592 |
|
593 |
generate_text_button.click(
|
594 |
generate_text_with_model,
|
595 |
+
inputs=[use_ollama, model, ollama_model, output, happy_talk, compress, compression_level, poster, custom_base_prompt],
|
596 |
outputs=text_output
|
597 |
)
|
598 |
+
|
599 |
+
def toggle_model_input(use_ollama):
|
600 |
+
return gr.update(visible=use_ollama), gr.update(visible=not use_ollama)
|
601 |
+
|
602 |
+
use_ollama.change(
|
603 |
+
toggle_model_input,
|
604 |
+
inputs=[use_ollama],
|
605 |
+
outputs=[ollama_model, model]
|
606 |
+
)
|
607 |
|
608 |
def update_all_options(choice):
|
609 |
updates = {}
|
|
|
643 |
if __name__ == "__main__":
|
644 |
print("FLUX Prompt Generator Initialized! HAVE FUN :)")
|
645 |
demo = create_interface()
|
646 |
+
demo.launch()
|
|