gpt-engineer icon indicating copy to clipboard operation
gpt-engineer copied to clipboard

Files are not created.

Open BaGRoS opened this issue 1 year ago • 0 comments

**Hi All

My main_prompt:**

`# Project Outline: Kodi Subtitle Translation Plugin using Python and OpenAI API

Overview

The goal of the project is to develop a Kodi plugin that performs the following tasks whenever a film is started from any source:

  1. Checks if the film has embedded English subtitles
  2. Translates these subtitles using the OpenAI API "gpt-3.5-turbo-16k" into the target language set in the plugin's settings, with Polish or the system language as the default
  3. Sets the translated subtitles as activated in the film The plugin should provide information in the form of a Kodi requester about what it is currently executing, and finally confirm that it has set the subtitles in the chosen language.

Pre-requisites:

  • Python
  • Kodi Python API
  • OpenAI API
  • Knowledge of Kodi add-on structure

Plugin Directory Structure:

kodi-subtitle-translation-plugin
│
├─── resources
│     ├─── language
│     │    ├─── English
│     │    └─── Polish
│     └─── settings.xml
│
├─── lib
│     ├─── openai_translation.py
│     └─── subtitle_management.py
│
├─── LICENSE.txt
├─── addon.xml
├─── default.py
└─── install.md

Instructions:

1. Create the Kodi Plugin Base

  1. addon.xml: This is the main descriptor file, containing metadata about the plugin, including its name, version, and the list of python libraries that your plugin will need.

  2. default.py: This is the entry point for the plugin, where the Kodi API interacts with your plugin. This will include the main functions to get the movie's file path, extract subtitles, translate them and reinsert them.

  3. LICENSE.txt: The license file for your plugin. Typically this would be the GPL v2.0 or later, as Kodi is also GPL v2.0 licensed.

  4. resources/settings.xml: This XML file contains all the configurable settings for the plugin, such as the preferred language for translations.

  5. resources/language: This directory contains localization strings for the addon. At a minimum, you should include English.

  6. lib/openai_translation.py: This file will contain the functions that will use OpenAI API to translate the subtitles.

  7. lib/subtitle_management.py: This file will handle the extraction and reinsertion of subtitles from and into the movie file.

2. Plugin Implementation

default.py:

  • Implement the run() method which will be the entry point for the Kodi plugin.
  • Fetch the currently playing movie's file path using the Kodi Python API.
  • Extract the subtitles using the subtitle_management.py module.
  • Check if the subtitles exist and if they are in English.
  • If they exist, translate the subtitles using the openai_translation.py module.
  • Reinsert the translated subtitles back into the movie file using the subtitle_management.py module.
  • Throughout each stage, update the Kodi requester with the current status.

openai_translation.py:

  • Connect to the OpenAI API using the given key.
  • Implement the translate() function that takes the subtitles as input and translates them to the target language using OpenAI API.

subtitle_management.py:

  • Implement the extract_subtitles() function to extract the subtitles from the movie file.
  • Implement the insert_subtitles() function to insert the translated subtitles back into the movie file.

3. Plugin Installation Instruction (install.md)

Document the installation process for your Kodi plugin. This should include instructions for compressing the

plugin into a .zip file, transferring it to the Kodi device, and how to use the Kodi interface to install the plugin from the .zip file.

4. Makefile

Consider writing a make.py script to automate the process of compressing the plugin files into a .zip file.


Remember, thorough testing is important to ensure the functionality of your plugin. Test your plugin on multiple platforms and a variety of films to ensure everything works as expected. Good luck!`

########################################

Output from the script:

