можешь мне описать точный алгоритм того что делает этот скрипт? и потом мы его модифицируем
import openai
import os
from dotenv import load_dotenv
from tkinter import Tk, filedialog, Button, Label
from tqdm import tqdm
import csv
import subprocess
import re
import sys

# Автоматическая установка отсутствующих пакетов
def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package])

required_packages = ["openai", "python-dotenv", "tqdm"]
for package in required_packages:
    try:
        __import__(package)
    except ImportError:
        install(package)

load_dotenv('key.gpt')
openai.api_key = os.getenv('OPENAI_API_KEY')

def extract_metadata_from_analysis(analysis):
    title, description, keywords = '', '', ''
    lines = analysis.splitlines()
    keywords_started = False
    keyword_list = []

    for line in lines:
        line_clean = re.sub(r'[\*\#\:\"]', '', line).strip()

        if line_clean.lower().startswith("title"):
            title = line_clean[len("title"):].strip()
        elif line_clean.lower().startswith("description"):
            description = line_clean[len("description"):].strip()
        elif line_clean.lower().startswith("keywords") or keywords_started:
            if not keywords_started:
                line_clean = line_clean[len("keywords"):].strip()
            keywords_started = True
            if line_clean:  # если строка не пустая, добавляем её в список ключевых слов
                keyword_list.append(line_clean)
            continue

    # Преобразуем список ключевых слов в одну строку
    keywords = ', '.join(keyword_list)

    return title, description, keywords

def get_corresponding_image(file_name_base, directory):
    jpeg_path = os.path.join(directory, file_name_base + '.jpeg')
    jpg_path = os.path.join(directory, file_name_base + '.jpg')
    png_path = os.path.join(directory, file_name_base + '.png')

    if os.path.isfile(jpeg_path):
        return jpeg_path
    elif os.path.isfile(jpg_path):
        return jpg_path
    elif os.path.isfile(png_path):
        return png_path
    return None

def process_file(text_file, directory, csv_writer):
    file_name_base = os.path.splitext(os.path.basename(text_file))[0]
    image_file = get_corresponding_image(file_name_base, directory)

    if not image_file:
        print(f"No corresponding image found for {text_file}, skipping.")
        return

    with open(text_file, "r", encoding="utf-8") as file:
        text = file.read()

    prompt = (
        f"Analyze the following text to create comprehensive metadata for an image:"
        f"\n\nText: {text}"
        f"\n\nAnalysis Steps:"
        f"\n1. Determine the main objects, actions, and background elements of the image."
        f"\n2. Note the primary colors of the background and key elements."
        f"\n3. Identify the conceptual meaning of the image, including thematic or cultural aspects."
        f"\n4. Define the potential audience and usage of the image, such as for marketing, web design, or editorial purposes."
        f"\n\nTitle Creation:"
        f"\n- Create a title with at least 7 words, no more than 120 characters."
        f"\n- Include main objects, actions, color scheme, and important details."
        f"\n- The title should be a complete sentence, addressing Who, What, When, Where, Why, and reflect the mood."
        f"\n- Avoid unnecessary articles and adjectives."
        f"\n\nDescription Creation:"
        f"\n- Develop a description up to 200 characters, noting additional characteristics (colors, season, object or activity details)."
        f"\n- Specify practical uses and the concept of the image (e.g., for advertising or seasonal materials)."
        f"\n- Avoid brand and trademark names."
        f"\n\nKeyword Selection:"
        f"\n- Provide 30 to 49 keywords reflecting the image's contents."
        f"\n- List keywords by significance, from main objects to background elements, mood, and concept."
        f"\n- Include popular search terms for SEO."
        f"\n- Avoid redundancy by not listing synonyms."
    )

    try:
        response = openai.ChatCompletion.create(
            model="gpt-4o-mini",
            messages=[{"role": "system", "content": "You analyze text to create detailed metadata for images."},
                      {"role": "user", "content": prompt}]
        )

        analysis = response['choices'][0]['message']['content'].strip()
        print(f'Metadata analysis generated for {text_file}: {analysis}')

        title, description, keywords = extract_metadata_from_analysis(analysis)

        if not title or not description or not keywords:
            print(f'Error: Missing metadata for {text_file}. Analysis result was: {analysis}')
        else:
            csv_writer.writerow([os.path.basename(image_file), title, description, keywords])

    except Exception as e:
        print(f"An error occurred while processing {text_file}: {e}")

def process_files():
    file_paths = filedialog.askopenfilenames(title="Select text files", filetypes=[("Text files", "*.txt")])
    directory = os.path.dirname(file_paths[0])
    csv_file_path = os.path.join(directory, 'metadata.csv')

    with open(csv_file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(['Filename', 'Title', 'Description', 'Keywords'])

        progress = tqdm(total=len(file_paths), desc="Processing files")
        for text_file in file_paths:
            process_file(text_file, directory, writer)
            progress.update(1)
        progress.close()

    print(f'Metadata CSV created at: {csv_file_path}')

def process_directory():
    directory = filedialog.askdirectory(title="Select a directory")
    text_files = [os.path.join(directory, f) for f in os.listdir(directory) if f.endswith('.txt')]
    csv_file_path = os.path.join(directory, 'metadata.csv')

    with open(csv_file_path, mode='w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(['Filename', 'Title', 'Description', 'Keywords'])

        progress = tqdm(total=len(text_files), desc="Processing files")
        for text_file in text_files:
            process_file(text_file, directory, writer)
            progress.update(1)
        progress.close()

    print(f'Metadata CSV created at: {csv_file_path}')

# Настройка графического интерфейса с помощью Tkinter
root = Tk()
root.title("Metadata Generator")

Label(root, text="Select files or directory for processing").pack()
Button(root, text="Select Files", command=process_files).pack()
Button(root, text="Select Directory", command=process_directory).pack()
root.mainloop()