meu software nao esta abrindo veja qual erro no codigo:

import os
import requests
from tkinter import Tk, Label, Entry, Button, Checkbutton, IntVar, Text, Scrollbar, VERTICAL, END, StringVar, OptionMenu
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
import openai
import cv2

# Configurações da API - Substitua pelas suas chaves reais
UNSPLASH_ACCESS_KEY = 'YOUR_UNSPLASH_ACCESS_KEY'
PEXELS_API_KEY = 'YOUR_PEXELS_API_KEY'
PIXABAY_API_KEY = 'YOUR_PIXABAY_API_KEY'
OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY'

openai.api_key = OPENAI_API_KEY

# Variáveis globais
paused = False
downloaded_image_count = 0
history_file = 'image_history.txt'
downloaded_urls = set()

# Carregar histórico de URLs
if os.path.exists(history_file):
    with open(history_file, 'r') as f:
        downloaded_urls = set(line.strip() for line in f)

# Função para limpar o histórico de URLs baixadas
def clear_history():
    global downloaded_urls
    downloaded_urls = set()  # Limpa o conjunto de URLs baixadas

    with open(history_file, 'w') as f:
        f.write('')  # Limpa o conteúdo do arquivo

    print("Histórico limpo.")

# Funções para download de imagens
def download_images(query, count, folder='images', resolution=None):
    unsplash_images = download_unsplash_images(query, count, folder, resolution)
    pexels_images = download_pexels_images(query, count, folder, resolution)
    pixabay_images = download_pixabay_images(query, count, folder, resolution)

    all_images = unsplash_images + pexels_images + pixabay_images

    if len(all_images) < count:
        required_images = count - len(all_images)
        all_images += download_unsplash_images(query, required_images, folder, resolution)

    return all_images

def download_unsplash_images(query, count, folder='images', resolution=None):
    url = f"https://api.unsplash.com/search/photos?query={query}&per_page={count}&client_id={UNSPLASH_ACCESS_KEY}"
    response = requests.get(url)
    response.raise_for_status()
    search_results = response.json()
    return save_images(search_results['results'], folder, query, 'urls', 'regular', resolution)

def download_pexels_images(query, count, folder='images', resolution=None):
    headers = {"Authorization": PEXELS_API_KEY}
    url = f"https://api.pexels.com/v1/search?query={query}&per_page={count}"
    response = requests.get(url, headers=headers)
    response.raise_for_status()
    search_results = response.json()
    return save_images(search_results['photos'], folder, query, 'src', 'medium', resolution)

def download_pixabay_images(query, count, folder='images', resolution=None):
    url = f"https://pixabay.com/api/?key={PIXABAY_API_KEY}&q={query}&image_type=photo&per_page={count}"
    response = requests.get(url)
    response.raise_for_status()
    search_results = response.json()
    return save_images(search_results['hits'], folder, query, 'webformatURL', None, resolution)

def save_images(images, folder, query, url_key, sub_key=None, resolution=None):
    global downloaded_image_count
    if not os.path.exists(folder):
        os.makedirs(folder)

    saved_images = []
    for i, img in enumerate(images):
        if paused:
            break

        img_url = img[url_key] if sub_key is None else img[url_key][sub_key]

        if img_url in downloaded_urls:
            continue

        try:
            img_response = requests.get(img_url)
            img_response.raise_for_status()

            image = Image.open(BytesIO(img_response.content))

            if resolution:
                width, height = resolution
                if image.size[0] < width or image.size[1] < height:
                    image = image.resize((width, height), Image.ANTIALIAS)

            img_filename = f"{folder}/{query}_{downloaded_image_count}.jpg"
            image.save(img_filename, format='JPEG', quality=95)

            saved_images.append(img_filename)
            downloaded_urls.add(img_url)
            with open(history_file, 'a') as f:
                f.write(img_url + '\n')

            downloaded_image_count += 1
            update_image_count_label()
            print(f"Saved {img_filename}")

        except Exception as e:
            print(f"Could not download {img_url} - {e}")

    return saved_images

# Função para gerar frases motivacionais
def generate_phrases(prompt, count):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        max_tokens=50,
        n=count,
        stop=None,
        temperature=0.5
    )
    return [choice['text'].strip() for choice in response.choices]

