gokaygokay commited on
Commit
025a281
1 Parent(s): 5dd8e5c
Files changed (2) hide show
  1. huggingface_inference_node.py +67 -17
  2. ui_components.py +33 -13
huggingface_inference_node.py CHANGED
@@ -1,17 +1,20 @@
1
  import os
2
  from openai import OpenAI
 
 
3
  import re
4
  from datetime import datetime
5
 
6
-
7
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
 
8
 
9
- class HuggingFaceInferenceNode:
10
  def __init__(self):
11
- self.client = OpenAI(
12
  base_url="https://api-inference.huggingface.co/v1/",
13
  api_key=huggingface_token,
14
  )
 
15
  self.prompts_dir = "./prompts"
16
  os.makedirs(self.prompts_dir, exist_ok=True)
17
 
@@ -28,7 +31,7 @@ class HuggingFaceInferenceNode:
28
 
29
  print(f"Prompt saved to {filename}")
30
 
31
- def generate(self, input_text, happy_talk, compress, compression_level, poster, prompt_type, custom_base_prompt=""):
32
  try:
33
  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."""
34
 
@@ -86,20 +89,67 @@ You are allowed to make up film and branding names, and do them like 80's, 90's
86
  system_message = "You are a helpful assistant. Try your best to give the best response possible to the user."
87
  user_message = f"{base_prompt}\nDescription: {input_text}"
88
 
89
- messages = [
90
- {"role": "system", "content": system_message},
91
- {"role": "user", "content": user_message}
92
- ]
93
-
94
- response = self.client.chat.completions.create(
95
- model="meta-llama/Meta-Llama-3.1-70B-Instruct",
96
- max_tokens=1024,
97
- temperature=0.7,
98
- top_p=0.95,
99
- messages=messages,
100
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
- output = response.choices[0].message.content.strip()
 
103
 
104
  # Clean up the output
105
  if ": " in output:
 
1
  import os
2
  from openai import OpenAI
3
+ import anthropic
4
+ from groq import Groq
5
  import re
6
  from datetime import datetime
7
 
 
8
  huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
9
+ groq_api_key = os.getenv("GROQ_API_KEY")
10
 
11
+ class LLMInferenceNode:
12
  def __init__(self):
13
+ self.huggingface_client = OpenAI(
14
  base_url="https://api-inference.huggingface.co/v1/",
15
  api_key=huggingface_token,
16
  )
17
+ self.groq_client = Groq(api_key=groq_api_key)
18
  self.prompts_dir = "./prompts"
19
  os.makedirs(self.prompts_dir, exist_ok=True)
20
 
 
31
 
32
  print(f"Prompt saved to {filename}")
33
 
34
+ def generate(self, input_text, happy_talk, compress, compression_level, poster, prompt_type, custom_base_prompt="", provider="Hugging Face", api_key=None, model=None):
35
  try:
36
  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."""
37
 
 
89
  system_message = "You are a helpful assistant. Try your best to give the best response possible to the user."
90
  user_message = f"{base_prompt}\nDescription: {input_text}"
91
 
