Spaces:
Running
Running
| import openai, os, json, re | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| sys_prompt = os.getenv("SYS_PROMPT") | |
| def get_prompts(image_base64, category, user_prompt, sentiment, negative_prompt, num_variations): | |
| try: | |
| prompt_examples = [f"Prompt {i + 1}" for i in range(num_variations)] | |
| json_format_example = json.dumps({"variations": prompt_examples}) | |
| if negative_prompt: | |
| message = [ | |
| { | |
| "role": "system", | |
| "content": f"""{sys_prompt} | |
| Return only a JSON with {num_variations} variations of ad prompts for image generation, based on the input image. | |
| Respond in this JSON format:\n{json_format_example}""" | |
| }, | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", "text": f"""Generate prompt variations for this ad image for {category} category having {sentiment} sentiment in JSON format only based on the following instruction: | |
| {user_prompt} | |
| Don't consider following things and treat them as negative prompt: | |
| {negative_prompt}"""}, | |
| {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}} | |
| ] | |
| } | |
| ] | |
| else: | |
| message = [ | |
| { | |
| "role": "system", | |
| "content": f"""{sys_prompt} | |
| Return only a JSON with {num_variations} variations of ad prompts for image generation, based on the input image. | |
| Respond in this JSON format:\n{json_format_example}""" | |
| }, | |
| { | |
| "role": "user", | |
| "content": [ | |
| {"type": "text", | |
| "text": f"""Generate prompt variations for this ad image for {category} category having {sentiment} sentiment in JSON format only based on the following instruction: | |
| {user_prompt}"""}, | |
| {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_base64}"}} | |
| ] | |
| } | |
| ] | |
| response = openai.chat.completions.create( | |
| model="gpt-4o", | |
| messages=message, | |
| temperature=0.7 | |
| ) | |
| content = response.choices[0].message.content.strip() | |
| content = re.sub(r"^```json\s*|\s*```$", "", content) | |
| # print(f"Prompt variations response: {content}") | |
| # return json.loads(content)["variations"] | |
| except Exception: | |
| return [] |