70 lines
2.6 KiB
Python
70 lines
2.6 KiB
Python
import argparse
|
|
from pathlib import Path
|
|
from itertools import zip_longest
|
|
from .common import invert_input_tag_args, add_file_as_text
|
|
from ..configuration import Config
|
|
from ..message import MessageFilter, Message, Question
|
|
from ..chat import ChatDB, msg_location
|
|
|
|
|
|
class TranslationCmdError(Exception):
|
|
pass
|
|
|
|
|
|
def create_message(chat: ChatDB, args: argparse.Namespace) -> Message:
|
|
"""
|
|
Create a new message from the given arguments and write it
|
|
to the cache directory.
|
|
"""
|
|
text_parts = []
|
|
if args.create is not None:
|
|
text_list = args.create
|
|
elif args.ask is not None:
|
|
text_list = args.ask
|
|
else:
|
|
raise TranslationCmdError("No input text found")
|
|
# NOTE: we currently support only one input document
|
|
text_files = args.input_document if args.input_document is not None else []
|
|
|
|
# create the full text to be translated by combining all text parts
|
|
# from the arguments with the content of the document
|
|
for text, text_file in zip_longest(text_list, text_files, fillvalue=None):
|
|
if text is not None and len(text.strip()) > 0:
|
|
text_parts.append(text)
|
|
if text_file is not None and len(text_file) > 0:
|
|
add_file_as_text(text_parts, text_file)
|
|
full_text = '\n\n'.join([str(s) for s in text_parts])
|
|
|
|
# FIXME: prepend translation prompt and glossaries (if given)
|
|
message = Message(question=Question(full_text),
|
|
tags=args.output_tags,
|
|
ai=args.AI,
|
|
model=args.model)
|
|
# only write the new message to the cache,
|
|
# don't add it to the internal list
|
|
chat.cache_write([message])
|
|
return message
|
|
|
|
|
|
def translation_cmd(args: argparse.Namespace, config: Config) -> None:
|
|
"""
|
|
Handler for the 'translation' command. Creates and executes translation
|
|
requests based on the input and selected AI. Depending on the AI, the
|
|
whole process may be significantly different (e.g. DeepL vs OpenAI).
|
|
"""
|
|
invert_input_tag_args(args)
|
|
mfilter = MessageFilter(tags_or=args.or_tags,
|
|
tags_and=args.and_tags,
|
|
tags_not=args.exclude_tags)
|
|
chat = ChatDB.from_dir(cache_path=Path(config.cache),
|
|
db_path=Path(config.db),
|
|
mfilter=mfilter,
|
|
glob=args.glob,
|
|
loc=msg_location(args.location))
|
|
# if it's a new translation, create and store it immediately
|
|
if args.ask or args.create:
|
|
# message = create_message(chat, args)
|
|
create_message(chat, args)
|
|
if args.create:
|
|
return
|