92
+ if provider == "Hugging Face":
93
+ response = self.huggingface_client.chat.completions.create(
94
+ model=model or "meta-llama/Meta-Llama-3.1-70B-Instruct",
95
+ max_tokens=1024,
96
+ temperature=0.7,
97
+ top_p=0.95,
98
+ messages=[
99
+ {"role": "system", "content": system_message},
100
+ {"role": "user", "content": user_message}
101
+ ],
102
+ )
103
+ output = response.choices[0].message.content.strip()
104
+
105
+ elif provider == "OpenAI":
106
+ openai_client = OpenAI(api_key=api_key)
107
+ response = openai_client.chat.completions.create(
108
+ model=model or "gpt-4",
109
+ max_tokens=1024,
110
+ temperature=0.7,
111
+ messages=[
112
+ {"role": "system", "content": system_message},
113
+ {"role": "user", "content": user_message}
114
+ ],
115
+ )
116
+ output = response.choices[0].message.content.strip()
117
+
118
+ elif provider == "Anthropic":
119
+ anthropic_client = anthropic.Anthropic(api_key=api_key)
120
+ response = anthropic_client.messages.create(
121
+ model=model or "claude-3-5-sonnet-20240620",
122
+ max_tokens=1024,
123
+ temperature=0.7,
124
+ system=system_message,
125
+ messages=[
126
+ {
127
+ "role": "user",
128
+ "content": [
129
+ {
130
+ "type": "text",
131
+ "text": user_message
132
+ }
133
+ ]
134
+ }
135
+ ]
136
+ )
137
+ output = response.content[0].text
138
+
139
+ elif provider == "Groq":
140
+ response = self.groq_client.chat.completions.create(
141
+ model=model or "llama-3.1-70b-versatile",
142
+ max_tokens=1024,
143
+ temperature=0.7,
144
+ messages=[
145
+ {"role": "system", "content": system_message},
146
+ {"role": "user", "content": user_message}
147
+ ],
148
+ )
149
+ output = response.choices[0].message.content.strip()
150
 
151
+ else:
152
+ raise ValueError(f"Unsupported provider: {provider}")
153
 
154
  # Clean up the output
155
  if ": " in output:
ui_components.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  from prompt_generator import PromptGenerator
3
- from huggingface_inference_node import HuggingFaceInferenceNode
4
  from caption_models import florence_caption, qwen_caption
5
  import random
6
  from prompt_generator import ARTFORM, PHOTO_TYPE, FEMALE_BODY_TYPES, MALE_BODY_TYPES, FEMALE_DEFAULT_TAGS, MALE_DEFAULT_TAGS, ROLES, HAIRSTYLES, FEMALE_CLOTHING, MALE_CLOTHING, PLACE, LIGHTING, COMPOSITION, POSE, BACKGROUND, FEMALE_ADDITIONAL_DETAILS, MALE_ADDITIONAL_DETAILS, PHOTOGRAPHY_STYLES, DEVICE, PHOTOGRAPHER, ARTIST, DIGITAL_ARTFORM
@@ -20,7 +20,7 @@ selected_prompt_type = "happy" # Default value
20
 
21
  def create_interface():
22
  prompt_generator = PromptGenerator()
23
- huggingface_node = HuggingFaceInferenceNode()
24
 
25
  with gr.Blocks(theme='bethecloud/storj_theme') as demo:
26
 
@@ -116,13 +116,17 @@ def create_interface():
116
  interactive=True
117
  )
118
  custom_base_prompt = gr.Textbox(label="Custom Base Prompt", lines=5)
119
- def update_prompt_type(value):
120
- global selected_prompt_type
121
- selected_prompt_type = value
122
- print(f"Updated prompt type: {selected_prompt_type}")
123
- return value
124
- prompt_type.change(update_prompt_type, inputs=[prompt_type], outputs=[prompt_type])
125
- generate_text_button = gr.Button("Generate Prompt with LLM (Llama 3.1 70B)")
 
 
 
 
126
  text_output = gr.Textbox(label="Generated Text", lines=10)
127
 
128
  def create_caption(image, model):
@@ -180,16 +184,32 @@ def create_interface():
180
  outputs=[output]
181
  )
182
 
183
- def generate_text_with_llm(output, happy_talk, compress, compression_level, custom_base_prompt):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  global selected_prompt_type
185
  print(f"Prompt type selected in UI: {selected_prompt_type}") # Debug print
186
- return huggingface_node.generate(output, happy_talk, compress, compression_level, False, selected_prompt_type, custom_base_prompt)
187
 
188
  generate_text_button.click(
189
  generate_text_with_llm,
190
- inputs=[output, happy_talk, compress, compression_level, custom_base_prompt],
191
  outputs=text_output,
192
- api_name="generate_text" # Add this line
193
  )