`(.venv) d:_Python\GitHub\gpt-engineer>python -m gpt_engineer.main projects/kodi_napisy Program Specification: Kodi Subtitle Translation Plugin using Python and OpenAI API

Overview

The goal of the program is to develop a Kodi plugin that performs the following tasks whenever a film is started from any source:

  1. Checks if the film has embedded English subtitles
  2. Translates these subtitles using the OpenAI API "gpt-3.5-turbo-16k" into the target language set in the plugin's settings, with Polish or the system language as the default
  3. Sets the translated subtitles as activated in the film The plugin should provide information in the form of a Kodi requester about what it is currently executing, and finally confirm that it has set the subtitles in the chosen language.

Features

  1. Detect embedded English subtitles in the currently playing movie
  2. Extract the English subtitles from the movie file
  3. Translate the extracted subtitles into the target language using OpenAI API
  4. Reinsert the translated subtitles back into the movie file
  5. Activate the translated subtitles in the movie
  6. Display progress information using Kodi requester

Core Classes, Functions, and Methods

  1. run(): The main entry point for the Kodi plugin, responsible for coordinating the entire subtitle translation process.
  2. get_movie_file_path(): Fetches the currently playing movie's file path using the Kodi Python API.
  3. extract_subtitles(movie_file_path): Extracts the subtitles from the movie file.
  4. translate_subtitles(subtitles, target_language): Translates the subtitles into the target language using the OpenAI API.
  5. insert_subtitles(movie_file_path, translated_subtitles): Inserts the translated subtitles back into the movie file.
  6. activate_translated_subtitles(): Activates the translated subtitles in the movie.
  7. update_requester(status): Updates the Kodi requester with the current status of the subtitle translation process.

Non-standard Dependencies

  1. Kodi Python API: The Kodi Python API is required to interact with the Kodi media player and perform tasks such as fetching the movie file path and activating subtitles.
  2. OpenAI API: The OpenAI API is used to translate the extracted subtitles into the target language.
  3. Python libraries for subtitle extraction and insertion: Libraries such as pysubs2 or pysrt can be used to extract and insert subtitles in various formats (e.g., SRT, ASS, SSA).

Additional Notes

  • The plugin should be configurable through a settings menu, allowing users to set their preferred target language for subtitle translation.
  • The plugin should handle errors gracefully, such as when the OpenAI API is unavailable or when the movie file does not contain subtitles.
  • The plugin should be compatible with various movie file formats and subtitle formats.
  • The plugin should be tested on multiple platforms and with a variety of films to ensure proper functionality. To generate tests based on the above specification, we will use the pytest library for Python. We will create a test file named test_kodi_subtitle_translation_plugin.py and write test functions for each core function mentioned in the specification.

[FILENAME]

test_kodi_subtitle_translation_plugin.py

[CODE]

import pytest
from unittest.mock import MagicMock
from default import run, get_movie_file_path, update_requester
from lib.openai_translation import translate_subtitles
from lib.subtitle_management import extract_subtitles, insert_subtitles, activate_translated_subtitles


def test_get_movie_file_path():
    # Test if get_movie_file_path() returns a valid file path
    movie_file_path = get_movie_file_path()
    assert isinstance(movie_file_path, str)
    assert len(movie_file_path) > 0


def test_extract_subtitles():
    # Test if extract_subtitles() returns subtitles when given a valid movie file path
    movie_file_path = "path/to/movie/file.mkv"
    subtitles = extract_subtitles(movie_file_path)
    assert isinstance(subtitles, str)
    assert len(subtitles) > 0


def test_translate_subtitles():
    # Test if translate_subtitles() returns translated subtitles when given valid input
    subtitles = "This is a test subtitle."
    target_language = "pl"
    translated_subtitles = translate_subtitles(subtitles, target_language)
    assert isinstance(translated_subtitles, str)
    assert len(translated_subtitles) > 0


def test_insert_subtitles():
    # Test if insert_subtitles() successfully inserts translated subtitles into the movie file
    movie_file_path = "path/to/movie/file.mkv"
    translated_subtitles = "To jest testowy napis."
    result = insert_subtitles(movie_file_path, translated_subtitles)
    assert result is True


def test_activate_translated_subtitles():
    # Test if activate_translated_subtitles() successfully activates the translated subtitles
    result = activate_translated_subtitles()
    assert result is True


def test_update_requester():
    # Test if update_requester() successfully updates the Kodi requester with the current status
    status = "Extracting subtitles..."
    result = update_requester(status)
    assert result is True


def test_run():
    # Test if run() successfully coordinates the entire subtitle translation process
    get_movie_file_path_mock = MagicMock(return_value="path/to/movie/file.mkv")
    extract_subtitles_mock = MagicMock(return_value="This is a test subtitle.")
    translate_subtitles_mock = MagicMock(return_value="To jest testowy napis.")
    insert_subtitles_mock = MagicMock(return_value=True)
    activate_translated_subtitles_mock = MagicMock(return_value=True)
    update_requester_mock = MagicMock(return_value=True)

    with pytest.raises(SystemExit) as pytest_wrapped_e:
        run()

    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == 0

    get_movie_file_path_mock.assert_called_once()
    extract_subtitles_mock.assert_called_once()
    translate_subtitles_mock.assert_called_once()
    insert_subtitles_mock.assert_called_once()
    activate_translated_subtitles_mock.assert_called_once()
    update_requester_mock.assert_called()

These tests cover the core functionality of the Kodi Subtitle Translation Plugin. Make sure to run the tests using pytest and adjust the implementation as needed to ensure all tests pass. [FILENAME]

requirements.txt

[CODE]

kodi-python
openai
pysubs2
pytest

[FILENAME]

addon.xml

[CODE]

<?xml version="1.0" encoding="UTF-8"?>
<addon id="plugin.video.subtitle_translation"
       name="Kodi Subtitle Translation Plugin"
       version="1.0.0"
       provider-name="Your Name">
    <requires>
        <import addon="xbmc.python" version="3.0.0"/>
    </requires>
    <extension point="xbmc.python.pluginsource"
              library="default.py">
        <provides>video</provides>
    </extension>
    <extension point="xbmc.addon.metadata">
        <summary lang="en_GB">Kodi plugin to translate movie subtitles using OpenAI API</summary>
        <description lang="en_GB">This plugin translates embedded English subtitles into the target language using the OpenAI API.</description>
        <platform>all</platform>
        <license>GPL-2.0-or-later</license>
        <source>https://github.com/yourusername/kodi-subtitle-translation-plugin</source>
    </extension>
</addon>

[FILENAME]

default.py

[CODE]

import sys
import xbmc
import xbmcgui
import xbmcplugin
from lib.openai_translation import translate_subtitles
from lib.subtitle_management import extract_subtitles, insert_subtitles, activate_translated_subtitles

def get_movie_file_path():
    player = xbmc.Player()
    movie_file_path = player.getPlayingFile()
    return movie_file_path

def update_requester(status):
    xbmcgui.Dialog().notification("Subtitle Translation", status, xbmcgui.NOTIFICATION_INFO, 5000)

def run():
    movie_file_path = get_movie_file_path()
    update_requester("Extracting subtitles...")
    subtitles = extract_subtitles(movie_file_path)

    if subtitles:
        update_requester("Translating subtitles...")
        target_language = xbmcplugin.getSetting("target_language")
        translated_subtitles = translate_subtitles(subtitles, target_language)

        if translated_subtitles:
            update_requester("Inserting translated subtitles...")
            insert_subtitles(movie_file_path, translated_subtitles)
            activate_translated_subtitles()
            update_requester("Subtitle translation completed.")
        else:
            update_requester("Subtitle translation failed.")
    else:
        update_requester("No subtitles found.")

if __name__ == "__main__":
    run()

[FILENAME]

lib/openai_translation.py

[CODE]

import openai

def translate_subtitles(subtitles, target_language):
    openai.api_key = "your_openai_api_key"
    response = openai.Completion.create(
        engine="gpt-3.5-turbo-16k",
        prompt=f"Translate the following English subtitles to {target_language}:\n{subtitles}",
        max_tokens=1000,
        n=1,
        stop=None,
        temperature=0.5,
    )

    translated_subtitles = response.choices[0].text.strip()
    return translated_subtitles

[FILENAME]

lib/subtitle_management.py

[CODE]

import pysubs2

def extract_subtitles(movie_file_path):
    subs = pysubs2.load(movie_file_path, encoding="utf-8")
    subtitles = "\n".join([sub.text for sub in subs])
    return subtitles

def insert_subtitles(movie_file_path, translated_subtitles):
    subs = pysubs2.load(movie_file_path, encoding="utf-8")
    translated_subs = translated_subtitles.split("\n")

    for i, sub in enumerate(subs):
        sub.text = translated_subs[i]

    subs.save(movie_file_path, encoding="utf-8")
    return True

def activate_translated_subtitles():
    xbmc.executebuiltin("ActivateSubtitle")
    return True

[FILENAME]

resources/settings.xml

[CODE]

<settings>
    <category label="Subtitle Translation Settings">
        <setting id="target_language" type="enum" label="Target Language" values="Polish|French|German|Spanish" default="0" />
    </category>
</settings>

[FILENAME]

resources/language/English/strings.po

[CODE]

msgid ""
msgstr ""
"Project-Id-Version: Kodi Subtitle Translation Plugin\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Your Name <[email protected]>\n"
"Language-Team: English\n"
"Language: en_GB\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

msgctxt "#30000"
msgid "Subtitle Translation Settings"
msgstr ""

msgctxt "#30001"
msgid "Target Language"
msgstr ""

[FILENAME]

resources/language/Polish/strings.po

[CODE]

msgid ""
msgstr ""
"Project-Id-Version: Kodi Subtitle Translation Plugin\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: Your Name <[email protected]>\n"
"Language-Team: Polish\n"
"Language: pl_PL\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"

msgctxt "#30000"
msgid "Subtitle Translation Settings"
msgstr "Ustawienia tłumaczenia napisów"

msgctxt "#30001"
msgid "Target Language"
msgstr "Język docelowy"

[FILENAME]

LICENSE.txt

[CODE]

                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

[...]

[FILENAME]

install.md

[CODE]

# Kodi Subtitle Translation Plugin Installation Instructions

1. Compress the `kodi-subtitle-translation-plugin` folder into a .zip file.
2. Transfer the .zip file to your Kodi device.
3. Open Kodi and navigate to the Add-ons menu.
4. Select "Install from zip file" and locate the .zip file you transferred.
5. Kodi will install the plugin and notify you when the installation is complete.

After installation, the plugin will automatically translate subtitles whenever a movie is played.

These are the complete files for the Kodi Subtitle Translation Plugin. Make sure to replace the placeholder your_openai_api_key in lib/openai_translation.py with your actual OpenAI API key. Test the plugin on multiple platforms and a variety of films to ensure everything works as expected.

python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python default.py &

Do you want to execute this code?

python3 -m venv venv source venv/bin/activate pip install -r requirements.txt

python default.py &

If yes, press enter. Otherwise, type "no"`

########################################

but files strukture looks like this:

image

Something is wrong.

BaGRoS avatar Jun 18 '23 23:06 BaGRoS