gokaygokay commited on
Commit
95bdd33
1 Parent(s): 2dd5330

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -35
app.py CHANGED
@@ -3,8 +3,8 @@ import random
3
  import json
4
  import os
5
  import re
6
- from openai import OpenAI
7
  from datetime import datetime
 
8
 
9
  # Load JSON files
10
  def load_json_file(file_name):
@@ -259,14 +259,19 @@ class PromptGenerator:
259
 
260
  return self.process_string(replaced, seed)
261
 
262
- class GPT4MiniNode:
263
  def __init__(self):
264
- self.client = None
 
 
 
 
 
265
  self.prompts_dir = "./prompts"
266
  os.makedirs(self.prompts_dir, exist_ok=True)
267
 
268
  def save_prompt(self, prompt):
269
- filename_text = "mini_" + prompt.split(',')[0].strip()
270
  filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
271
  filename_text = filename_text[:30]
272
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
@@ -278,9 +283,9 @@ class GPT4MiniNode:
278
 
279
  print(f"Prompt saved to {filename}")
280
 
281
- def generate(self, api_key, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
282
  try:
283
- self.client = OpenAI(api_key=api_key)
284
 
285
  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 (e.g. Wes Anderson, Christopher Nolan, Quentin Tarantino) 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 as a screen grab from a 35mm film still, including details about the film grain, color grading, and any artifacts or characteristics specific to 35mm film photography."""
286
 
@@ -295,23 +300,7 @@ Supporting characters: Describe the supporting characters
295
  Branding type: Describe the branding type
296
  Tagline: Include a tagline that captures the essence of the movie.
297
  Visual style: Ensure that the visual style fits the branding type and tagline.
298
- You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters.
299
-
300
- Never add ** in front of title, main character, etc.
301
- Here is an example of a prompt, make the output like a movie poster:
302
- Title: Display the title "Verdant Spirits" in elegant and ethereal text, placed centrally at the top of the poster.
303
-
304
- Main Character: Depict a serene and enchantingly beautiful woman with an aura of nature, her face partly adorned and encased with vibrant green foliage and delicate floral arrangements. She exudes an ethereal and mystical presence.
305
-
306
- Background: The background should feature a dreamlike enchanted forest with lush greenery, vibrant flowers, and an ethereal glow emanating from the foliage. The scene should feel magical and otherworldly, suggesting a hidden world within nature.
307
-
308
- Supporting Characters: Add an enigmatic skeletal figure entwined with glowing, bioluminescent leaves and plants, subtly blending with the dark, verdant background. This figure should evoke a sense of ancient wisdom and mysterious energy.
309
-
310
- Studio Ghibli Branding: Incorporate the Studio Ghibli logo at the bottom center of the poster to establish it as an official Ghibli film.
311
-
312
- Tagline: Include a tagline that reads: "Where Nature's Secrets Come to Life" prominently on the poster.
313
-
314
- Visual Style: Ensure the overall visual style is consistent with Studio Ghibli s signature look rich, detailed backgrounds, and characters imbued with a touch of whimsy and mystery. The colors should be lush and inviting, with an emphasis on the enchanting and mystical aspects of nature."""
315
 
316
  if poster:
317
  base_prompt = poster_prompt
@@ -329,21 +318,24 @@ Visual Style: Ensure the overall visual style is consistent with Studio Ghibli s
329
  char_limit = compression_chars[compression_level]
330
  base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
331
 
332
- response = self.client.chat.completions.create(
333
- model="gpt-4o-mini",
334
- messages=[{"role": "user", "content": f"{base_prompt}\nDescription: {input_text}"}],
335
- )
 
 
 
 
336
 
337
- result = response.choices[0].message.content
338
- self.save_prompt(result)
339
- return result
340
  except Exception as e:
341
  print(f"An error occurred: {e}")
342
  return f"Error occurred while processing the request: {str(e)}"
343
 
344
  def create_interface():
345
  prompt_generator = PromptGenerator()
346
- gpt4_mini_node = GPT4MiniNode()
347
 
348
  with gr.Blocks() as demo:
349
  gr.Markdown("# AI Prompt Generator and Text Generator")
@@ -389,8 +381,8 @@ def create_interface():
389
  outputs=[output, gr.Number(visible=False), t5xxl_output, clip_l_output, clip_g_output]
390
  )
391
 
392
- with gr.Tab("GPT4 Mini Text Generator"):
393
- api_key = gr.Textbox(label="OpenAI API Key", type="password", placeholder="Enter your OpenAI API key")
394
  input_text = gr.Textbox(label="Input Text", lines=5)