194
 
195
  # Add this line to disable caching for the generate_text_with_llm function
 
1
  import gradio as gr
2
  from prompt_generator import PromptGenerator
3
+ from huggingface_inference_node import LLMInferenceNode
4
  from caption_models import florence_caption, qwen_caption
5
  import random
6
  from prompt_generator import ARTFORM, PHOTO_TYPE, FEMALE_BODY_TYPES, MALE_BODY_TYPES, FEMALE_DEFAULT_TAGS, MALE_DEFAULT_TAGS, ROLES, HAIRSTYLES, FEMALE_CLOTHING, MALE_CLOTHING, PLACE, LIGHTING, COMPOSITION, POSE, BACKGROUND, FEMALE_ADDITIONAL_DETAILS, MALE_ADDITIONAL_DETAILS, PHOTOGRAPHY_STYLES, DEVICE, PHOTOGRAPHER, ARTIST, DIGITAL_ARTFORM
 
20
 
21
  def create_interface():
22
  prompt_generator = PromptGenerator()
23
+ llm_node = LLMInferenceNode()
24
 
25
  with gr.Blocks(theme='bethecloud/storj_theme') as demo:
26
 
 
116
  interactive=True
117
  )
118
  custom_base_prompt = gr.Textbox(label="Custom Base Prompt", lines=5)
119
+
120
+ # Add new components for LLM provider selection
121
+ llm_provider = gr.Dropdown(
122
+ choices=["Hugging Face", "OpenAI", "Anthropic", "Groq"],
123
+ label="LLM Provider",
124
+ value="Hugging Face"
125
+ )
126
+ api_key = gr.Textbox(label="API Key", type="password", visible=False)
127
+ model = gr.Dropdown(label="Model", choices=["meta-llama/Meta-Llama-3.1-70B-Instruct"], value="meta-llama/Meta-Llama-3.1-70B-Instruct")
128
+
129
+ generate_text_button = gr.Button("Generate Prompt with LLM")
130
  text_output = gr.Textbox(label="Generated Text", lines=10)
131
 
132
  def create_caption(image, model):
 
184
  outputs=[output]
185
  )
186
 
187
+ def update_model_choices(provider):
188
+ provider_models = {
189
+ "Hugging Face": ["meta-llama/Meta-Llama-3.1-70B-Instruct"],
190
+ "Groq": ["llama-3.1-70b-versatile"],
191
+ "OpenAI": ["gpt-4o", "gpt-4o-mini"],
192
+ "Anthropic": ["claude-3-5-sonnet-20240620"],
193
+ }
194
+ models = provider_models[provider]
195
+ return gr.Dropdown(choices=models, value=models[0])
196
+
197
+ def update_api_key_visibility(provider):
198
+ return gr.update(visible=(provider in ["OpenAI", "Anthropic"]))
199
+
200
+ llm_provider.change(update_model_choices, inputs=[llm_provider], outputs=[model])
201
+ llm_provider.change(update_api_key_visibility, inputs=[llm_provider], outputs=[api_key])
202
+
203
+ def generate_text_with_llm(output, happy_talk, compress, compression_level, custom_base_prompt, provider, api_key, model):
204
  global selected_prompt_type
205
  print(f"Prompt type selected in UI: {selected_prompt_type}") # Debug print
206
+ return llm_node.generate(output, happy_talk, compress, compression_level, False, selected_prompt_type, custom_base_prompt, provider, api_key, model)
207
 
208
  generate_text_button.click(
209
  generate_text_with_llm,
210
+ inputs=[output, happy_talk, compress, compression_level, custom_base_prompt, llm_provider, api_key, model],
211
  outputs=text_output,
212
+ api_name="generate_text"
213
  )
214
 
215
  # Add this line to disable caching for the generate_text_with_llm function