67 lines
2.4 KiB
Python
67 lines
2.4 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.
|
|
"""
|
|
question_parts = []
|
|
if args.create is not None:
|
|
question_list = args.create
|
|
elif args.ask is not None:
|
|
question_list = args.ask
|
|
else:
|
|
raise TranslationCmdError("No input text found")
|
|
text_files = args.input_document if args.source_text is not None else []
|
|
|
|
for question, text_file in zip_longest(question_list, text_files, fillvalue=None):
|
|
if question is not None and len(question.strip()) > 0:
|
|
question_parts.append(question)
|
|
if text_file is not None and len(text_file) > 0:
|
|
add_file_as_text(question_parts, text_file)
|
|
|
|
full_question = '\n\n'.join([str(s) for s in question_parts])
|
|
|
|
message = Message(question=Question(full_question),
|
|
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
|