395
  happy_talk = gr.Checkbox(label="Happy Talk", value=True)
396
  compress = gr.Checkbox(label="Compress", value=False)
@@ -402,8 +394,8 @@ def create_interface():
402
  text_output = gr.Textbox(label="Generated Text", lines=10)
403
 
404
  generate_text_button.click(
405
- gpt4_mini_node.generate,
406
- inputs=[api_key, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt],
407
  outputs=text_output
408
  )
409
 
 
3
  import json
4
  import os
5
  import re
 
6
  from datetime import datetime
7
+ from huggingface_hub import InferenceClient
8
 
9
  # Load JSON files
10
  def load_json_file(file_name):
 
259
 
260
  return self.process_string(replaced, seed)
261
 
262
+ class HuggingFaceInferenceNode:
263
  def __init__(self):
264
+ self.clients = {
265
+ "Mixtral": InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO"),
266
+ "Mistral": InferenceClient("mistralai/Mistral-7B-Instruct-v0.3"),
267
+ "Llama": InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct"),
268
+ "Mistral-Nemo": InferenceClient("mistralai/Mistral-Nemo-Instruct-2407")
269
+ }
270
  self.prompts_dir = "./prompts"
271
  os.makedirs(self.prompts_dir, exist_ok=True)
272
 
273
  def save_prompt(self, prompt):
274
+ filename_text = "hf_" + prompt.split(',')[0].strip()
275
  filename_text = re.sub(r'[^\w\-_\. ]', '_', filename_text)
276
  filename_text = filename_text[:30]
277
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
 
283
 
284
  print(f"Prompt saved to {filename}")
285
 
286
+ def generate(self, model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt=""):
287
  try:
288
+ client = self.clients[model]
289
 
290
  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 (e.g. Wes Anderson, Christopher Nolan, Quentin Tarantino) 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 as a screen grab from a 35mm film still, including details about the film grain, color grading, and any artifacts or characteristics specific to 35mm film photography."""
291
 
 
300
  Branding type: Describe the branding type
301
  Tagline: Include a tagline that captures the essence of the movie.
302
  Visual style: Ensure that the visual style fits the branding type and tagline.
303
+ You are allowed to make up film and branding names, and do them like 80's, 90's or modern movie posters."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
 
305
  if poster:
306
  base_prompt = poster_prompt
 
318
  char_limit = compression_chars[compression_level]
319
  base_prompt += f" Compress the output to be concise while retaining key visual details. MAX OUTPUT SIZE no more than {char_limit} characters."
320
 
321
+ messages = f"<|im_start|>system\nYou are OpenGPT 4o a helpful and very powerful chatbot web assistant made by KingNish. You are provided with WEB results from which you can find informations to answer users query in Structured, Better and in Human Way. You do not say Unnecesarry things. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply in details like human, use short forms, friendly tone and emotions.<|im_end|>"
322
+ messages += f"\n<|im_start|>user\n{base_prompt}\nDescription: {input_text}<|im_end|>\n<|im_start|>assistant\n"
323
+
324
+ stream = client.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
325
+ output = ""
326
+ for response in stream:
327
+ if not response.token.text == "<|im_end|>":
328
+ output += response.token.text
329
 
330
+ self.save_prompt(output)
331
+ return output
 
332
  except Exception as e:
333
  print(f"An error occurred: {e}")
334
  return f"Error occurred while processing the request: {str(e)}"
335
 
336
  def create_interface():
337
  prompt_generator = PromptGenerator()
338
+ huggingface_node = HuggingFaceInferenceNode()
339
 
340
  with gr.Blocks() as demo:
341
  gr.Markdown("# AI Prompt Generator and Text Generator")
 
381
  outputs=[output, gr.Number(visible=False), t5xxl_output, clip_l_output, clip_g_output]
382
  )
383
 
384
+ with gr.Tab("HuggingFace Inference Text Generator"):
385
+ model = gr.Dropdown(["Mixtral", "Mistral", "Llama", "Mistral-Nemo"], label="Model", value="Mixtral")
386
  input_text = gr.Textbox(label="Input Text", lines=5)
387
  happy_talk = gr.Checkbox(label="Happy Talk", value=True)
388
  compress = gr.Checkbox(label="Compress", value=False)
 
394
  text_output = gr.Textbox(label="Generated Text", lines=10)
395
 
396
  generate_text_button.click(
397
+ huggingface_node.generate,
398
+ inputs=[model, input_text, happy_talk, compress, compression_level, poster, custom_base_prompt],
399
  outputs=text_output
400
  )
401