translation: added check for valid document format when using OpenAI

This commit is contained in:
juk0de 2023-11-08 20:10:30 +01:00
parent a185c0db7b
commit 82ad697b68

View File

@ -1,4 +1,5 @@
import argparse
import mimetypes
from pathlib import Path
from .common import invert_input_tag_args, read_text_file
from ..configuration import Config
@ -13,11 +14,16 @@ class TranslationCmdError(Exception):
text_separator: str = 'TEXT:'
def assert_document_type_supported_openai(document_file: Path) -> None:
doctype = mimetypes.guess_type(document_file)
if doctype != 'text/plain':
raise TranslationCmdError("AI 'OpenAI' only supports document type 'text/plain''")
def translation_prompt_openai(source_lang: str, target_lang: str) -> str:
"""
Return the prompt for GPT that tells it to do the translation.
"""
# FIXME: specify the document format if known
return f"Translate the text below the line {text_separator} from {source_lang} to {target_lang}."
@ -51,7 +57,8 @@ def create_message_openai(chat: ChatDB, args: argparse.Namespace) -> Message:
user_text: str
user_prompt: str
if args.input_document is not None:
user_text = read_text_file(args.input_document)
assert_document_type_supported_openai(Path(args.input_document))
user_text = read_text_file(Path(args.input_document))
user_prompt = '\n\n'.join([str(s) for s in text_args])
else:
user_text = text_args[-1]