# Função para adicionar texto às imagens com fundo preto
def add_text_to_image(image_path, text, font_name='Arial', font_size=30, text_style="normal"):
    image = Image.open(image_path)
    draw = ImageDraw.Draw(image)

    # Selecionar a fonte com base nas opções escolhidas
    font = ImageFont.truetype(font_name, font_size)

    if text_style == "bold":
        font = ImageFont.truetype(font_name, font_size, weight="bold")
    elif text_style == "italic":
        font = ImageFont.truetype(font_name, font_size, italic=True)

    text_width, text_height = draw.textsize(text, font=font)

    # Calcular as coordenadas para posicionar o texto no centro da imagem
    width, height = image.size
    text_x = (width - text_width) / 2
    text_y = (height - text_height) / 2

    # Adicionar fundo preto ao texto para garantir legibilidade
    bg_rect_xy = (text_x - 5, text_y - 5, text_x + text_width + 5, text_y + text_height + 5)
    draw.rectangle(bg_rect_xy, fill="black")

    # Adicionar o texto à imagem
    draw.text((text_x, text_y), text, font=font, fill="white")
    image.save(image_path)
    print(f"Texto com fundo preto adicionado em {image_path}")

# Função para atualizar o rótulo do contador de imagens
def update_image_count_label():
    global image_count_var
    image_count_var.set(f"Imagens Baixadas: {downloaded_image_count}")

# Função para remover marca d'água das imagens usando OpenCV
def remove_watermark(image_path, output_path):
    image = cv2.imread(image_path)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    _, mask = cv2.threshold(gray, 200, 255, cv2.THRESH_BINARY)

    result = cv2.inpaint(image, mask, 3, cv2.INPAINT_TELEA)
    cv2.imwrite(output_path, result)
    print(f"Saved image without watermark to {output_path}")

# Função para remover marcas d'água de todas as imagens baixadas
def remove_watermarks_from_images():
    images = image_list_text.get('1.0', END).strip().split('\n')
    folder = 'images_no_watermark'

    if not os.path.exists(folder):
        os.makedirs(folder)

    for image in images:
        if image:
            output_path = os.path.join(folder, os.path.basename(image))
            remove_watermark(image, output_path)

# Interface gráfica com Tkinter
def create_gui():
    global image_count_var, image_list_text

    def on_search():
        global paused
        paused = False
        query = query_entry.get()
        resolution = (1920, 1080) if horizontal_var.get() else (1080, 1920) if vertical_var.get() else None
        min_count = 50
        folder = 'images'

        images = download_images(query, min_count, folder, resolution)

        image_list_text.delete('1.0', END)
        image_list_text.insert('1.0', '\n'.join(images))

    def on_generate_phrases():
        prompt = phrase_entry.get()
        count = 10  # Número de frases a serem geradas
        phrases = generate_phrases(prompt, count)
        images = image_list_text.get('1.0', END).strip().split('\n')

        if len(images) < len(phrases):
            phrases = phrases[:len(images)]

        for image, phrase in zip(images, phrases):
            add_text_to_image(image, phrase)

    def on_pause():
        global paused
        paused = not paused
        pause_button.config(text="Retomar" if paused else "Pausar")

    def on_remove_watermarks():
        remove_watermarks_from_images()

    root = Tk()
    root.title("Image Downloader and Text Adder")

    image_count_var = StringVar()

    Label(root, text="Image Type:").grid(row=0, column=0, sticky='w')
    query_entry = Entry(root, width=50)
    query_entry.grid(row=0, column=1, padx=10, pady=5)

    horizontal_var = IntVar()
        Checkbutton(root, text="1920x1080 (Horizontal)", variable=horizontal_var).grid(row=1, column=1, sticky='w', padx=10)
    vertical_var = IntVar()
    Checkbutton(root, text="1080x1920 (Vertical)", variable=vertical_var).grid(row=2, column=1, sticky='w', padx=10)

    Button(root, text="Pesquisar e Baixar Imagens", command=on_search).grid(row=3, column=1, sticky='w', pady=10)

    Label(root, text="Frases para Adicionar (opcional):").grid(row=4, column=0, sticky='w', pady=(10, 0))
    phrase_entry = Entry(root, width=50)
    phrase_entry.grid(row=4, column=1, padx=10, pady=(10, 0))

    Button(root, text="Gerar Frases e Adicionar ao Texto", command=on_generate_phrases).grid(row=5, column=1, sticky='w', pady=10)

    Button(root, text="Pausar", command=on_pause).grid(row=6, column=1, sticky='w', pady=10)
    Button(root, text="Remover Marcas d'Água", command=on_remove_watermarks).grid(row=7, column=1, sticky='w', pady=10)

    image_count_label = Label(root, textvariable=image_count_var)
    image_count_label.grid(row=8, column=1, sticky='w', pady=10)

    image_list_text = Text(root, height=10, width=70)
    image_list_text.grid(row=9, column=1, padx=10, pady=10)

    scrollbar = Scrollbar(root, orient=VERTICAL, command=image_list_text.yview)
    scrollbar.grid(row=9, column=2, sticky='ns')

    image_list_text.config(yscrollcommand=scrollbar.set)

    Button(root, text="Limpar Histórico", command=clear_history).grid(row=10, column=1, sticky='w', pady=10)

    root.mainloop()

# Iniciar a interface gráfica
create_gui()