File size: 3,824 Bytes
58ac83f
 
 
ae8b149
2a95781
58ac83f
 
a274967
 
24715fe
 
13ba412
24715fe
 
 
 
 
a274967
58ac83f
 
 
 
 
 
 
 
 
567da63
58ac83f
 
 
 
 
c103376
 
58ac83f
c103376
 
 
a274967
 
 
 
 
 
 
 
58ac83f
13ba412
24715fe
 
 
 
 
13ba412
 
 
 
 
24715fe
ae8b149
24715fe
 
 
ae8b149
24715fe
13ba412
 
 
 
 
 
 
 
 
 
ae8b149
 
 
 
 
24715fe
58ac83f
 
 
24715fe
 
498cc41
24715fe
498cc41
24715fe
 
498cc41
 
 
501992b
 
498cc41
 
24715fe
498cc41
 
58ac83f
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import os
import requests


GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"
GROQ_API_KEY = os.getenv("GROQ_API_KEY")  # Secure key from Hugging Face Secrets

if not GROQ_API_KEY:
    raise ValueError("GROQ_API_KEY is missing! Set it in Hugging Face Secrets.")


OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")  # Set this in Hugging Face Secrets

if not OPENAI_API_KEY:
    raise ValueError("OPENAI_API_KEY is missing! Set it in Hugging Face Secrets.")

    
# Helper function to load system prompt from txt files
def load_prompt(filename):
    with open(f'config/system_prompts/{filename}', 'r') as file:
        return file.read()

# Function to call Groq API with system prompt and user input
def call_groq(system_prompt, user_input):
    headers = {"Authorization": f"Bearer {GROQ_API_KEY}"}
    payload = {
        "model": "deepseek-r1-distill-llama-70b",
        "messages": [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_input}
        ]
    }
    print("Sending payload to Groq API...")
    print(payload)
    response = requests.post(GROQ_API_URL, json=payload, headers=headers)
    print("Groq API response status:", response.status_code)
    print("Groq API response body:", response.text)

    if response.status_code != 200:
        raise Exception(f"Groq API error: {response.status_code} - {response.text}")
    
    data = response.json()
    if 'choices' not in data or not data['choices']:
        raise Exception("Groq API returned no choices.")

    return data['choices'][0]['message']['content']

def generate_ad_image(prompt, model="gpt-image-1"):
    headers = {
        "Authorization": f"Bearer {OPENAI_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": model,
        "messages": [
            {"role": "system", "content": "You are an expert image generator. Provide only a valid image URL, no text."},
            {"role": "user", "content": prompt}
        ]
    }

    response = requests.post(OPENAI_API_URL, json=payload, headers=headers)
    if response.status_code != 200:
        raise Exception(f"OpenAI API error: {response.status_code} - {response.text}")

    data = response.json()
    if 'choices' not in data or not data['choices']:
        raise Exception("OpenAI API returned no choices.")

    # Extract image URL(s) from message content
    image_urls = []
    for choice in data['choices']:
        content = choice['message'].get('content', '')
        # Simple heuristic to extract URLs
        urls = [word for word in content.split() if word.startswith('http')]
        image_urls.extend(urls)

    if not image_urls:
        raise Exception("No valid image URLs found in OpenAI API response.")

    return image_urls

def ad_copy_agent(product, description, audience, tone):
    system_prompt = load_prompt("ad_copy_prompt.txt")
    user_input = f"Product: {product}\nDescription: {description}\nAudience: {audience}\nTone: {tone}"
    output = call_groq(system_prompt, user_input)
    
    # Split out the image prompt section
    parts = output.split('Image Prompt:')
    ad_section = parts[0].strip()
    image_prompt = parts[1].strip() if len(parts) > 1 else ''
    
    # Extract clean ad copies
    ad_copies = []
    for line in ad_section.split('\n'):
        if line.strip():
            ad_copies.append(line.strip())

    ad_copy_text = '\n'.join(ad_copies)
    
    return ad_copy_text, image_prompt

def sentiment_agent(social_data):
    system_prompt = load_prompt("sentiment_prompt.txt")
    return call_groq(system_prompt, social_data)

def timing_agent(platform):
    system_prompt = load_prompt("timing_prompt.txt")
    return call_groq(system_prompt, f"Platform: {platform}")