{"repo": "LuteOrg/lute-v3", "n_pairs": 200, "version": "v2_function_scoped", "contexts": {"tests/orm/test_Term.py::155": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_replace_remove_image", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/models/test_Term.py::156": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["assert_record_count_equals", "db", "pytest", "text"], "enclosing_function": "test_update_status_updates_date", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 47}, "tests/unit/book/test_stats.py::208": {"resolved_imports": ["lute/db/__init__.py", "lute/term/model.py", "lute/book/stats.py"], "used_names": [], "enclosing_function": "test_stats_only_update_books_marked_stale", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/acceptance/conftest.py::213": {"resolved_imports": [], "used_names": ["parsers", "then"], "enclosing_function": "then_title", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/acceptance/conftest.py::494": {"resolved_imports": [], "used_names": ["parsers", "then", "time"], "enclosing_function": "then_reading_page_term_form_iframe_shows_term", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/term/test_service_apply_ajax_update.py::34": {"resolved_imports": ["lute/models/repositories.py", "lute/db/__init__.py", "lute/term/service.py"], "used_names": ["TermRepository", "db"], "enclosing_function": "assert_updated", "extracted_code": "# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 1134}, "tests/orm/test_Text.py::61": {"resolved_imports": ["lute/models/book.py", "lute/db/__init__.py"], "used_names": ["Book", "Text", "TextBookmark", "WordsRead", "assert_record_count_equals", "datetime", "db"], "enclosing_function": "test_delete_text_cascade_deletes_bookmarks_leaves_wordsread", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass Text(db.Model):\n \"\"\"\n Each page in a Book.\n \"\"\"\n\n __tablename__ = \"texts\"\n\n id = db.Column(\"TxID\", db.Integer, primary_key=True)\n _text = db.Column(\"TxText\", db.String, nullable=False)\n order = db.Column(\"TxOrder\", db.Integer)\n start_date = db.Column(\"TxStartDate\", db.DateTime, nullable=True)\n _read_date = db.Column(\"TxReadDate\", db.DateTime, nullable=True)\n bk_id = db.Column(\"TxBkID\", db.Integer, db.ForeignKey(\"books.BkID\"), nullable=False)\n word_count = db.Column(\"TxWordCount\", db.Integer, nullable=True)\n\n book = db.relationship(\"Book\", back_populates=\"texts\")\n bookmarks = db.relationship(\n \"TextBookmark\",\n back_populates=\"text\",\n cascade=\"all, delete-orphan\",\n )\n sentences = db.relationship(\n \"Sentence\",\n back_populates=\"text\",\n order_by=\"Sentence.order\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, book, text, order=1):\n self.book = book\n self.text = text\n self.order = order\n self.sentences = []\n\n @property\n def title(self):\n \"\"\"\n Text title is the book title + page fraction.\n \"\"\"\n b = self.book\n s = f\"({self.order}/{self.book.page_count})\"\n t = f\"{b.title} {s}\"\n return t\n\n @property\n def text(self):\n return self._text\n\n @text.setter\n def text(self, s):\n self._text = s\n if s.strip() == \"\":\n return\n toks = self._get_parsed_tokens()\n wordtoks = [t for t in toks if t.is_word]\n self.word_count = len(wordtoks)\n if self._read_date is not None:\n self._load_sentences_from_tokens(toks)\n\n @property\n def read_date(self):\n return self._read_date\n\n @read_date.setter\n def read_date(self, s):\n self._read_date = s\n # Ensure loaded.\n self.load_sentences()\n\n def _get_parsed_tokens(self):\n \"Return the tokens.\"\n lang = self.book.language\n return lang.parser.get_parsed_tokens(self.text, lang)\n\n def _load_sentences_from_tokens(self, parsedtokens):\n \"Save sentences using the tokens.\"\n parser = self.book.language.parser\n self._remove_sentences()\n curr_sentence_tokens = []\n sentence_num = 1\n\n def _add_current():\n \"Create and add sentence from current state.\"\n if curr_sentence_tokens:\n se = Sentence.from_tokens(curr_sentence_tokens, parser, sentence_num)\n self._add_sentence(se)\n # Reset for the next sentence.\n curr_sentence_tokens.clear()\n\n for pt in parsedtokens:\n curr_sentence_tokens.append(pt)\n if pt.is_end_of_sentence:\n _add_current()\n sentence_num += 1\n\n # Add any stragglers.\n _add_current()\n\n def load_sentences(self):\n \"\"\"\n Parse the current text and create Sentence objects.\n \"\"\"\n toks = self._get_parsed_tokens()\n self._load_sentences_from_tokens(toks)\n\n def _add_sentence(self, sentence):\n \"Add a sentence to the Text.\"\n if sentence not in self.sentences:\n self.sentences.append(sentence)\n sentence.text = self\n\n def _remove_sentences(self):\n \"Remove all sentence from the Text.\"\n for sentence in self.sentences:\n sentence.text = None\n self.sentences = []\n\nclass WordsRead(db.Model):\n \"\"\"\n Tracks reading events for Text entities.\n \"\"\"\n\n __tablename__ = \"wordsread\"\n id = db.Column(\"WrID\", db.Integer, primary_key=True)\n language_id = db.Column(\n \"WrLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n tx_id = db.Column(\n \"WrTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"SET NULL\"),\n nullable=True,\n )\n read_date = db.Column(\"WrReadDate\", db.DateTime, nullable=False)\n word_count = db.Column(\"WrWordCount\", db.Integer, nullable=False)\n\n def __init__(self, text, read_date, word_count):\n self.tx_id = text.id\n self.language_id = text.book.language.id\n self.read_date = read_date\n self.word_count = word_count\n\nclass TextBookmark(db.Model):\n \"\"\"\n Bookmarks for a given Book page\n\n The TextBookmark includes a title\n \"\"\"\n\n __tablename__ = \"textbookmarks\"\n\n id = db.Column(\"TbID\", db.Integer, primary_key=True)\n tx_id = db.Column(\n \"TbTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"CASCADE\"),\n nullable=False,\n )\n title = db.Column(\"TbTitle\", db.Text, nullable=False)\n\n text = db.relationship(\"Text\", back_populates=\"bookmarks\")\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8481}, "tests/unit/book/test_Repository.py::49": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": ["assert_sql_result"], "enclosing_function": "test_save_new_book", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/config/test_app_config.py::26": {"resolved_imports": ["lute/config/app_config.py"], "used_names": ["AppConfig"], "enclosing_function": "test_valid_config", "extracted_code": "# Source: lute/config/app_config.py\nclass AppConfig: # pylint: disable=too-many-instance-attributes\n \"\"\"\n Configuration wrapper around yaml file.\n\n Adds various properties for lint-time checking.\n \"\"\"\n\n def __init__(self, config_file_path):\n \"\"\"\n Load the required configuration file.\n \"\"\"\n self._load_config(config_file_path)\n\n def _load_config(self, config_file_path):\n \"\"\"\n Load and validate the config file.\n \"\"\"\n with open(config_file_path, \"r\", encoding=\"utf-8\") as cf:\n config = yaml.safe_load(cf)\n\n if not isinstance(config, dict):\n raise RuntimeError(\n f\"File at {config_file_path} is invalid or is not a yaml dictionary.\"\n )\n\n self.env = config.get(\"ENV\", None)\n if self.env not in [\"prod\", \"dev\"]:\n raise ValueError(f\"ENV must be prod or dev, was {self.env}.\")\n\n self.is_docker = bool(config.get(\"IS_DOCKER\", False))\n\n # Database name.\n self.dbname = config.get(\"DBNAME\", None)\n if self.dbname is None:\n raise ValueError(\"Config file must have 'DBNAME'\")\n\n # Various invoke tasks in /tasks.py check if the database is a\n # test_ db prior to running some destructive action.\n self.is_test_db = self.dbname.startswith(\"test_\")\n\n # Path to user data.\n self.datapath = config.get(\"DATAPATH\", self._get_appdata_dir())\n self.plugin_datapath = os.path.join(self.datapath, \"plugins\")\n self.userimagespath = os.path.join(self.datapath, \"userimages\")\n self.useraudiopath = os.path.join(self.datapath, \"useraudio\")\n self.userthemespath = os.path.join(self.datapath, \"userthemes\")\n self.temppath = os.path.join(self.datapath, \"temp\")\n self.dbfilename = os.path.join(self.datapath, self.dbname)\n\n # Path to db backup.\n # When Lute starts up, it backs up the db\n # if migrations are going to be applied, just in case.\n # Hidden directory as a hint to the the user that\n # this is a system dir.\n self.system_backup_path = os.path.join(self.datapath, \".system_db_backups\")\n\n # Default backup path for user, can be overridden in settings.\n self.default_user_backup_path = config.get(\n \"BACKUP_PATH\", os.path.join(self.datapath, \"backups\")\n )\n\n def _get_appdata_dir(self):\n \"Get user's appdata directory from platformdirs.\"\n dirs = PlatformDirs(\"Lute3\", \"Lute3\")\n return dirs.user_data_dir\n\n @property\n def sqliteconnstring(self):\n \"Full sqlite connection string.\"\n return f\"sqlite:///{self.dbfilename}\"\n\n @staticmethod\n def configdir():\n \"Return the path to the configuration file directory.\"\n return os.path.dirname(os.path.realpath(__file__))\n\n @staticmethod\n def default_config_filename():\n \"Return the path to the default configuration file.\"\n thisdir = AppConfig.configdir()\n return os.path.join(thisdir, \"config.yml\")", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 3053}, "tests/unit/book/test_datatables.py::43": {"resolved_imports": ["lute/models/language.py", "lute/book/datatables.py", "lute/db/__init__.py", "lute/db/demo.py"], "used_names": ["db", "get_data_tables_list"], "enclosing_function": "test_smoke_book_datatables_query_runs", "extracted_code": "# Source: lute/book/datatables.py\ndef get_data_tables_list(parameters, is_archived, session):\n \"Book json data for datatables.\"\n archived = \"true\" if is_archived else \"false\"\n\n base_sql = f\"\"\"\n SELECT\n b.BkID As BkID,\n LgName,\n BkTitle,\n case when currtext.TxID is null then 1 else currtext.TxOrder end as PageNum,\n textcounts.pagecount AS PageCount,\n booklastopened.lastopeneddate AS LastOpenedDate,\n BkArchived,\n tags.taglist AS TagList,\n textcounts.wc AS WordCount,\n c.distinctterms as DistinctCount,\n c.distinctunknowns as UnknownCount,\n c.unknownpercent as UnknownPercent,\n c.status_distribution as StatusDistribution,\n case when completed_books.BkID is null then 0 else 1 end as IsCompleted\n\n FROM books b\n INNER JOIN languages ON LgID = b.BkLgID\n LEFT OUTER JOIN texts currtext ON currtext.TxID = BkCurrentTxID\n INNER JOIN (\n select TxBkID, max(TxStartDate) as lastopeneddate from texts group by TxBkID\n ) booklastopened on booklastopened.TxBkID = b.BkID\n INNER JOIN (\n SELECT TxBkID, SUM(TxWordCount) as wc, COUNT(TxID) AS pagecount\n FROM texts\n GROUP BY TxBkID\n ) textcounts on textcounts.TxBkID = b.BkID\n LEFT OUTER JOIN bookstats c on c.BkID = b.BkID\n\n LEFT OUTER JOIN (\n SELECT BtBkID as BkID, GROUP_CONCAT(T2Text, ', ') AS taglist\n FROM\n (\n SELECT BtBkID, T2Text\n FROM booktags bt\n INNER JOIN tags2 t2 ON t2.T2ID = bt.BtT2ID\n ORDER BY T2Text\n ) tagssrc\n GROUP BY BtBkID\n ) AS tags ON tags.BkID = b.BkID\n\n left outer join (\n select texts.TxBkID as BkID\n from texts\n inner join (\n /* last page in each book */\n select TxBkID, max(TxOrder) as maxTxOrder from texts group by TxBkID\n ) last_page on last_page.TxBkID = texts.TxBkID and last_page.maxTxOrder = texts.TxOrder\n where TxReadDate is not null\n ) completed_books on completed_books.BkID = b.BkID\n\n WHERE b.BkArchived = {archived}\n and languages.LgParserType in ({ supported_parser_type_criteria() })\n \"\"\"\n\n # Add \"where\" criteria for all the filters.\n language_id = parameters[\"filtLanguage\"]\n if language_id == \"null\" or language_id == \"undefined\" or language_id is None:\n language_id = \"0\"\n language_id = int(language_id)\n if language_id != 0:\n base_sql += f\" and LgID = {language_id}\"\n\n connection = session.connection()\n return DataTablesSqliteQuery.get_data(base_sql, parameters, connection)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 2650}, "tests/unit/cli/test_language_term_export.py::49": {"resolved_imports": ["lute/cli/language_term_export.py", "lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/db/demo.py"], "used_names": ["Term", "TermRepository", "assert_sql_result", "db", "generate_book_file", "generate_language_file", "make_book"], "enclosing_function": "test_single_book_export", "extracted_code": "# Source: lute/cli/language_term_export.py\ndef generate_language_file(language_name, outfile_name):\n \"\"\"\n Generate the datafile for the language.\n \"\"\"\n books = db.session.query(Book).all()\n books = [b for b in books if b.language.name == language_name]\n if len(books) == 0:\n print(f\"No books for given language {language_name}, quitting.\")\n else:\n print(f\"Writing to {outfile_name}\")\n _generate_file(books, outfile_name)\n print(\"Done. \")\n\ndef generate_book_file(bookid, outfile_name):\n \"\"\"\n Generate the datafile for the book.\n \"\"\"\n books = db.session.query(Book).all()\n books = [b for b in books if f\"{b.id}\" == f\"{bookid}\"]\n if len(books) == 0:\n print(f\"No book with id = {bookid}.\")\n else:\n print(f\"Writing to {outfile_name}\")\n _generate_file(books, outfile_name)\n print(\"Done. \")\n\n\n# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 9482}, "tests/unit/read/render/test_multiword_indexer.py::57": {"resolved_imports": ["lute/read/render/multiword_indexer.py"], "used_names": ["MultiwordTermIndexer"], "enclosing_function": "test_can_search_multiple_times_with_different_tokens", "extracted_code": "# Source: lute/read/render/multiword_indexer.py\nclass MultiwordTermIndexer:\n \"\"\"\n Find terms in strings using ahocorapy.\n \"\"\"\n\n zws = \"\\u200B\" # zero-width space\n\n def __init__(self):\n self.kwtree = KeywordTree(case_insensitive=True)\n self.finalized = False\n\n def add(self, t):\n \"Add zws-enclosed term to tree.\"\n add_t = f\"{self.zws}{t}{self.zws}\"\n self.kwtree.add(add_t)\n\n def search_all(self, lc_tokens):\n \"Find all terms and starting token index.\"\n if not self.finalized:\n self.kwtree.finalize()\n self.finalized = True\n\n zws = self.zws\n content = zws + zws.join(lc_tokens) + zws\n zwsindexes = [i for i, char in enumerate(content) if char == zws]\n results = self.kwtree.search_all(content)\n\n for result in results:\n # print(f\"{result}\\n\", flush=True)\n t = result[0].strip(zws)\n charpos = result[1]\n index = zwsindexes.index(charpos)\n yield (t, index)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1035}, "tests/unit/read/render/test_multiword_indexer.py::43": {"resolved_imports": ["lute/read/render/multiword_indexer.py"], "used_names": ["MultiwordTermIndexer", "pytest"], "enclosing_function": "test_scenario", "extracted_code": "# Source: lute/read/render/multiword_indexer.py\nclass MultiwordTermIndexer:\n \"\"\"\n Find terms in strings using ahocorapy.\n \"\"\"\n\n zws = \"\\u200B\" # zero-width space\n\n def __init__(self):\n self.kwtree = KeywordTree(case_insensitive=True)\n self.finalized = False\n\n def add(self, t):\n \"Add zws-enclosed term to tree.\"\n add_t = f\"{self.zws}{t}{self.zws}\"\n self.kwtree.add(add_t)\n\n def search_all(self, lc_tokens):\n \"Find all terms and starting token index.\"\n if not self.finalized:\n self.kwtree.finalize()\n self.finalized = True\n\n zws = self.zws\n content = zws + zws.join(lc_tokens) + zws\n zwsindexes = [i for i, char in enumerate(content) if char == zws]\n results = self.kwtree.search_all(content)\n\n for result in results:\n # print(f\"{result}\\n\", flush=True)\n t = result[0].strip(zws)\n charpos = result[1]\n index = zwsindexes.index(charpos)\n yield (t, index)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1035}, "tests/orm/test_Term.py::201": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_remove_flash_message", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/orm/test_Book.py::43": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_save_book", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 47}, "tests/unit/db/test_management.py::40": {"resolved_imports": ["lute/db/__init__.py", "lute/models/setting.py", "lute/models/repositories.py", "lute/db/management.py"], "used_names": ["UserSetting", "assert_record_count_equals", "db", "delete_all_data"], "enclosing_function": "test_wiping_db_clears_out_all_tables", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/setting.py\nclass UserSetting(SettingBase):\n \"User setting.\"\n __tablename__ = None\n __mapper_args__ = {\"polymorphic_identity\": \"user\"}\n\n\n# Source: lute/db/management.py\ndef delete_all_data(session):\n \"\"\"\n DANGEROUS! Delete everything, restore user settings, clear sys settings.\n\n NO CHECKS ARE PERFORMED.\n \"\"\"\n\n # Setting the pragma first ensures cascade delete.\n statements = [\n \"pragma foreign_keys = ON\",\n \"delete from languages\",\n \"delete from tags\",\n \"delete from tags2\",\n \"delete from settings\",\n ]\n for s in statements:\n session.execute(text(s))\n session.commit()\n add_default_user_settings(session, current_app.env_config.default_user_backup_path)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 808}, "tests/orm/test_Term.py::76": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_term_parent_with_two_children", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/db/test_demo.py::38": {"resolved_imports": ["lute/db/__init__.py", "lute/db/demo.py", "lute/parse/registry.py"], "used_names": [], "enclosing_function": "test_new_db_doesnt_contain_anything", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/book/test_datatables.py::70": {"resolved_imports": ["lute/models/language.py", "lute/book/datatables.py", "lute/db/__init__.py", "lute/db/demo.py"], "used_names": ["datetime", "db", "get_data_tables_list", "make_book"], "enclosing_function": "test_book_data_says_completed_if_last_page_has_been_read", "extracted_code": "# Source: lute/book/datatables.py\ndef get_data_tables_list(parameters, is_archived, session):\n \"Book json data for datatables.\"\n archived = \"true\" if is_archived else \"false\"\n\n base_sql = f\"\"\"\n SELECT\n b.BkID As BkID,\n LgName,\n BkTitle,\n case when currtext.TxID is null then 1 else currtext.TxOrder end as PageNum,\n textcounts.pagecount AS PageCount,\n booklastopened.lastopeneddate AS LastOpenedDate,\n BkArchived,\n tags.taglist AS TagList,\n textcounts.wc AS WordCount,\n c.distinctterms as DistinctCount,\n c.distinctunknowns as UnknownCount,\n c.unknownpercent as UnknownPercent,\n c.status_distribution as StatusDistribution,\n case when completed_books.BkID is null then 0 else 1 end as IsCompleted\n\n FROM books b\n INNER JOIN languages ON LgID = b.BkLgID\n LEFT OUTER JOIN texts currtext ON currtext.TxID = BkCurrentTxID\n INNER JOIN (\n select TxBkID, max(TxStartDate) as lastopeneddate from texts group by TxBkID\n ) booklastopened on booklastopened.TxBkID = b.BkID\n INNER JOIN (\n SELECT TxBkID, SUM(TxWordCount) as wc, COUNT(TxID) AS pagecount\n FROM texts\n GROUP BY TxBkID\n ) textcounts on textcounts.TxBkID = b.BkID\n LEFT OUTER JOIN bookstats c on c.BkID = b.BkID\n\n LEFT OUTER JOIN (\n SELECT BtBkID as BkID, GROUP_CONCAT(T2Text, ', ') AS taglist\n FROM\n (\n SELECT BtBkID, T2Text\n FROM booktags bt\n INNER JOIN tags2 t2 ON t2.T2ID = bt.BtT2ID\n ORDER BY T2Text\n ) tagssrc\n GROUP BY BtBkID\n ) AS tags ON tags.BkID = b.BkID\n\n left outer join (\n select texts.TxBkID as BkID\n from texts\n inner join (\n /* last page in each book */\n select TxBkID, max(TxOrder) as maxTxOrder from texts group by TxBkID\n ) last_page on last_page.TxBkID = texts.TxBkID and last_page.maxTxOrder = texts.TxOrder\n where TxReadDate is not null\n ) completed_books on completed_books.BkID = b.BkID\n\n WHERE b.BkArchived = {archived}\n and languages.LgParserType in ({ supported_parser_type_criteria() })\n \"\"\"\n\n # Add \"where\" criteria for all the filters.\n language_id = parameters[\"filtLanguage\"]\n if language_id == \"null\" or language_id == \"undefined\" or language_id is None:\n language_id = \"0\"\n language_id = int(language_id)\n if language_id != 0:\n base_sql += f\" and LgID = {language_id}\"\n\n connection = session.connection()\n return DataTablesSqliteQuery.get_data(base_sql, parameters, connection)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 2650}, "tests/unit/themes/test_service.py::19": {"resolved_imports": ["lute/themes/service.py", "lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["Service", "db"], "enclosing_function": "test_list_themes", "extracted_code": "# Source: lute/themes/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _css_path(self):\n \"\"\"\n Path to css in this folder.\n \"\"\"\n thisdir = os.path.dirname(__file__)\n theme_dir = os.path.join(thisdir, \"css\")\n return os.path.abspath(theme_dir)\n\n def list_themes(self):\n \"\"\"\n List of theme file names and user-readable name.\n \"\"\"\n\n def _make_display_name(s):\n ret = os.path.basename(s)\n ret = ret.replace(\".css\", \"\").replace(\"_\", \" \")\n return ret\n\n g = glob(os.path.join(self._css_path(), \"*.css\"))\n themes = [(os.path.basename(f), _make_display_name(f)) for f in g]\n theme_basenames = [t[0] for t in themes]\n\n g = glob(os.path.join(current_app.env_config.userthemespath, \"*.css\"))\n additional_user_themes = [\n (os.path.basename(f), _make_display_name(f))\n for f in g\n if os.path.basename(f) not in theme_basenames\n ]\n\n themes += additional_user_themes\n sorted_themes = sorted(themes, key=lambda x: x[1])\n return [default_entry] + sorted_themes\n\n def get_current_css(self):\n \"\"\"\n Return the current css pointed at by the current_theme user setting.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n if current_theme == default_entry[0]:\n return \"\"\n\n def _get_theme_css_in_dir(d):\n \"Get css, or '' if no file.\"\n fname = os.path.join(d, current_theme)\n if not os.path.exists(fname):\n return \"\"\n with open(fname, \"r\", encoding=\"utf-8\") as f:\n return f.read()\n\n ret = _get_theme_css_in_dir(self._css_path())\n add = _get_theme_css_in_dir(current_app.env_config.userthemespath)\n if add != \"\":\n ret += f\"\\n\\n/* Additional user css */\\n\\n{add}\"\n return ret\n\n def next_theme(self):\n \"\"\"\n Move to the next theme in the list of themes.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n themes = [t[0] for t in self.list_themes()]\n themes.append(default_entry[0])\n for i in range(0, len(themes)): # pylint: disable=consider-using-enumerate\n if themes[i] == current_theme:\n new_index = i + 1\n break\n repo.set_value(\"current_theme\", themes[new_index])\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2663}, "tests/orm/test_Language.py::38": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Language", "assert_sql_result", "db"], "enclosing_function": "test_save_new_language", "extracted_code": "# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 6039}, "tests/orm/test_Book.py::111": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["Book", "BookStats", "db"], "enclosing_function": "test_load_book_loads_lang", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass BookStats(db.Model):\n \"The stats table.\"\n __tablename__ = \"bookstats\"\n\n BkID = db.Column(db.Integer, primary_key=True)\n distinctterms = db.Column(db.Integer)\n distinctunknowns = db.Column(db.Integer)\n unknownpercent = db.Column(db.Integer)\n status_distribution = db.Column(db.String, nullable=True)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 4102}, "tests/unit/read/test_service_popup_data.py::84": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Term", "db"], "enclosing_function": "test_term_with_no_parents", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 7471}, "plugins/lute-thai/tests/test_ThaiParser.py::28": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["Term"], "enclosing_function": "test_token_count", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7421}, "tests/orm/test_Language.py::93": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Language", "LanguageDictionary", "LanguageRepository", "assert_sql_result", "db", "json"], "enclosing_function": "test_language_dictionaries_smoke_test", "extracted_code": "# Source: lute/models/language.py\nclass LanguageDictionary(db.Model):\n \"\"\"\n Language dictionary.\n \"\"\"\n\n __tablename__ = \"languagedicts\"\n\n id = db.Column(\"LdID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\n \"LdLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n language = db.relationship(\"Language\", back_populates=\"dictionaries\")\n usefor = db.Column(\"LdUseFor\", db.String(20), nullable=False)\n dicttype = db.Column(\"LdType\", db.String(20), nullable=False)\n dicturi = db.Column(\"LdDictURI\", db.String(200), nullable=False)\n is_active = db.Column(\"LdIsActive\", db.Boolean, default=True)\n sort_order = db.Column(\"LdSortOrder\", db.SmallInteger, nullable=False)\n\n # HACK: pre-pend '*' to URLs that need to open a new window.\n # This is a relic of the original code, and should be changed.\n # TODO remove-asterisk-hack: remove * from URL start.\n def make_uri(self):\n \"Hack add asterisk.\"\n prepend = \"*\" if self.dicttype == \"popuphtml\" else \"\"\n return f\"{prepend}{self.dicturi}\"\n\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/models/repositories.py\nclass LanguageRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, language_id):\n \"Get by ID.\"\n return self.session.query(Language).filter(Language.id == language_id).first()\n\n def find_by_name(self, name):\n \"Get by name.\"\n return (\n self.session.query(Language)\n .filter(func.lower(Language.name) == func.lower(name))\n .first()\n )\n\n def all_dictionaries(self):\n \"All dictionaries for all languages.\"\n lang_dicts = {}\n for lang in db.session.query(Language).all():\n lang_dicts[lang.id] = {\n \"term\": lang.active_dict_uris(\"terms\"),\n \"sentence\": lang.active_dict_uris(\"sentences\"),\n }\n return lang_dicts\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 7952}, "tests/unit/models/test_Term.py::85": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Term", "TermRepository", "db"], "enclosing_function": "test_find_by_spec", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 8558}, "tests/unit/read/render/test_service.py::22": {"resolved_imports": ["lute/parse/base.py", "lute/read/render/service.py", "lute/db/__init__.py", "lute/models/term.py"], "used_names": ["Service", "db"], "enclosing_function": "_run_scenario", "extracted_code": "# Source: lute/read/render/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def find_all_Terms_in_string(self, s, language): # pylint: disable=too-many-locals\n \"\"\"\n Find all terms contained in the string s.\n\n For example\n - given s = \"Here is a cat\"\n - given terms in the db: [ \"cat\", \"a cat\", \"dog\" ]\n\n This would return the terms \"cat\" and \"a cat\".\n \"\"\"\n cleaned = re.sub(r\" +\", \" \", s)\n tokens = language.get_parsed_tokens(cleaned)\n return self._find_all_terms_in_tokens(tokens, language)\n\n def _get_multiword_terms(self, language):\n \"Get all multiword terms.\"\n sql = sqltext(\n \"\"\"\n SELECT WoID, WoTextLC FROM words\n WHERE WoLgID=:language_id and WoTokenCount>1\n \"\"\"\n )\n sql = sql.bindparams(language_id=language.id)\n return self.session.execute(sql).all()\n\n def _find_all_multi_word_term_text_lcs_in_content(self, text_lcs, language):\n \"Find multiword terms, return list of text_lcs.\"\n\n # There are a few ways of finding multi-word Terms\n # (with token_count > 1) in the content:\n #\n # 1. load each mword term text_lc via sql and check.\n # 2. using the model\n # 3. SQL with \"LIKE\"\n #\n # During reasonable test runs with my data, the times in seconds\n # for each are similar (~0.02, ~0.05, ~0.025). This method is\n # only used for small amounts of data, and the user experience hit\n # is negligible, so I'll use the first method which IMO is the clearest\n # code.\n\n zws = \"\\u200B\" # zero-width space\n content = zws + zws.join(text_lcs) + zws\n\n # Method 1:\n reclist = self._get_multiword_terms(language)\n return [p[1] for p in reclist if f\"{zws}{p[1]}{zws}\" in content]\n\n ## # Method 2: use the model.\n ## contained_term_qry = self.session.query(Term).filter(\n ## Term.language == language,\n ## Term.token_count > 1,\n ## func.instr(content, Term.text_lc) > 0,\n ## )\n ## return [r.text_lc for r in contained_term_qry.all()]\n\n ## # Method 3: Query with LIKE\n ## sql = sqltext(\n ## \"\"\"\n ## SELECT WoTextLC FROM words\n ## WHERE WoLgID=:lid and WoTokenCount>1\n ## AND :content LIKE '%' || :zws || WoTextLC || :zws || '%'\n ## \"\"\"\n ## )\n ## sql = sql.bindparams(lid=language.id, content=content, zws=zws)\n ## recs = self.session.execute(sql).all()\n ## return [r[0] for r in recs]\n\n def _find_all_terms_in_tokens(self, tokens, language, kwtree=None):\n \"\"\"\n Find all terms contained in the (ordered) parsed tokens tokens.\n\n For example\n - given tokens = \"Here\", \" \", \"is\", \" \", \"a\", \" \", \"cat\"\n - given terms in the db: [ \"cat\", \"a/ /cat\", \"dog\" ]\n\n This would return the terms \"cat\" and \"a/ /cat\".\n\n Method:\n - build list of lowercase text in the tokens\n - append all multword term strings that exist in the content\n - query for Terms that exist in the list\n\n Note: this method only uses indexes for multiword terms, as any\n content analyzed is first parsed into tokens before being passed\n to this routine. There's no need to search for single-word Terms\n in the tokenized strings, they can be found by a simple query.\n \"\"\"\n\n # Performance: About half of the time in this routine is spent in\n # Step 1 (finding multiword terms), the rest in step 2 (the actual\n # query).\n # dt = DebugTimer(\"_find_all_terms_in_tokens\", display=True)\n\n parser = language.parser\n text_lcs = [parser.get_lowercase(t.token) for t in tokens]\n\n # Step 1: get the multiwords in the content.\n if kwtree is None:\n mword_terms = self._find_all_multi_word_term_text_lcs_in_content(\n text_lcs, language\n )\n else:\n results = kwtree.search_all(text_lcs)\n mword_terms = [r[0] for r in results]\n # dt.step(\"filtered mword terms\")\n\n # Step 2: load the Term objects.\n #\n # The Term fetch is actually performant -- there is no\n # real difference between loading the Term objects versus\n # loading raw data with SQL and getting dicts.\n #\n # Code for getting raw data:\n # param_keys = [f\"w{i}\" for i, _ in enumerate(text_lcs)]\n # keys_placeholders = ','.join([f\":{k}\" for k in param_keys])\n # param_dict = dict(zip(param_keys, text_lcs))\n # param_dict[\"langid\"] = language.id\n # sql = sqltext(f\"\"\"SELECT WoID, WoTextLC FROM words\n # WHERE WoLgID=:langid and WoTextLC in ({keys_placeholders})\"\"\")\n # sql = sql.bindparams(language.id, *text_lcs)\n # results = self.session.execute(sql, param_dict).fetchall()\n text_lcs.extend(mword_terms)\n tok_strings = list(set(text_lcs))\n terms_matching_tokens_qry = self.session.query(Term).filter(\n Term.text_lc.in_(tok_strings), Term.language == language\n )\n all_terms = terms_matching_tokens_qry.all()\n # dt.step(\"exec query\")\n\n return all_terms\n\n def get_textitems(self, s, language, multiword_term_indexer=None):\n \"\"\"\n Get array of TextItems for the string s.\n\n The multiword_term_indexer is a big performance boost, but takes\n time to initialize.\n \"\"\"\n # Hacky reset of state of ParsedToken state.\n # _Shouldn't_ be needed but doesn't hurt, even if it's lame.\n ParsedToken.reset_counters()\n\n cleaned = re.sub(r\" +\", \" \", s)\n tokens = language.get_parsed_tokens(cleaned)\n terms = self._find_all_terms_in_tokens(tokens, language, multiword_term_indexer)\n textitems = calc_get_textitems(tokens, terms, language, multiword_term_indexer)\n return textitems\n\n def get_multiword_indexer(self, language):\n \"Return indexer loaded with all multiword terms.\"\n mw = MultiwordTermIndexer()\n for r in self._get_multiword_terms(language):\n mw.add(r[1])\n return mw\n\n def get_paragraphs(self, s, language):\n \"\"\"\n Get array of arrays of TextItems for the given string s.\n\n This doesn't use an indexer, as it should only be used\n for a single page of text!\n \"\"\"\n textitems = self.get_textitems(s, language)\n\n def _split_textitems_by_paragraph(textitems):\n \"Split by ¶\"\n ret = []\n curr_para = []\n for t in textitems:\n if t.text == \"¶\":\n ret.append(curr_para)\n curr_para = []\n else:\n curr_para.append(t)\n if len(curr_para) > 0:\n ret.append(curr_para)\n return ret\n\n def _split_by_sentence_number(p):\n sentences = [\n list(sentence)\n for _, sentence in itertools.groupby(p, key=lambda t: t.sentence_number)\n ]\n for s in sentences:\n s[0].add_html_class(\"sentencestart\")\n return sentences\n\n paras = [\n _split_by_sentence_number(list(sentences))\n for sentences in _split_textitems_by_paragraph(textitems)\n ]\n\n return paras\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 7547}, "tests/orm/test_Term.py::70": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_term_parent_with_two_children", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/db/setup/test_Setup.py::184": {"resolved_imports": ["lute/db/setup/main.py", "lute/db/setup/migrator.py"], "used_names": ["BackupManager", "Setup", "closing", "os", "sqlite3"], "enclosing_function": "test_happy_path_no_existing_database", "extracted_code": "# Source: lute/db/setup/main.py\nclass BackupManager: # pylint: disable=too-few-public-methods\n \"\"\"\n Creates db backups when needed, prunes old backups.\n \"\"\"\n\n def __init__(self, file_to_backup, backup_directory, max_number_of_backups):\n self.file_to_backup = file_to_backup\n self.backup_directory = backup_directory\n self.max_number_of_backups = max_number_of_backups\n\n def do_backup(self, next_backup_datetime=None):\n \"\"\"\n Perform the db file backup to backup_dir,\n pruning old backups.\n \"\"\"\n\n if next_backup_datetime is None:\n now = datetime.now()\n next_backup_datetime = now.strftime(\"%Y%m%d-%H%M%S-%f\")\n\n bname = os.path.basename(self.file_to_backup)\n backup_filename = f\"{bname}.{next_backup_datetime}.gz\"\n backup_path = os.path.join(self.backup_directory, backup_filename)\n\n os.makedirs(self.backup_directory, exist_ok=True)\n\n # Copy the file to the backup directory and gzip it\n with open(self.file_to_backup, \"rb\") as source_file, gzip.open(\n backup_path, \"wb\"\n ) as backup_file:\n shutil.copyfileobj(source_file, backup_file)\n assert os.path.exists(backup_path)\n\n # List all backup files in the directory, sorted by name.\n # Since this includes the timestamp, the oldest files will be\n # listed first.\n globname = f\"{bname}.*.gz\"\n globpath = os.path.join(self.backup_directory, globname)\n backup_files = glob.glob(globpath)\n backup_files.sort(key=os.path.basename)\n\n # Delete excess backup files if necessary\n while len(backup_files) > self.max_number_of_backups:\n file_to_delete = backup_files.pop(0)\n os.remove(file_to_delete)\n\nclass Setup: # pylint: disable=too-few-public-methods\n \"\"\"\n Main setup class, coordinates other classes.\n \"\"\"\n\n def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments\n self,\n db_filename: str,\n baseline_schema_file: str,\n backup_manager: BackupManager,\n migrator: SqliteMigrator,\n output_func=None,\n ):\n self._db_filename = db_filename\n self._baseline_schema_file = baseline_schema_file\n self._backup_mgr = backup_manager\n self._migrator = migrator\n self._output_func = output_func\n\n def setup(self):\n \"\"\"\n Do database setup, making backup if necessary, running migrations.\n \"\"\"\n new_db = False\n has_migrations = False\n\n if not os.path.exists(self._db_filename):\n new_db = True\n # Note openin a connection creates a db file,\n # so this has to be done after the existence\n # check.\n with closing(self._open_connection()) as conn:\n self._create_baseline(conn)\n\n with closing(self._open_connection()) as conn:\n has_migrations = self._migrator.has_migrations(conn)\n\n # Don't do a backup with an open connection ...\n # I don't _think_ it matters, but better to be safe.\n def null_print(s): # pylint: disable=unused-argument\n pass\n\n outfunc = self._output_func or null_print\n if not new_db and has_migrations:\n outfunc(\"Creating backup before running migrations ...\")\n self._backup_mgr.do_backup()\n outfunc(\"Done backup.\")\n\n with closing(self._open_connection()) as conn:\n self._migrator.do_migration(conn)\n\n def _open_connection(self):\n \"\"\"\n Get connection to db_filename. Callers must close.\n \"\"\"\n return sqlite3.connect(self._db_filename, detect_types=sqlite3.PARSE_DECLTYPES)\n\n def _create_baseline(self, conn):\n \"\"\"\n Create baseline database.\n \"\"\"\n b = self._baseline_schema_file\n with open(b, \"r\", encoding=\"utf8\") as f:\n sql = f.read()\n conn.executescript(sql)", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 3995}, "tests/integration/test_main.py::25": {"resolved_imports": ["lute/config/app_config.py", "lute/app_factory.py"], "used_names": ["AppConfig", "closing", "create_app", "os", "sqlite3"], "enclosing_function": "test_init_no_existing_database", "extracted_code": "# Source: lute/config/app_config.py\nclass AppConfig: # pylint: disable=too-many-instance-attributes\n \"\"\"\n Configuration wrapper around yaml file.\n\n Adds various properties for lint-time checking.\n \"\"\"\n\n def __init__(self, config_file_path):\n \"\"\"\n Load the required configuration file.\n \"\"\"\n self._load_config(config_file_path)\n\n def _load_config(self, config_file_path):\n \"\"\"\n Load and validate the config file.\n \"\"\"\n with open(config_file_path, \"r\", encoding=\"utf-8\") as cf:\n config = yaml.safe_load(cf)\n\n if not isinstance(config, dict):\n raise RuntimeError(\n f\"File at {config_file_path} is invalid or is not a yaml dictionary.\"\n )\n\n self.env = config.get(\"ENV\", None)\n if self.env not in [\"prod\", \"dev\"]:\n raise ValueError(f\"ENV must be prod or dev, was {self.env}.\")\n\n self.is_docker = bool(config.get(\"IS_DOCKER\", False))\n\n # Database name.\n self.dbname = config.get(\"DBNAME\", None)\n if self.dbname is None:\n raise ValueError(\"Config file must have 'DBNAME'\")\n\n # Various invoke tasks in /tasks.py check if the database is a\n # test_ db prior to running some destructive action.\n self.is_test_db = self.dbname.startswith(\"test_\")\n\n # Path to user data.\n self.datapath = config.get(\"DATAPATH\", self._get_appdata_dir())\n self.plugin_datapath = os.path.join(self.datapath, \"plugins\")\n self.userimagespath = os.path.join(self.datapath, \"userimages\")\n self.useraudiopath = os.path.join(self.datapath, \"useraudio\")\n self.userthemespath = os.path.join(self.datapath, \"userthemes\")\n self.temppath = os.path.join(self.datapath, \"temp\")\n self.dbfilename = os.path.join(self.datapath, self.dbname)\n\n # Path to db backup.\n # When Lute starts up, it backs up the db\n # if migrations are going to be applied, just in case.\n # Hidden directory as a hint to the the user that\n # this is a system dir.\n self.system_backup_path = os.path.join(self.datapath, \".system_db_backups\")\n\n # Default backup path for user, can be overridden in settings.\n self.default_user_backup_path = config.get(\n \"BACKUP_PATH\", os.path.join(self.datapath, \"backups\")\n )\n\n def _get_appdata_dir(self):\n \"Get user's appdata directory from platformdirs.\"\n dirs = PlatformDirs(\"Lute3\", \"Lute3\")\n return dirs.user_data_dir\n\n @property\n def sqliteconnstring(self):\n \"Full sqlite connection string.\"\n return f\"sqlite:///{self.dbfilename}\"\n\n @staticmethod\n def configdir():\n \"Return the path to the configuration file directory.\"\n return os.path.dirname(os.path.realpath(__file__))\n\n @staticmethod\n def default_config_filename():\n \"Return the path to the default configuration file.\"\n thisdir = AppConfig.configdir()\n return os.path.join(thisdir, \"config.yml\")\n\n\n# Source: lute/app_factory.py\ndef create_app(\n app_config_path=None,\n extra_config=None,\n output_func=None,\n):\n \"\"\"\n App factory. Calls dbsetup, and returns Flask app.\n\n Args:\n - app_config_path: path to yml file. If None, use root config or default.\n - extra_config: dict, e.g. pass { 'TESTING': True } during unit tests.\n \"\"\"\n\n def null_print(s): # pylint: disable=unused-argument\n pass\n\n outfunc = output_func or null_print\n\n if app_config_path is None:\n if os.path.exists(\"config.yml\"):\n app_config_path = \"config.yml\"\n else:\n app_config_path = AppConfig.default_config_filename()\n\n app_config = AppConfig(app_config_path)\n _setup_app_dirs(app_config)\n setup_db(app_config, output_func)\n\n if extra_config is None:\n extra_config = {}\n outfunc(\"Initializing app.\")\n app = _create_app(app_config, extra_config)\n\n # Plugins are loaded after the app, as they may use settings etc.\n _init_parser_plugins(app_config.plugin_datapath, outfunc)\n\n return app", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 4123}, "plugins/lute-mandarin/tests/test_MandarinParser.py::32": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["Term", "pytest"], "enclosing_function": "test_token_count", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 7421}, "tests/unit/models/test_Setting.py::141": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["patch"], "enclosing_function": "test_time_since_last_backup_in_past", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/book/test_Repository.py::210": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": ["assert_sql_result", "pytest"], "enclosing_function": "test_delete", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_field_mapping.py::145": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "get_values_and_media_mapping"], "enclosing_function": "test_filtered_parents_tag_replacements", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\ndef get_values_and_media_mapping(term, sentence_lookup, mapping):\n \"\"\"\n Get the value replacements to be put in the mapping, and build\n dict of new filenames to original filenames.\n \"\"\"\n\n def all_translations():\n ret = [term.translation or \"\"]\n for p in term.parents:\n if p.translation not in ret:\n ret.append(p.translation or \"\")\n return [r for r in ret if r.strip() != \"\"]\n\n def parse_keys_needing_calculation(calculate_keys, media_mappings):\n \"\"\"\n Build a parser for some keys in the mapping string, return\n calculated value to use in the mapping. SIDE EFFECT:\n adds ankiconnect post actions to post_actions if needed\n (e.g. for image uploads).\n\n e.g. the mapping \"article: { tags:[\"der\", \"die\", \"das\"] }\"\n needs to be parsed to extract certain tags from the current\n term.\n \"\"\"\n\n def _filtered_tags_in_term_list(term_list, tagvals):\n \"Get all unique tags.\"\n # tagvals is a pyparsing ParseResults, use list() to convert to strings.\n ttext = [tt.text for t in term_list for tt in t.term_tags]\n ttext = sorted(list(set(ttext)))\n ftags = [tt for tt in ttext if tt in list(tagvals)]\n return \", \".join(ftags)\n\n def get_filtered_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list([term], tagvals)\n\n def get_filtered_parents_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list(term.parents, tagvals)\n\n def handle_image(_):\n id_images = [\n (t, t.get_current_image())\n for t in _all_terms(term)\n if t.get_current_image() is not None\n ]\n image_srcs = []\n for t, imgfilename in id_images:\n new_filename = f\"LUTE_TERM_{t.id}.jpg\"\n image_url = f\"/userimages/{t.language.id}/{imgfilename}\"\n media_mappings[new_filename] = image_url\n image_srcs.append(f'')\n\n return \"\".join(image_srcs)\n\n def handle_sentences(_):\n \"Get sample sentence for term.\"\n if term.id is None:\n # Dummy parse.\n return \"\"\n return sentence_lookup.get_sentence_for_term(term.id)\n\n quotedString.setParseAction(pp.removeQuotes)\n tagvallist = Suppress(\"[\") + pp.delimitedList(quotedString) + Suppress(\"]\")\n tagcrit = tagvallist | QuotedString(quoteChar='\"')\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n\n image = Suppress(\"image\")\n sentence = Suppress(\"sentence\")\n\n matcher = (\n tag_matcher.set_parse_action(get_filtered_tags)\n | parents_tag_matcher.set_parse_action(get_filtered_parents_tags)\n | image.set_parse_action(handle_image)\n | sentence.set_parse_action(handle_sentences)\n )\n\n calc_replacements = {\n # Matchers return the value that should be used as the\n # replacement value for the given mapping string. e.g.\n # tags[\"der\", \"die\"] returns \"der\" if term.tags = [\"der\", \"x\"]\n k: matcher.parseString(k).asList()[0]\n for k in calculate_keys\n }\n\n return calc_replacements\n\n def remove_zws(replacements_dict):\n cleaned = {}\n for key, value in replacements_dict.items():\n if isinstance(value, str):\n cleaned[key] = value.replace(\"\\u200B\", \"\")\n else:\n cleaned[key] = value\n return cleaned\n\n # One-for-one replacements in the mapping string.\n # e.g. \"{ id }\" is replaced by term.termid.\n replacements = {\n \"id\": term.id,\n \"term\": term.text,\n \"language\": term.language.name,\n \"parents\": \", \".join([p.text for p in term.parents]),\n \"tags\": \", \".join(sorted({tt.text for tt in term.term_tags})),\n \"translation\": \"
\".join(all_translations()),\n \"pronunciation\": term.romanization,\n \"parents.pronunciation\": \", \".join(\n [p.romanization or \"\" for p in term.parents]\n ),\n }\n\n mapping_string = \"; \".join(mapping.values())\n calc_keys = [\n k\n for k in set(re.findall(r\"{\\s*(.*?)\\s*}\", mapping_string))\n if k not in replacements\n ]\n\n media_mappings = {}\n calc_replacements = parse_keys_needing_calculation(calc_keys, media_mappings)\n\n final_replacements = {**replacements, **calc_replacements}\n cleaned = remove_zws(final_replacements)\n return (cleaned, media_mappings)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4848}, "tests/unit/models/test_Language.py::36": {"resolved_imports": ["lute/db/__init__.py", "lute/db/demo.py", "lute/models/language.py", "lute/models/repositories.py"], "used_names": ["Language"], "enclosing_function": "test_new_language_has_sane_defaults", "extracted_code": "# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 5989}, "tests/unit/ankiexport/test_service.py::96": {"resolved_imports": ["lute/models/srsexport.py", "lute/ankiexport/service.py"], "used_names": ["Service"], "enclosing_function": "test_validate_only_checks_active_specs", "extracted_code": "# Source: lute/ankiexport/service.py\nclass Service:\n \"Srs export service.\"\n\n def __init__(\n self,\n anki_deck_names,\n anki_note_types_and_fields,\n export_specs,\n ):\n \"init\"\n self.anki_deck_names = anki_deck_names\n self.anki_note_types_and_fields = anki_note_types_and_fields\n self.export_specs = export_specs\n\n def validate_spec(self, spec):\n \"\"\"\n Returns array of errors if any for the given spec.\n \"\"\"\n if not spec.active:\n return []\n\n errors = []\n\n try:\n validate_criteria(spec.criteria)\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n if spec.deck_name not in self.anki_deck_names:\n errors.append(f'No deck name \"{spec.deck_name}\"')\n\n valid_note_type = spec.note_type in self.anki_note_types_and_fields\n if not valid_note_type:\n errors.append(f'No note type \"{spec.note_type}\"')\n\n mapping = None\n try:\n mapping = json.loads(spec.field_mapping)\n except json.decoder.JSONDecodeError:\n errors.append(\"Mapping is not valid json\")\n\n if valid_note_type and mapping:\n note_fields = self.anki_note_types_and_fields.get(spec.note_type, {})\n bad_fields = [f for f in mapping.keys() if f not in note_fields]\n if len(bad_fields) > 0:\n bad_fields = \", \".join(bad_fields)\n msg = f\"Note type {spec.note_type} does not have field(s): {bad_fields}\"\n errors.append(msg)\n\n if mapping:\n try:\n validate_mapping(json.loads(spec.field_mapping))\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n return errors\n\n def validate_specs(self):\n \"\"\"\n Return hash of spec ids and any config errors.\n \"\"\"\n failures = {}\n for spec in self.export_specs:\n v = self.validate_spec(spec)\n if len(v) != 0:\n failures[spec.id] = \"; \".join(v)\n return failures\n\n def validate_specs_failure_message(self):\n \"Failure message for alerts.\"\n failures = self.validate_specs()\n msgs = []\n for k, v in failures.items():\n spec = next(s for s in self.export_specs if s.id == k)\n msgs.append(f\"{spec.export_name}: {v}\")\n return msgs\n\n def _all_terms(self, term):\n \"Term and any parents.\"\n ret = [term]\n ret.extend(term.parents)\n return ret\n\n def _all_tags(self, term):\n \"Tags for term and all parents.\"\n ret = [tt.text for t in self._all_terms(term) for tt in t.term_tags]\n return sorted(list(set(ret)))\n\n # pylint: disable=too-many-arguments,too-many-positional-arguments\n def _build_ankiconnect_post_json(\n self,\n mapping,\n media_mappings,\n lute_and_term_tags,\n deck_name,\n model_name,\n ):\n \"Build post json for term using the mappings.\"\n\n post_actions = []\n for new_filename, original_url in media_mappings.items():\n hsh = {\n \"action\": \"storeMediaFile\",\n \"params\": {\n \"filename\": new_filename,\n \"url\": original_url,\n },\n }\n post_actions.append(hsh)\n\n post_actions.append(\n {\n \"action\": \"addNote\",\n \"params\": {\n \"note\": {\n \"deckName\": deck_name,\n \"modelName\": model_name,\n \"fields\": mapping,\n \"tags\": lute_and_term_tags,\n }\n },\n }\n )\n\n return {\"action\": \"multi\", \"params\": {\"actions\": post_actions}}\n\n def get_ankiconnect_post_data_for_term(self, term, base_url, sentence_lookup):\n \"\"\"\n Get post data for a single term.\n This assumes that all the specs are valid!\n Separate method for unit testing.\n \"\"\"\n use_exports = [\n spec\n for spec in self.export_specs\n if spec.active and evaluate_criteria(spec.criteria, term)\n ]\n # print(f\"Using {len(use_exports)} exports\")\n\n ret = {}\n for export in use_exports:\n mapping = json.loads(export.field_mapping)\n replacements, mmap = get_values_and_media_mapping(\n term, sentence_lookup, mapping\n )\n for k, v in mmap.items():\n mmap[k] = base_url + v\n updated_mapping = get_fields_and_final_values(mapping, replacements)\n tags = [\"lute\"] + self._all_tags(term)\n\n p = self._build_ankiconnect_post_json(\n updated_mapping,\n mmap,\n tags,\n export.deck_name,\n export.note_type,\n )\n ret[export.export_name] = p\n\n return ret\n\n def get_ankiconnect_post_data(\n self, term_ids, termid_sentences, base_url, db_session\n ):\n \"\"\"\n Build data to be posted.\n\n Throws if any validation failure or mapping failure, as it's\n annoying to handle partial failures.\n \"\"\"\n\n msgs = self.validate_specs_failure_message()\n if len(msgs) > 0:\n show_msgs = [f\"* {m}\" for m in msgs]\n show_msgs = \"\\n\".join(show_msgs)\n err_msg = \"Anki export configuration errors:\\n\" + show_msgs\n raise AnkiExportConfigurationError(err_msg)\n\n repo = TermRepository(db_session)\n\n refsrepo = ReferencesRepository(db_session)\n sentence_lookup = SentenceLookup(termid_sentences, refsrepo)\n\n ret = {}\n for tid in term_ids:\n term = repo.find(tid)\n pd = self.get_ankiconnect_post_data_for_term(\n term, base_url, sentence_lookup\n )\n if len(pd) > 0:\n ret[tid] = pd\n\n return ret", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 6075}, "tests/unit/parse/test_SpaceDelimitedParser.py::140": {"resolved_imports": ["lute/parse/space_delimited_parser.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_quick_checks", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/cli/test_language_term_export.py::48": {"resolved_imports": ["lute/cli/language_term_export.py", "lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/db/demo.py"], "used_names": ["Term", "TermRepository", "assert_sql_result", "db", "generate_book_file", "generate_language_file", "make_book"], "enclosing_function": "test_single_book_export", "extracted_code": "# Source: lute/cli/language_term_export.py\ndef generate_language_file(language_name, outfile_name):\n \"\"\"\n Generate the datafile for the language.\n \"\"\"\n books = db.session.query(Book).all()\n books = [b for b in books if b.language.name == language_name]\n if len(books) == 0:\n print(f\"No books for given language {language_name}, quitting.\")\n else:\n print(f\"Writing to {outfile_name}\")\n _generate_file(books, outfile_name)\n print(\"Done. \")\n\ndef generate_book_file(bookid, outfile_name):\n \"\"\"\n Generate the datafile for the book.\n \"\"\"\n books = db.session.query(Book).all()\n books = [b for b in books if f\"{b.id}\" == f\"{bookid}\"]\n if len(books) == 0:\n print(f\"No book with id = {bookid}.\")\n else:\n print(f\"Writing to {outfile_name}\")\n _generate_file(books, outfile_name)\n print(\"Done. \")\n\n\n# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 9482}, "tests/unit/models/test_Book_add_remove_pages.py::78": {"resolved_imports": ["lute/db/__init__.py"], "used_names": ["db", "make_book"], "enclosing_function": "test_add_page_after_last", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 47}, "tests/orm/test_Term.py::161": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_replace_remove_image", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/acceptance/conftest.py::364": {"resolved_imports": [], "used_names": ["parsers", "re", "then"], "enclosing_function": "check_exported_file", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/book/test_stats.py::140": {"resolved_imports": ["lute/db/__init__.py", "lute/term/model.py", "lute/book/stats.py"], "used_names": ["assert_record_count_equals"], "enclosing_function": "test_cache_loads_when_prompted", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/book/test_Repository.py::29": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": ["Book", "db", "pytest"], "enclosing_function": "fixture_book", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/book/model.py\nclass Book: # pylint: disable=too-many-instance-attributes\n \"\"\"\n A book domain object, to create/edit lute.models.book.Books.\n\n Book language can be specified either by language_id, or\n language_name. language_name is useful for loading books via\n scripts/api. language_id takes precedence.\n \"\"\"\n\n def __init__(self):\n self.id = None\n self.language_id = None\n self.language_name = None\n self.title = None\n self.text = None\n self.source_uri = None\n self.audio_filename = None\n self.audio_current_pos = None\n self.audio_bookmarks = None\n self.book_tags = []\n\n self.threshold_page_tokens = 250\n self.split_by = \"paragraphs\"\n\n # The source file used for the book text.\n # Overrides the self.text if not None.\n self.text_source_path = None\n\n self.text_stream = None\n self.text_stream_filename = None\n\n # The source file used for audio.\n self.audio_source_path = None\n\n self.audio_stream = None\n self.audio_stream_filename = None\n\n def __repr__(self):\n return f\"\"\n\n def add_tag(self, tag):\n self.book_tags.append(tag)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1324}, "tests/unit/book/test_stats.py::160": {"resolved_imports": ["lute/db/__init__.py", "lute/term/model.py", "lute/book/stats.py"], "used_names": ["assert_record_count_equals"], "enclosing_function": "test_get_stats_calculates_and_caches_stats", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/read/test_service_popup_data.py::83": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Term", "db"], "enclosing_function": "test_term_with_no_parents", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 7471}, "tests/unit/models/test_Book_add_remove_pages.py::66": {"resolved_imports": ["lute/db/__init__.py"], "used_names": ["db", "make_book"], "enclosing_function": "test_add_page_before_first", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 47}, "tests/unit/book/test_Repository.py::186": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": ["assert_sql_result"], "enclosing_function": "test_save_update_existing", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/features/test_rendering.py::40": {"resolved_imports": ["lute/db/__init__.py", "lute/models/language.py", "lute/language/service.py", "lute/term/model.py", "lute/read/render/service.py", "lute/read/service.py"], "used_names": ["Language", "db", "given", "parsers"], "enclosing_function": "given_lang", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 6039}, "tests/unit/db/test_management.py::70": {"resolved_imports": ["lute/db/__init__.py", "lute/models/setting.py", "lute/models/repositories.py", "lute/db/management.py"], "used_names": ["add_default_user_settings", "db", "text"], "enclosing_function": "test_user_settings_loaded_with_defaults", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/db/management.py\ndef add_default_user_settings(session, default_user_backup_path):\n \"\"\"\n Load missing user settings with default values.\n \"\"\"\n repo = UserSettingRepository(session)\n\n def add_initial_vals_if_needed(hsh):\n \"Add settings as required.\"\n for k, v in hsh.items():\n if not repo.key_exists(k):\n s = UserSetting()\n s.key = k\n s.value = v\n session.add(s)\n session.commit()\n\n # These keys are rendered into the global javascript namespace var\n # LUTE_USER_SETTINGS, so if any of these keys change, check the usage\n # of that variable as well.\n keys_and_defaults = {\n \"backup_enabled\": True,\n \"backup_auto\": True,\n \"backup_warn\": True,\n \"backup_dir\": default_user_backup_path,\n \"backup_count\": 5,\n \"lastbackup\": None,\n \"mecab_path\": None,\n \"japanese_reading\": \"hiragana\",\n \"current_theme\": \"-\",\n \"custom_styles\": \"/* Custom css to modify Lute's appearance. */\",\n \"show_highlights\": True,\n \"current_language_id\": 0,\n # Behaviour:\n \"open_popup_in_new_tab\": False,\n \"stop_audio_on_term_form_open\": True,\n \"stats_calc_sample_size\": 5,\n # Term popups:\n \"term_popup_promote_parent_translation\": True,\n \"term_popup_show_components\": True,\n # Anki:\n \"use_ankiconnect\": False,\n \"ankiconnect_url\": \"http://127.0.0.1:8765\",\n }\n add_initial_vals_if_needed(keys_and_defaults)\n\n # Revise the mecab path if necessary.\n # Note this is done _after_ the defaults are loaded,\n # because the user may have already loaded the defaults\n # (e.g. on machine upgrade) and stored them in the db,\n # so we may have to _update_ the existing setting.\n revised_mecab_path = _revised_mecab_path(repo)\n repo.set_value(\"mecab_path\", revised_mecab_path)\n session.commit()\n\n add_initial_vals_if_needed(initial_hotkey_defaults())", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 2069}, "tests/unit/cli/test_import_books.py::46": {"resolved_imports": ["lute/cli/import_books.py", "lute/models/book.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Book", "BookRepository", "and_", "db", "import_books_from_csv"], "enclosing_function": "test_smoke_test", "extracted_code": "# Source: lute/cli/import_books.py\ndef import_books_from_csv(file, language, tags, commit):\n \"\"\"\n Bulk import books from a CSV file.\n\n Args:\n\n file: the path to the CSV file to import (see lute/cli/commands.py\n for the requirements for this file).\n language: the name of the language to use by default, as it appears in\n your languages settings\n tags: a list of tags to apply to all books\n commit: a boolean value indicating whether to commit the changes to the\n database. If false, a list of books to be imported will be\n printed out, but no changes will be made.\n \"\"\"\n repo = Repository(db.session)\n lang_repo = LanguageRepository(db.session)\n\n count = 0\n with open(file, newline=\"\", encoding=\"utf-8\") as f:\n r = csv.DictReader(f)\n for row in r:\n book = Book()\n book.title = row[\"title\"]\n book.language_name = row.get(\"language\") or language\n if not book.language_name:\n print(f\"Skipping book with unspecified language: {book.title}\")\n continue\n lang = lang_repo.find_by_name(book.language_name)\n if not lang:\n print(\n f\"Skipping book with unknown language ({book.language_name}): {book.title}\"\n )\n continue\n if repo.find_by_title(book.title, lang.id) is not None:\n print(f\"Already exists in {book.language_name}: {book.title}\")\n continue\n count += 1\n all_tags = []\n if tags:\n all_tags.extend(tags)\n if \"tags\" in row and row[\"tags\"]:\n for tag in row[\"tags\"].split(\",\"):\n if tag and tag not in all_tags:\n all_tags.append(tag)\n book.book_tags = all_tags\n book.text = row[\"text\"]\n book.source_uri = row.get(\"url\") or None\n if \"audio\" in row and row[\"audio\"]:\n book.audio_filename = os.path.join(os.path.dirname(file), row[\"audio\"])\n book.audio_bookmarks = row.get(\"bookmarks\") or None\n repo.add(book)\n print(\n f\"Added {book.language_name} book (tags={','.join(all_tags)}): {book.title}\"\n )\n\n print()\n print(f\"Added {count} books\")\n print()\n\n if not commit:\n db.session.rollback()\n print(\"Dry run, no changes made.\")\n return\n\n print(\"Committing...\")\n sys.stdout.flush()\n repo.commit()\n\n\n# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\n\n# Source: lute/models/repositories.py\nclass BookRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, book_id):\n \"Get by ID.\"\n return self.session.query(Book).filter(Book.id == book_id).first()\n\n def find_by_title(self, book_title, language_id):\n \"Get by title.\"\n return (\n self.session.query(Book)\n .filter(and_(Book.title == book_title, Book.language_id == language_id))\n .first()\n )\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 6885}, "tests/unit/parse/test_SpaceDelimitedParser.py::149": {"resolved_imports": ["lute/parse/space_delimited_parser.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_quick_checks", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/parse/test_registry.py::46": {"resolved_imports": ["lute/parse/registry.py", "lute/parse/space_delimited_parser.py"], "used_names": ["supported_parser_types"], "enclosing_function": "test_supported_parser_types", "extracted_code": "# Source: lute/parse/registry.py\ndef supported_parser_types():\n \"\"\"\n List of supported Language.parser_types\n \"\"\"\n return list(a[0] for a in supported_parsers())", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 173}, "tests/unit/utils/test_formutils.py::23": {"resolved_imports": ["lute/db/__init__.py", "lute/utils/formutils.py", "lute/models/repositories.py"], "used_names": ["db", "language_choices"], "enclosing_function": "test_language_choices_if_only_single_language_exists", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/utils/formutils.py\ndef language_choices(session, dummy_entry_placeholder=\"-\"):\n \"\"\"\n Return the list of languages for select boxes.\n\n If only one lang exists, only return that,\n otherwise add a '-' dummy entry at the top.\n \"\"\"\n langs = session.query(Language).order_by(Language.name).all()\n supported = [lang for lang in langs if lang.is_supported]\n lang_choices = [(s.id, s.name) for s in supported]\n # Add a dummy placeholder even if there are no languages.\n if len(lang_choices) != 1:\n lang_choices = [(0, dummy_entry_placeholder)] + lang_choices\n return lang_choices", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 675}, "tests/unit/language/test_service.py::18": {"resolved_imports": ["lute/language/service.py", "lute/db/__init__.py", "lute/utils/debug_helpers.py"], "used_names": ["Service", "db"], "enclosing_function": "test_get_all_lang_defs", "extracted_code": "# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2195}, "tests/orm/test_Book.py::34": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_save_book", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 47}, "tests/unit/ankiexport/test_field_mapping.py::89": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "get_values_and_media_mapping"], "enclosing_function": "test_basic_replacements", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\ndef get_values_and_media_mapping(term, sentence_lookup, mapping):\n \"\"\"\n Get the value replacements to be put in the mapping, and build\n dict of new filenames to original filenames.\n \"\"\"\n\n def all_translations():\n ret = [term.translation or \"\"]\n for p in term.parents:\n if p.translation not in ret:\n ret.append(p.translation or \"\")\n return [r for r in ret if r.strip() != \"\"]\n\n def parse_keys_needing_calculation(calculate_keys, media_mappings):\n \"\"\"\n Build a parser for some keys in the mapping string, return\n calculated value to use in the mapping. SIDE EFFECT:\n adds ankiconnect post actions to post_actions if needed\n (e.g. for image uploads).\n\n e.g. the mapping \"article: { tags:[\"der\", \"die\", \"das\"] }\"\n needs to be parsed to extract certain tags from the current\n term.\n \"\"\"\n\n def _filtered_tags_in_term_list(term_list, tagvals):\n \"Get all unique tags.\"\n # tagvals is a pyparsing ParseResults, use list() to convert to strings.\n ttext = [tt.text for t in term_list for tt in t.term_tags]\n ttext = sorted(list(set(ttext)))\n ftags = [tt for tt in ttext if tt in list(tagvals)]\n return \", \".join(ftags)\n\n def get_filtered_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list([term], tagvals)\n\n def get_filtered_parents_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list(term.parents, tagvals)\n\n def handle_image(_):\n id_images = [\n (t, t.get_current_image())\n for t in _all_terms(term)\n if t.get_current_image() is not None\n ]\n image_srcs = []\n for t, imgfilename in id_images:\n new_filename = f\"LUTE_TERM_{t.id}.jpg\"\n image_url = f\"/userimages/{t.language.id}/{imgfilename}\"\n media_mappings[new_filename] = image_url\n image_srcs.append(f'')\n\n return \"\".join(image_srcs)\n\n def handle_sentences(_):\n \"Get sample sentence for term.\"\n if term.id is None:\n # Dummy parse.\n return \"\"\n return sentence_lookup.get_sentence_for_term(term.id)\n\n quotedString.setParseAction(pp.removeQuotes)\n tagvallist = Suppress(\"[\") + pp.delimitedList(quotedString) + Suppress(\"]\")\n tagcrit = tagvallist | QuotedString(quoteChar='\"')\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n\n image = Suppress(\"image\")\n sentence = Suppress(\"sentence\")\n\n matcher = (\n tag_matcher.set_parse_action(get_filtered_tags)\n | parents_tag_matcher.set_parse_action(get_filtered_parents_tags)\n | image.set_parse_action(handle_image)\n | sentence.set_parse_action(handle_sentences)\n )\n\n calc_replacements = {\n # Matchers return the value that should be used as the\n # replacement value for the given mapping string. e.g.\n # tags[\"der\", \"die\"] returns \"der\" if term.tags = [\"der\", \"x\"]\n k: matcher.parseString(k).asList()[0]\n for k in calculate_keys\n }\n\n return calc_replacements\n\n def remove_zws(replacements_dict):\n cleaned = {}\n for key, value in replacements_dict.items():\n if isinstance(value, str):\n cleaned[key] = value.replace(\"\\u200B\", \"\")\n else:\n cleaned[key] = value\n return cleaned\n\n # One-for-one replacements in the mapping string.\n # e.g. \"{ id }\" is replaced by term.termid.\n replacements = {\n \"id\": term.id,\n \"term\": term.text,\n \"language\": term.language.name,\n \"parents\": \", \".join([p.text for p in term.parents]),\n \"tags\": \", \".join(sorted({tt.text for tt in term.term_tags})),\n \"translation\": \"
\".join(all_translations()),\n \"pronunciation\": term.romanization,\n \"parents.pronunciation\": \", \".join(\n [p.romanization or \"\" for p in term.parents]\n ),\n }\n\n mapping_string = \"; \".join(mapping.values())\n calc_keys = [\n k\n for k in set(re.findall(r\"{\\s*(.*?)\\s*}\", mapping_string))\n if k not in replacements\n ]\n\n media_mappings = {}\n calc_replacements = parse_keys_needing_calculation(calc_keys, media_mappings)\n\n final_replacements = {**replacements, **calc_replacements}\n cleaned = remove_zws(final_replacements)\n return (cleaned, media_mappings)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4848}, "tests/unit/ankiexport/test_criteria.py::57": {"resolved_imports": ["lute/ankiexport/criteria.py", "lute/ankiexport/exceptions.py"], "used_names": ["evaluate_criteria"], "enclosing_function": "test_blank_criteria_is_always_true", "extracted_code": "# Source: lute/ankiexport/criteria.py\ndef evaluate_criteria(s, term):\n \"Parse the criteria, return True or False for the given term.\"\n # pylint: disable=too-many-locals\n\n if (s or \"\").strip() == \"\":\n return True\n\n def has_any_matching_tags(tagvals):\n term_tags = [t.text for t in term.term_tags]\n return any(e in term_tags for e in tagvals)\n\n def has_any_matching_parent_tags(tagvals):\n ptags = []\n for p in term.parents:\n ptags.extend([t.text for t in p.term_tags])\n return any(e in ptags for e in tagvals)\n\n def has_any_matching_all_tags(tagvals):\n alltags = [t.text for t in term.term_tags]\n for p in term.parents:\n alltags.extend([t.text for t in p.term_tags])\n return any(e in alltags for e in tagvals)\n\n def matches_lang(lang):\n return term.language.name == lang[0]\n\n def check_has_images():\n \"True if term or any parent has image.\"\n pi = [p.get_current_image() is not None for p in term.parents]\n return term.get_current_image() is not None or any(pi)\n\n def check_has(args):\n \"Check has:x\"\n has_item = args[0]\n if has_item == \"image\":\n return check_has_images()\n raise RuntimeError(f\"Unhandled has check for {has_item}\")\n\n def get_binary_operator(opstring):\n \"Return lambda matching op.\"\n opMap = {\n \"<\": lambda a, b: a < b,\n \"<=\": lambda a, b: a <= b,\n \">\": lambda a, b: a > b,\n \">=\": lambda a, b: a >= b,\n \"!=\": lambda a, b: a != b,\n \"=\": lambda a, b: a == b,\n \"==\": lambda a, b: a == b,\n }\n return opMap[opstring]\n\n def check_parent_count(args):\n \"Check parents.\"\n opstring, val = args\n oplambda = get_binary_operator(opstring)\n pcount = len(term.parents)\n return oplambda(pcount, val)\n\n def check_status_val(args):\n \"Check status.\"\n opstring, val = args\n oplambda = get_binary_operator(opstring)\n return oplambda(term.status, val)\n\n ### class BoolNot:\n ### \"Not unary operator.\"\n ### def __init__(self, t):\n ### self.arg = t[0][1]\n ### def __bool__(self) -> bool:\n ### v = bool(self.arg)\n ### return not v\n ### def __str__(self) -> str:\n ### return \"~\" + str(self.arg)\n ### __repr__ = __str__\n\n class BoolBinOp:\n \"Binary operation.\"\n repr_symbol: str = \"\"\n eval_fn: Callable[[Iterable[bool]], bool] = lambda _: False\n\n def __init__(self, t):\n self.args = t[0][0::2]\n\n def __str__(self) -> str:\n sep = f\" {self.repr_symbol} \"\n return f\"({sep.join(map(str, self.args))})\"\n\n def __bool__(self) -> bool:\n return self.eval_fn(bool(a) for a in self.args)\n\n class BoolAnd(BoolBinOp):\n repr_symbol = \"&\"\n eval_fn = all\n\n class BoolOr(BoolBinOp):\n repr_symbol = \"|\"\n eval_fn = any\n\n quoteval = QuotedString(quoteChar='\"')\n quotedString.setParseAction(pp.removeQuotes)\n list_of_values = pp.delimitedList(quotedString)\n\n tagvallist = Suppress(\"[\") + list_of_values + Suppress(\"]\")\n tagcrit = tagvallist | quoteval\n\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n all_tag_matcher = Suppress(Literal(\"all.tags\") + Literal(\":\")) + tagcrit\n\n lang_matcher = Suppress(\"language\") + Suppress(\":\") + quoteval\n\n has_options = Literal(\"image\")\n has_matcher = Suppress(\"has\") + Suppress(\":\") + has_options\n\n comparison_op = one_of(\"< <= > >= != = == <>\")\n integer = Word(nums).setParseAction(lambda x: int(x[0]))\n\n parent_count_matcher = (\n Suppress(\"parents\")\n + Suppress(\".\")\n + Suppress(\"count\")\n + comparison_op\n + integer\n )\n\n status_matcher = Suppress(\"status\") + comparison_op + integer\n\n and_keyword = Keyword(\"and\")\n or_keyword = Keyword(\"or\")\n\n multi_check = infixNotation(\n tag_matcher.set_parse_action(has_any_matching_tags)\n | parents_tag_matcher.set_parse_action(has_any_matching_parent_tags)\n | all_tag_matcher.set_parse_action(has_any_matching_all_tags)\n | lang_matcher.set_parse_action(matches_lang)\n | has_matcher.set_parse_action(check_has)\n | parent_count_matcher.set_parse_action(check_parent_count)\n | status_matcher.set_parse_action(check_status_val),\n [\n (and_keyword, 2, opAssoc.LEFT, BoolAnd),\n (or_keyword, 2, opAssoc.LEFT, BoolOr),\n ],\n )\n\n try:\n result = multi_check.parseString(s, parseAll=True)\n return bool(result[0])\n except pp.ParseException as ex:\n msg = f\"Criteria syntax error at position {ex.loc} or later: {ex.line}\"\n raise AnkiExportConfigurationError(msg) from ex", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4969}, "tests/unit/term/test_Term_status_follow.py::89": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["assert_sql_result"], "enclosing_function": "assert_statuses", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/term/test_datatables.py::77": {"resolved_imports": ["lute/term/datatables.py", "lute/db/__init__.py"], "used_names": ["add_terms", "db", "get_data_tables_list"], "enclosing_function": "test_parents_included_in_termids_query", "extracted_code": "# Source: lute/term/datatables.py\ndef get_data_tables_list(parameters, session):\n \"Term json data for datatables.\"\n\n base_sql = \"\"\"SELECT\n w.WoID as WoID, LgName, L.LgID as LgID, w.WoText as WoText, parents.parentlist as ParentText, w.WoTranslation,\n w.WoRomanization,\n WiSource,\n ifnull(tags.taglist, '') as TagList,\n StText,\n StID,\n StAbbreviation,\n case w.WoSyncStatus when 1 then 'y' else '' end as SyncStatus,\n datetime(WoCreated, 'localtime') as WoCreated\n FROM\n words w\n INNER JOIN languages L on L.LgID = w.WoLgID\n INNER JOIN statuses S on S.StID = w.WoStatus\n LEFT OUTER JOIN (\n /* Special concat used for easy parsing on client. */\n SELECT WpWoID as WoID, GROUP_CONCAT(PText, ';;') AS parentlist\n FROM\n (\n select WpWoID, WoText as PText\n from wordparents wp\n INNER JOIN words on WoID = WpParentWoID\n order by WoText\n ) parentssrc\n GROUP BY WpWoID\n ) AS parents on parents.WoID = w.WoID\n LEFT OUTER JOIN (\n /* Special concat used for easy parsing on client. */\n SELECT WtWoID as WoID, GROUP_CONCAT(TgText, ';;') AS taglist\n FROM\n (\n select WtWoID, TgText\n from wordtags wt\n INNER JOIN tags t on t.TgID = wt.WtTgID\n order by TgText\n ) tagssrc\n GROUP BY WtWoID\n ) AS tags on tags.WoID = w.WoID\n LEFT OUTER JOIN wordimages wi on wi.WiWoID = w.WoID\n \"\"\"\n\n typecrit = supported_parser_type_criteria()\n wheres = [f\"L.LgParserType in ({typecrit})\"]\n\n # Add \"where\" criteria for all the filters.\n\n # Have to check for 'null' for language filter.\n # A new user may filter the language when the demo data is loaded,\n # but on \"wipe database\" the filtLanguage value stored in localdata\n # may be invalid, resulting in the filtLanguage form control actually\n # sending the **string value** \"null\" here.\n # The other filter values don't change with the data,\n # so we don't need to check for null.\n # Tricky tricky.\n language_id = parameters[\"filtLanguage\"]\n if language_id == \"null\" or language_id is None:\n language_id = \"0\"\n language_id = int(language_id)\n if language_id != 0:\n wheres.append(f\"L.LgID == {language_id}\")\n\n if parameters[\"filtParentsOnly\"] == \"true\":\n wheres.append(\"parents.parentlist IS NULL\")\n\n sql_age_calc = \"cast(julianday('now') - julianday(w.wocreated) as int)\"\n age_min = parameters[\"filtAgeMin\"].strip()\n if age_min:\n wheres.append(f\"{sql_age_calc} >= {int(age_min)}\")\n age_max = parameters[\"filtAgeMax\"].strip()\n if age_max:\n wheres.append(f\"{sql_age_calc} <= {int(age_max)}\")\n\n st_range = [\"StID != 98\"]\n status_min = int(parameters.get(\"filtStatusMin\", \"0\"))\n status_max = int(parameters.get(\"filtStatusMax\", \"99\"))\n st_range.append(f\"StID >= {status_min}\")\n st_range.append(f\"StID <= {status_max}\")\n st_where = \" AND \".join(st_range)\n if parameters[\"filtIncludeIgnored\"] == \"true\":\n st_where = f\"({st_where} OR StID = 98)\"\n wheres.append(st_where)\n\n termids = parameters[\"filtTermIDs\"].strip()\n if termids != \"\":\n parentsql = f\"select WpParentWoID from wordparents where WpWoID in ({termids})\"\n wheres.append(f\"((w.WoID in ({termids})) OR (w.WoID in ({parentsql})))\")\n\n # Phew.\n return DataTablesSqliteQuery.get_data(\n base_sql + \" WHERE \" + \" AND \".join(wheres), parameters, session.connection()\n )\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3522}, "tests/unit/backup/test_backup.py::147": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["Service", "UserSettingRepository", "db"], "enclosing_function": "test_last_import_setting_is_updated_on_successful_backup", "extracted_code": "# Source: lute/backup/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def create_backup(self, app_config, settings, is_manual=False, suffix=None):\n \"\"\"\n Create backup using current app config, settings.\n\n is_manual is True if this is a user-triggered manual\n backup, otherwise is False.\n\n suffix can be specified for test.\n\n settings are from BackupSettings.\n - backup_enabled\n - backup_dir\n - backup_auto\n - backup_warn\n - backup_count\n - last_backup_datetime\n \"\"\"\n if not os.path.exists(settings.backup_dir):\n raise BackupException(\"Missing directory \" + settings.backup_dir)\n\n # def _print_now(msg):\n # \"Timing helper for when implement audio backup.\"\n # now = datetime.now().strftime(\"%H-%M-%S\")\n # print(f\"{now} - {msg}\", flush=True)\n\n self._mirror_images_dir(app_config.userimagespath, settings.backup_dir)\n\n prefix = \"manual_\" if is_manual else \"\"\n if suffix is None:\n suffix = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n fname = f\"{prefix}lute_backup_{suffix}.db\"\n backupfile = os.path.join(settings.backup_dir, fname)\n\n f = self._create_db_backup(app_config.dbfilename, backupfile)\n self._remove_excess_backups(settings.backup_count, settings.backup_dir)\n return f\n\n def should_run_auto_backup(self, backup_settings):\n \"\"\"\n True (if applicable) if last backup was old.\n \"\"\"\n bs = backup_settings\n if bs.backup_enabled is False or bs.backup_auto is False:\n return False\n\n last = bs.last_backup_datetime\n if last is None:\n return True\n\n curr = int(time.time())\n diff = curr - last\n return diff > 24 * 60 * 60\n\n def backup_warning(self, backup_settings):\n \"Get warning if needed.\"\n if not backup_settings.backup_warn:\n return \"\"\n\n have_books = self.session.query(self.session.query(Book).exists()).scalar()\n have_terms = self.session.query(self.session.query(Term).exists()).scalar()\n if have_books is False and have_terms is False:\n return \"\"\n\n last = backup_settings.last_backup_datetime\n if last is None:\n return \"Never backed up.\"\n\n curr = int(time.time())\n diff = curr - last\n old_backup_msg = \"Last backup was more than 1 week ago.\"\n if diff > 7 * 24 * 60 * 60:\n return old_backup_msg\n\n return \"\"\n\n def _create_db_backup(self, dbfilename, backupfile):\n \"Make a backup.\"\n shutil.copy(dbfilename, backupfile)\n f = f\"{backupfile}.gz\"\n with open(backupfile, \"rb\") as in_file, gzip.open(\n f, \"wb\", compresslevel=4\n ) as out_file:\n shutil.copyfileobj(in_file, out_file)\n os.remove(backupfile)\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n return f\n\n def skip_this_backup(self):\n \"Set the last backup time to today.\"\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n\n def _remove_excess_backups(self, count, outdir):\n \"Remove old backups.\"\n files = [f for f in self.list_backups(outdir) if not f.is_manual]\n files.sort(reverse=True)\n to_remove = files[count:]\n for f in to_remove:\n os.remove(f.filepath)\n\n def _mirror_images_dir(self, userimagespath, outdir):\n \"Copy the images to backup.\"\n target_dir = os.path.join(outdir, \"userimages_backup\")\n target_dir = os.path.abspath(target_dir)\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n shutil.copytree(userimagespath, target_dir, dirs_exist_ok=True)\n\n def list_backups(self, outdir) -> List[DatabaseBackupFile]:\n \"List all backup files.\"\n return [\n DatabaseBackupFile(os.path.join(outdir, f))\n for f in os.listdir(outdir)\n if re.match(r\"(manual_)?lute_backup_\", f)\n ]\n\n\n# Source: lute/models/repositories.py\nclass UserSettingRepository(SettingRepositoryBase):\n \"Repository.\"\n\n def __init__(self, session):\n super().__init__(session, UserSetting)\n\n def key_exists_precheck(self, keyname):\n \"\"\"\n User keys must exist.\n \"\"\"\n if not self.key_exists(keyname):\n raise MissingUserSettingKeyException(keyname)\n\n def get_backup_settings(self):\n \"Convenience method.\"\n bs = BackupSettings()\n\n def _bool(v):\n return v in (1, \"1\", \"y\", True)\n\n bs.backup_enabled = _bool(self.get_value(\"backup_enabled\"))\n bs.backup_auto = _bool(self.get_value(\"backup_auto\"))\n bs.backup_warn = _bool(self.get_value(\"backup_warn\"))\n bs.backup_dir = self.get_value(\"backup_dir\")\n bs.backup_count = int(self.get_value(\"backup_count\") or 5)\n bs.last_backup_datetime = self.get_last_backup_datetime()\n return bs\n\n def get_last_backup_datetime(self):\n \"Get the last_backup_datetime as int, or None.\"\n v = self.get_value(\"lastbackup\")\n if v is None:\n return None\n return int(v)\n\n def set_last_backup_datetime(self, v):\n \"Set and save the last backup time.\"\n self.set_value(\"lastbackup\", v)\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 7709}, "tests/unit/language/test_service.py::41": {"resolved_imports": ["lute/language/service.py", "lute/db/__init__.py", "lute/utils/debug_helpers.py"], "used_names": ["Service", "db"], "enclosing_function": "test_get_language_def", "extracted_code": "# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2195}, "tests/dbasserts.py::40": {"resolved_imports": ["lute/config/app_config.py"], "used_names": ["create_engine", "text"], "enclosing_function": "assert_sql_result", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/unit/book/test_Repository.py::53": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": ["assert_sql_result"], "enclosing_function": "test_save_new_book", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_field_mapping.py::188": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["get_fields_and_final_values"], "enclosing_function": "test_empty_fields_not_posted", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\ndef get_fields_and_final_values(mapping, replacements):\n \"Break mapping string into fields, apply replacements.\"\n ret = {}\n for fieldname, value in mapping.items():\n subbed_value = value\n for k, v in replacements.items():\n pattern = rf\"{{\\s*{re.escape(k)}\\s*}}\"\n subbed_value = re.sub(pattern, f\"{v}\", subbed_value)\n if subbed_value.strip() != \"\":\n ret[fieldname.strip()] = subbed_value.strip()\n return ret", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 515}, "tests/orm/test_Text.py::51": {"resolved_imports": ["lute/models/book.py", "lute/db/__init__.py"], "used_names": ["Book", "Text", "TextBookmark", "WordsRead", "assert_record_count_equals", "datetime", "db"], "enclosing_function": "test_delete_text_cascade_deletes_bookmarks_leaves_wordsread", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass Text(db.Model):\n \"\"\"\n Each page in a Book.\n \"\"\"\n\n __tablename__ = \"texts\"\n\n id = db.Column(\"TxID\", db.Integer, primary_key=True)\n _text = db.Column(\"TxText\", db.String, nullable=False)\n order = db.Column(\"TxOrder\", db.Integer)\n start_date = db.Column(\"TxStartDate\", db.DateTime, nullable=True)\n _read_date = db.Column(\"TxReadDate\", db.DateTime, nullable=True)\n bk_id = db.Column(\"TxBkID\", db.Integer, db.ForeignKey(\"books.BkID\"), nullable=False)\n word_count = db.Column(\"TxWordCount\", db.Integer, nullable=True)\n\n book = db.relationship(\"Book\", back_populates=\"texts\")\n bookmarks = db.relationship(\n \"TextBookmark\",\n back_populates=\"text\",\n cascade=\"all, delete-orphan\",\n )\n sentences = db.relationship(\n \"Sentence\",\n back_populates=\"text\",\n order_by=\"Sentence.order\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, book, text, order=1):\n self.book = book\n self.text = text\n self.order = order\n self.sentences = []\n\n @property\n def title(self):\n \"\"\"\n Text title is the book title + page fraction.\n \"\"\"\n b = self.book\n s = f\"({self.order}/{self.book.page_count})\"\n t = f\"{b.title} {s}\"\n return t\n\n @property\n def text(self):\n return self._text\n\n @text.setter\n def text(self, s):\n self._text = s\n if s.strip() == \"\":\n return\n toks = self._get_parsed_tokens()\n wordtoks = [t for t in toks if t.is_word]\n self.word_count = len(wordtoks)\n if self._read_date is not None:\n self._load_sentences_from_tokens(toks)\n\n @property\n def read_date(self):\n return self._read_date\n\n @read_date.setter\n def read_date(self, s):\n self._read_date = s\n # Ensure loaded.\n self.load_sentences()\n\n def _get_parsed_tokens(self):\n \"Return the tokens.\"\n lang = self.book.language\n return lang.parser.get_parsed_tokens(self.text, lang)\n\n def _load_sentences_from_tokens(self, parsedtokens):\n \"Save sentences using the tokens.\"\n parser = self.book.language.parser\n self._remove_sentences()\n curr_sentence_tokens = []\n sentence_num = 1\n\n def _add_current():\n \"Create and add sentence from current state.\"\n if curr_sentence_tokens:\n se = Sentence.from_tokens(curr_sentence_tokens, parser, sentence_num)\n self._add_sentence(se)\n # Reset for the next sentence.\n curr_sentence_tokens.clear()\n\n for pt in parsedtokens:\n curr_sentence_tokens.append(pt)\n if pt.is_end_of_sentence:\n _add_current()\n sentence_num += 1\n\n # Add any stragglers.\n _add_current()\n\n def load_sentences(self):\n \"\"\"\n Parse the current text and create Sentence objects.\n \"\"\"\n toks = self._get_parsed_tokens()\n self._load_sentences_from_tokens(toks)\n\n def _add_sentence(self, sentence):\n \"Add a sentence to the Text.\"\n if sentence not in self.sentences:\n self.sentences.append(sentence)\n sentence.text = self\n\n def _remove_sentences(self):\n \"Remove all sentence from the Text.\"\n for sentence in self.sentences:\n sentence.text = None\n self.sentences = []\n\nclass WordsRead(db.Model):\n \"\"\"\n Tracks reading events for Text entities.\n \"\"\"\n\n __tablename__ = \"wordsread\"\n id = db.Column(\"WrID\", db.Integer, primary_key=True)\n language_id = db.Column(\n \"WrLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n tx_id = db.Column(\n \"WrTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"SET NULL\"),\n nullable=True,\n )\n read_date = db.Column(\"WrReadDate\", db.DateTime, nullable=False)\n word_count = db.Column(\"WrWordCount\", db.Integer, nullable=False)\n\n def __init__(self, text, read_date, word_count):\n self.tx_id = text.id\n self.language_id = text.book.language.id\n self.read_date = read_date\n self.word_count = word_count\n\nclass TextBookmark(db.Model):\n \"\"\"\n Bookmarks for a given Book page\n\n The TextBookmark includes a title\n \"\"\"\n\n __tablename__ = \"textbookmarks\"\n\n id = db.Column(\"TbID\", db.Integer, primary_key=True)\n tx_id = db.Column(\n \"TbTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"CASCADE\"),\n nullable=False,\n )\n title = db.Column(\"TbTitle\", db.Text, nullable=False)\n\n text = db.relationship(\"Text\", back_populates=\"bookmarks\")\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8481}, "tests/unit/db/setup/test_Setup.py::181": {"resolved_imports": ["lute/db/setup/main.py", "lute/db/setup/migrator.py"], "used_names": ["BackupManager", "Setup", "closing", "os", "sqlite3"], "enclosing_function": "test_happy_path_no_existing_database", "extracted_code": "# Source: lute/db/setup/main.py\nclass BackupManager: # pylint: disable=too-few-public-methods\n \"\"\"\n Creates db backups when needed, prunes old backups.\n \"\"\"\n\n def __init__(self, file_to_backup, backup_directory, max_number_of_backups):\n self.file_to_backup = file_to_backup\n self.backup_directory = backup_directory\n self.max_number_of_backups = max_number_of_backups\n\n def do_backup(self, next_backup_datetime=None):\n \"\"\"\n Perform the db file backup to backup_dir,\n pruning old backups.\n \"\"\"\n\n if next_backup_datetime is None:\n now = datetime.now()\n next_backup_datetime = now.strftime(\"%Y%m%d-%H%M%S-%f\")\n\n bname = os.path.basename(self.file_to_backup)\n backup_filename = f\"{bname}.{next_backup_datetime}.gz\"\n backup_path = os.path.join(self.backup_directory, backup_filename)\n\n os.makedirs(self.backup_directory, exist_ok=True)\n\n # Copy the file to the backup directory and gzip it\n with open(self.file_to_backup, \"rb\") as source_file, gzip.open(\n backup_path, \"wb\"\n ) as backup_file:\n shutil.copyfileobj(source_file, backup_file)\n assert os.path.exists(backup_path)\n\n # List all backup files in the directory, sorted by name.\n # Since this includes the timestamp, the oldest files will be\n # listed first.\n globname = f\"{bname}.*.gz\"\n globpath = os.path.join(self.backup_directory, globname)\n backup_files = glob.glob(globpath)\n backup_files.sort(key=os.path.basename)\n\n # Delete excess backup files if necessary\n while len(backup_files) > self.max_number_of_backups:\n file_to_delete = backup_files.pop(0)\n os.remove(file_to_delete)\n\nclass Setup: # pylint: disable=too-few-public-methods\n \"\"\"\n Main setup class, coordinates other classes.\n \"\"\"\n\n def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments\n self,\n db_filename: str,\n baseline_schema_file: str,\n backup_manager: BackupManager,\n migrator: SqliteMigrator,\n output_func=None,\n ):\n self._db_filename = db_filename\n self._baseline_schema_file = baseline_schema_file\n self._backup_mgr = backup_manager\n self._migrator = migrator\n self._output_func = output_func\n\n def setup(self):\n \"\"\"\n Do database setup, making backup if necessary, running migrations.\n \"\"\"\n new_db = False\n has_migrations = False\n\n if not os.path.exists(self._db_filename):\n new_db = True\n # Note openin a connection creates a db file,\n # so this has to be done after the existence\n # check.\n with closing(self._open_connection()) as conn:\n self._create_baseline(conn)\n\n with closing(self._open_connection()) as conn:\n has_migrations = self._migrator.has_migrations(conn)\n\n # Don't do a backup with an open connection ...\n # I don't _think_ it matters, but better to be safe.\n def null_print(s): # pylint: disable=unused-argument\n pass\n\n outfunc = self._output_func or null_print\n if not new_db and has_migrations:\n outfunc(\"Creating backup before running migrations ...\")\n self._backup_mgr.do_backup()\n outfunc(\"Done backup.\")\n\n with closing(self._open_connection()) as conn:\n self._migrator.do_migration(conn)\n\n def _open_connection(self):\n \"\"\"\n Get connection to db_filename. Callers must close.\n \"\"\"\n return sqlite3.connect(self._db_filename, detect_types=sqlite3.PARSE_DECLTYPES)\n\n def _create_baseline(self, conn):\n \"\"\"\n Create baseline database.\n \"\"\"\n b = self._baseline_schema_file\n with open(b, \"r\", encoding=\"utf8\") as f:\n sql = f.read()\n conn.executescript(sql)", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 3995}, "tests/unit/models/test_Term.py::60": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Term", "text"], "enclosing_function": "test_term_left_as_is_if_its_an_exception", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 7421}, "tests/unit/db/test_management.py::78": {"resolved_imports": ["lute/db/__init__.py", "lute/models/setting.py", "lute/models/repositories.py", "lute/db/management.py"], "used_names": ["add_default_user_settings", "db", "text"], "enclosing_function": "test_user_settings_loaded_with_defaults", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/db/management.py\ndef add_default_user_settings(session, default_user_backup_path):\n \"\"\"\n Load missing user settings with default values.\n \"\"\"\n repo = UserSettingRepository(session)\n\n def add_initial_vals_if_needed(hsh):\n \"Add settings as required.\"\n for k, v in hsh.items():\n if not repo.key_exists(k):\n s = UserSetting()\n s.key = k\n s.value = v\n session.add(s)\n session.commit()\n\n # These keys are rendered into the global javascript namespace var\n # LUTE_USER_SETTINGS, so if any of these keys change, check the usage\n # of that variable as well.\n keys_and_defaults = {\n \"backup_enabled\": True,\n \"backup_auto\": True,\n \"backup_warn\": True,\n \"backup_dir\": default_user_backup_path,\n \"backup_count\": 5,\n \"lastbackup\": None,\n \"mecab_path\": None,\n \"japanese_reading\": \"hiragana\",\n \"current_theme\": \"-\",\n \"custom_styles\": \"/* Custom css to modify Lute's appearance. */\",\n \"show_highlights\": True,\n \"current_language_id\": 0,\n # Behaviour:\n \"open_popup_in_new_tab\": False,\n \"stop_audio_on_term_form_open\": True,\n \"stats_calc_sample_size\": 5,\n # Term popups:\n \"term_popup_promote_parent_translation\": True,\n \"term_popup_show_components\": True,\n # Anki:\n \"use_ankiconnect\": False,\n \"ankiconnect_url\": \"http://127.0.0.1:8765\",\n }\n add_initial_vals_if_needed(keys_and_defaults)\n\n # Revise the mecab path if necessary.\n # Note this is done _after_ the defaults are loaded,\n # because the user may have already loaded the defaults\n # (e.g. on machine upgrade) and stored them in the db,\n # so we may have to _update_ the existing setting.\n revised_mecab_path = _revised_mecab_path(repo)\n repo.set_value(\"mecab_path\", revised_mecab_path)\n session.commit()\n\n add_initial_vals_if_needed(initial_hotkey_defaults())", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 2069}, "tests/unit/term/test_Term_status_follow.py::386": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["db"], "enclosing_function": "test_remove_parent_doesnt_affect_other_linked_terms", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/orm/test_Book.py::46": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_save_book", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 47}, "tests/unit/db/setup/test_Setup.py::202": {"resolved_imports": ["lute/db/setup/main.py", "lute/db/setup/migrator.py"], "used_names": ["BackupManager", "Setup", "closing", "gzip", "os", "sqlite3"], "enclosing_function": "test_existing_database_with_migrations", "extracted_code": "# Source: lute/db/setup/main.py\nclass BackupManager: # pylint: disable=too-few-public-methods\n \"\"\"\n Creates db backups when needed, prunes old backups.\n \"\"\"\n\n def __init__(self, file_to_backup, backup_directory, max_number_of_backups):\n self.file_to_backup = file_to_backup\n self.backup_directory = backup_directory\n self.max_number_of_backups = max_number_of_backups\n\n def do_backup(self, next_backup_datetime=None):\n \"\"\"\n Perform the db file backup to backup_dir,\n pruning old backups.\n \"\"\"\n\n if next_backup_datetime is None:\n now = datetime.now()\n next_backup_datetime = now.strftime(\"%Y%m%d-%H%M%S-%f\")\n\n bname = os.path.basename(self.file_to_backup)\n backup_filename = f\"{bname}.{next_backup_datetime}.gz\"\n backup_path = os.path.join(self.backup_directory, backup_filename)\n\n os.makedirs(self.backup_directory, exist_ok=True)\n\n # Copy the file to the backup directory and gzip it\n with open(self.file_to_backup, \"rb\") as source_file, gzip.open(\n backup_path, \"wb\"\n ) as backup_file:\n shutil.copyfileobj(source_file, backup_file)\n assert os.path.exists(backup_path)\n\n # List all backup files in the directory, sorted by name.\n # Since this includes the timestamp, the oldest files will be\n # listed first.\n globname = f\"{bname}.*.gz\"\n globpath = os.path.join(self.backup_directory, globname)\n backup_files = glob.glob(globpath)\n backup_files.sort(key=os.path.basename)\n\n # Delete excess backup files if necessary\n while len(backup_files) > self.max_number_of_backups:\n file_to_delete = backup_files.pop(0)\n os.remove(file_to_delete)\n\nclass Setup: # pylint: disable=too-few-public-methods\n \"\"\"\n Main setup class, coordinates other classes.\n \"\"\"\n\n def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments\n self,\n db_filename: str,\n baseline_schema_file: str,\n backup_manager: BackupManager,\n migrator: SqliteMigrator,\n output_func=None,\n ):\n self._db_filename = db_filename\n self._baseline_schema_file = baseline_schema_file\n self._backup_mgr = backup_manager\n self._migrator = migrator\n self._output_func = output_func\n\n def setup(self):\n \"\"\"\n Do database setup, making backup if necessary, running migrations.\n \"\"\"\n new_db = False\n has_migrations = False\n\n if not os.path.exists(self._db_filename):\n new_db = True\n # Note openin a connection creates a db file,\n # so this has to be done after the existence\n # check.\n with closing(self._open_connection()) as conn:\n self._create_baseline(conn)\n\n with closing(self._open_connection()) as conn:\n has_migrations = self._migrator.has_migrations(conn)\n\n # Don't do a backup with an open connection ...\n # I don't _think_ it matters, but better to be safe.\n def null_print(s): # pylint: disable=unused-argument\n pass\n\n outfunc = self._output_func or null_print\n if not new_db and has_migrations:\n outfunc(\"Creating backup before running migrations ...\")\n self._backup_mgr.do_backup()\n outfunc(\"Done backup.\")\n\n with closing(self._open_connection()) as conn:\n self._migrator.do_migration(conn)\n\n def _open_connection(self):\n \"\"\"\n Get connection to db_filename. Callers must close.\n \"\"\"\n return sqlite3.connect(self._db_filename, detect_types=sqlite3.PARSE_DECLTYPES)\n\n def _create_baseline(self, conn):\n \"\"\"\n Create baseline database.\n \"\"\"\n b = self._baseline_schema_file\n with open(b, \"r\", encoding=\"utf8\") as f:\n sql = f.read()\n conn.executescript(sql)", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 3995}, "tests/unit/db/test_management.py::85": {"resolved_imports": ["lute/db/__init__.py", "lute/models/setting.py", "lute/models/repositories.py", "lute/db/management.py"], "used_names": ["add_default_user_settings", "db"], "enclosing_function": "test_user_settings_load_leaves_existing_values", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/db/management.py\ndef add_default_user_settings(session, default_user_backup_path):\n \"\"\"\n Load missing user settings with default values.\n \"\"\"\n repo = UserSettingRepository(session)\n\n def add_initial_vals_if_needed(hsh):\n \"Add settings as required.\"\n for k, v in hsh.items():\n if not repo.key_exists(k):\n s = UserSetting()\n s.key = k\n s.value = v\n session.add(s)\n session.commit()\n\n # These keys are rendered into the global javascript namespace var\n # LUTE_USER_SETTINGS, so if any of these keys change, check the usage\n # of that variable as well.\n keys_and_defaults = {\n \"backup_enabled\": True,\n \"backup_auto\": True,\n \"backup_warn\": True,\n \"backup_dir\": default_user_backup_path,\n \"backup_count\": 5,\n \"lastbackup\": None,\n \"mecab_path\": None,\n \"japanese_reading\": \"hiragana\",\n \"current_theme\": \"-\",\n \"custom_styles\": \"/* Custom css to modify Lute's appearance. */\",\n \"show_highlights\": True,\n \"current_language_id\": 0,\n # Behaviour:\n \"open_popup_in_new_tab\": False,\n \"stop_audio_on_term_form_open\": True,\n \"stats_calc_sample_size\": 5,\n # Term popups:\n \"term_popup_promote_parent_translation\": True,\n \"term_popup_show_components\": True,\n # Anki:\n \"use_ankiconnect\": False,\n \"ankiconnect_url\": \"http://127.0.0.1:8765\",\n }\n add_initial_vals_if_needed(keys_and_defaults)\n\n # Revise the mecab path if necessary.\n # Note this is done _after_ the defaults are loaded,\n # because the user may have already loaded the defaults\n # (e.g. on machine upgrade) and stored them in the db,\n # so we may have to _update_ the existing setting.\n revised_mecab_path = _revised_mecab_path(repo)\n repo.set_value(\"mecab_path\", revised_mecab_path)\n session.commit()\n\n add_initial_vals_if_needed(initial_hotkey_defaults())", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 2069}, "plugins/lute-mandarin/tests/test_MandarinParser.py::122": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["MandarinParser", "os"], "enclosing_function": "test_term_found_in_exceptions_file_is_split", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/backup/test_backup.py::256": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["DatabaseBackupFile", "patch"], "enclosing_function": "test_database_backup_file_size_formatting", "extracted_code": "# Source: lute/backup/service.py\nclass DatabaseBackupFile:\n \"\"\"\n A representation of a lute backup file to hold metadata attributes.\n \"\"\"\n\n def __init__(self, filepath: Union[str, os.PathLike]):\n if not os.path.exists(filepath):\n raise BackupException(f\"No backup file at {filepath}.\")\n\n name = os.path.basename(filepath)\n if not re.match(r\"(manual_)?lute_backup_\", name):\n raise BackupException(f\"Not a valid lute database backup at {filepath}.\")\n\n self.filepath = filepath\n self.name = name\n self.is_manual = self.name.startswith(\"manual_\")\n\n def __lt__(self, other):\n return self.last_modified < other.last_modified\n\n @property\n def last_modified(self) -> datetime:\n return datetime.fromtimestamp(os.path.getmtime(self.filepath)).astimezone()\n\n @property\n def size_bytes(self) -> int:\n return os.path.getsize(self.filepath)\n\n @property\n def size(self) -> str:\n \"\"\"\n A human-readable string representation of the size of the file.\n\n Eg.\n 1746 bytes\n 4 kB\n 27 MB\n \"\"\"\n s = self.size_bytes\n if s >= 1e9:\n return f\"{round(s * 1e-9)} GB\"\n if s >= 1e6:\n return f\"{round(s * 1e-6)} MB\"\n if s >= 1e3:\n return f\"{round(s * 1e-3)} KB\"\n return f\"{s} bytes\"", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 1383}, "tests/acceptance/lute_test_client.py::387": {"resolved_imports": [], "used_names": [], "enclosing_function": "_get_element_for_word", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/db/setup/test_SqliteMigrator.py::108": {"resolved_imports": ["lute/db/setup/migrator.py"], "used_names": ["SqliteMigrator"], "enclosing_function": "test_repeatable_migs_are_always_applied", "extracted_code": "# Source: lute/db/setup/migrator.py\nclass SqliteMigrator:\n \"\"\"\n Sqlite migrator class.\n\n Follows the principles documented in\n https://github.com/jzohrab/DbMigrator/blob/master/docs/managing_database_changes.md\n \"\"\"\n\n def __init__(self, location, repeatable):\n self.location = location\n self.repeatable = repeatable\n\n def has_migrations(self, conn):\n \"\"\"\n Return True if have non-applied migrations.\n \"\"\"\n outstanding = self._get_pending(conn)\n return len(outstanding) > 0\n\n def _get_pending(self, conn):\n \"\"\"\n Get all non-applied (one-time) migrations.\n \"\"\"\n allfiles = []\n with _change_directory(self.location):\n allfiles = [\n os.path.join(self.location, s)\n for s in os.listdir()\n if s.endswith(\".sql\")\n ]\n allfiles.sort()\n outstanding = [f for f in allfiles if self._should_apply(conn, f)]\n return outstanding\n\n def do_migration(self, conn):\n \"\"\"\n Run all migrations, then all repeatable migrations.\n \"\"\"\n self._process_folder(conn)\n self._process_repeatable(conn)\n\n def _process_folder(self, conn):\n \"\"\"\n Run all pending migrations. Write executed script to\n _migrations table.\n \"\"\"\n outstanding = self._get_pending(conn)\n for f in outstanding:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n self._add_migration_to_database(conn, f)\n\n def _process_repeatable(self, conn):\n \"\"\"\n Run all repeatable migrations.\n \"\"\"\n with _change_directory(self.repeatable):\n files = [\n os.path.join(self.repeatable, f)\n for f in os.listdir()\n if f.endswith(\".sql\")\n ]\n for f in files:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n\n def _should_apply(self, conn, filename):\n \"\"\"\n True if a migration hasn't been run yet.\n\n The file basename (no directory) is stored in the migration table.\n \"\"\"\n f = os.path.basename(filename)\n sql = f\"select count(filename) from _migrations where filename = '{f}'\"\n res = conn.execute(sql).fetchone()\n return res[0] == 0\n\n def _add_migration_to_database(self, conn, filename):\n \"\"\"\n Track the executed migration in _migrations.\n \"\"\"\n f = os.path.basename(filename)\n conn.execute(\"begin transaction\")\n conn.execute(f\"INSERT INTO _migrations values ('{f}')\")\n conn.execute(\"commit transaction\")\n\n def _process_file(self, conn, f):\n \"\"\"\n Run the given file.\n \"\"\"\n with open(f, \"r\", encoding=\"utf8\") as sql_file:\n commands = sql_file.read()\n self._exec_commands(conn, commands)\n\n def _exec_commands(self, conn, sql):\n \"\"\"\n Execute all commands in the given file.\n \"\"\"\n conn.executescript(sql)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3329}, "tests/acceptance/lute_test_client.py::370": {"resolved_imports": [], "used_names": [], "enclosing_function": "_to_string", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/book/test_datatables.py::57": {"resolved_imports": ["lute/models/language.py", "lute/book/datatables.py", "lute/db/__init__.py", "lute/db/demo.py"], "used_names": ["Language", "db", "get_data_tables_list"], "enclosing_function": "test_book_query_only_returns_supported_language_books", "extracted_code": "# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/book/datatables.py\ndef get_data_tables_list(parameters, is_archived, session):\n \"Book json data for datatables.\"\n archived = \"true\" if is_archived else \"false\"\n\n base_sql = f\"\"\"\n SELECT\n b.BkID As BkID,\n LgName,\n BkTitle,\n case when currtext.TxID is null then 1 else currtext.TxOrder end as PageNum,\n textcounts.pagecount AS PageCount,\n booklastopened.lastopeneddate AS LastOpenedDate,\n BkArchived,\n tags.taglist AS TagList,\n textcounts.wc AS WordCount,\n c.distinctterms as DistinctCount,\n c.distinctunknowns as UnknownCount,\n c.unknownpercent as UnknownPercent,\n c.status_distribution as StatusDistribution,\n case when completed_books.BkID is null then 0 else 1 end as IsCompleted\n\n FROM books b\n INNER JOIN languages ON LgID = b.BkLgID\n LEFT OUTER JOIN texts currtext ON currtext.TxID = BkCurrentTxID\n INNER JOIN (\n select TxBkID, max(TxStartDate) as lastopeneddate from texts group by TxBkID\n ) booklastopened on booklastopened.TxBkID = b.BkID\n INNER JOIN (\n SELECT TxBkID, SUM(TxWordCount) as wc, COUNT(TxID) AS pagecount\n FROM texts\n GROUP BY TxBkID\n ) textcounts on textcounts.TxBkID = b.BkID\n LEFT OUTER JOIN bookstats c on c.BkID = b.BkID\n\n LEFT OUTER JOIN (\n SELECT BtBkID as BkID, GROUP_CONCAT(T2Text, ', ') AS taglist\n FROM\n (\n SELECT BtBkID, T2Text\n FROM booktags bt\n INNER JOIN tags2 t2 ON t2.T2ID = bt.BtT2ID\n ORDER BY T2Text\n ) tagssrc\n GROUP BY BtBkID\n ) AS tags ON tags.BkID = b.BkID\n\n left outer join (\n select texts.TxBkID as BkID\n from texts\n inner join (\n /* last page in each book */\n select TxBkID, max(TxOrder) as maxTxOrder from texts group by TxBkID\n ) last_page on last_page.TxBkID = texts.TxBkID and last_page.maxTxOrder = texts.TxOrder\n where TxReadDate is not null\n ) completed_books on completed_books.BkID = b.BkID\n\n WHERE b.BkArchived = {archived}\n and languages.LgParserType in ({ supported_parser_type_criteria() })\n \"\"\"\n\n # Add \"where\" criteria for all the filters.\n language_id = parameters[\"filtLanguage\"]\n if language_id == \"null\" or language_id == \"undefined\" or language_id is None:\n language_id = \"0\"\n language_id = int(language_id)\n if language_id != 0:\n base_sql += f\" and LgID = {language_id}\"\n\n connection = session.connection()\n return DataTablesSqliteQuery.get_data(base_sql, parameters, connection)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 8642}, "tests/unit/book/test_Repository.py::48": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": ["assert_sql_result"], "enclosing_function": "test_save_new_book", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/models/test_Setting.py::135": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["patch"], "enclosing_function": "test_time_since_last_backup_in_past", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_service.py::195": {"resolved_imports": ["lute/models/srsexport.py", "lute/ankiexport/service.py"], "used_names": ["Mock", "Service", "json"], "enclosing_function": "test_smoke_ankiconnect_post_data_for_term", "extracted_code": "# Source: lute/ankiexport/service.py\nclass Service:\n \"Srs export service.\"\n\n def __init__(\n self,\n anki_deck_names,\n anki_note_types_and_fields,\n export_specs,\n ):\n \"init\"\n self.anki_deck_names = anki_deck_names\n self.anki_note_types_and_fields = anki_note_types_and_fields\n self.export_specs = export_specs\n\n def validate_spec(self, spec):\n \"\"\"\n Returns array of errors if any for the given spec.\n \"\"\"\n if not spec.active:\n return []\n\n errors = []\n\n try:\n validate_criteria(spec.criteria)\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n if spec.deck_name not in self.anki_deck_names:\n errors.append(f'No deck name \"{spec.deck_name}\"')\n\n valid_note_type = spec.note_type in self.anki_note_types_and_fields\n if not valid_note_type:\n errors.append(f'No note type \"{spec.note_type}\"')\n\n mapping = None\n try:\n mapping = json.loads(spec.field_mapping)\n except json.decoder.JSONDecodeError:\n errors.append(\"Mapping is not valid json\")\n\n if valid_note_type and mapping:\n note_fields = self.anki_note_types_and_fields.get(spec.note_type, {})\n bad_fields = [f for f in mapping.keys() if f not in note_fields]\n if len(bad_fields) > 0:\n bad_fields = \", \".join(bad_fields)\n msg = f\"Note type {spec.note_type} does not have field(s): {bad_fields}\"\n errors.append(msg)\n\n if mapping:\n try:\n validate_mapping(json.loads(spec.field_mapping))\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n return errors\n\n def validate_specs(self):\n \"\"\"\n Return hash of spec ids and any config errors.\n \"\"\"\n failures = {}\n for spec in self.export_specs:\n v = self.validate_spec(spec)\n if len(v) != 0:\n failures[spec.id] = \"; \".join(v)\n return failures\n\n def validate_specs_failure_message(self):\n \"Failure message for alerts.\"\n failures = self.validate_specs()\n msgs = []\n for k, v in failures.items():\n spec = next(s for s in self.export_specs if s.id == k)\n msgs.append(f\"{spec.export_name}: {v}\")\n return msgs\n\n def _all_terms(self, term):\n \"Term and any parents.\"\n ret = [term]\n ret.extend(term.parents)\n return ret\n\n def _all_tags(self, term):\n \"Tags for term and all parents.\"\n ret = [tt.text for t in self._all_terms(term) for tt in t.term_tags]\n return sorted(list(set(ret)))\n\n # pylint: disable=too-many-arguments,too-many-positional-arguments\n def _build_ankiconnect_post_json(\n self,\n mapping,\n media_mappings,\n lute_and_term_tags,\n deck_name,\n model_name,\n ):\n \"Build post json for term using the mappings.\"\n\n post_actions = []\n for new_filename, original_url in media_mappings.items():\n hsh = {\n \"action\": \"storeMediaFile\",\n \"params\": {\n \"filename\": new_filename,\n \"url\": original_url,\n },\n }\n post_actions.append(hsh)\n\n post_actions.append(\n {\n \"action\": \"addNote\",\n \"params\": {\n \"note\": {\n \"deckName\": deck_name,\n \"modelName\": model_name,\n \"fields\": mapping,\n \"tags\": lute_and_term_tags,\n }\n },\n }\n )\n\n return {\"action\": \"multi\", \"params\": {\"actions\": post_actions}}\n\n def get_ankiconnect_post_data_for_term(self, term, base_url, sentence_lookup):\n \"\"\"\n Get post data for a single term.\n This assumes that all the specs are valid!\n Separate method for unit testing.\n \"\"\"\n use_exports = [\n spec\n for spec in self.export_specs\n if spec.active and evaluate_criteria(spec.criteria, term)\n ]\n # print(f\"Using {len(use_exports)} exports\")\n\n ret = {}\n for export in use_exports:\n mapping = json.loads(export.field_mapping)\n replacements, mmap = get_values_and_media_mapping(\n term, sentence_lookup, mapping\n )\n for k, v in mmap.items():\n mmap[k] = base_url + v\n updated_mapping = get_fields_and_final_values(mapping, replacements)\n tags = [\"lute\"] + self._all_tags(term)\n\n p = self._build_ankiconnect_post_json(\n updated_mapping,\n mmap,\n tags,\n export.deck_name,\n export.note_type,\n )\n ret[export.export_name] = p\n\n return ret\n\n def get_ankiconnect_post_data(\n self, term_ids, termid_sentences, base_url, db_session\n ):\n \"\"\"\n Build data to be posted.\n\n Throws if any validation failure or mapping failure, as it's\n annoying to handle partial failures.\n \"\"\"\n\n msgs = self.validate_specs_failure_message()\n if len(msgs) > 0:\n show_msgs = [f\"* {m}\" for m in msgs]\n show_msgs = \"\\n\".join(show_msgs)\n err_msg = \"Anki export configuration errors:\\n\" + show_msgs\n raise AnkiExportConfigurationError(err_msg)\n\n repo = TermRepository(db_session)\n\n refsrepo = ReferencesRepository(db_session)\n sentence_lookup = SentenceLookup(termid_sentences, refsrepo)\n\n ret = {}\n for tid in term_ids:\n term = repo.find(tid)\n pd = self.get_ankiconnect_post_data_for_term(\n term, base_url, sentence_lookup\n )\n if len(pd) > 0:\n ret[tid] = pd\n\n return ret", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 6075}, "tests/acceptance/conftest.py::474": {"resolved_imports": [], "used_names": ["parsers", "then"], "enclosing_function": "then_reading_page_term_form_iframe_contains", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/book/test_service.py::41": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py", "lute/book/model.py", "lute/book/service.py"], "used_names": ["Book", "BookRepository", "Service", "db", "os"], "enclosing_function": "test_create_book_from_file_paths", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/repositories.py\nclass BookRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, book_id):\n \"Get by ID.\"\n return self.session.query(Book).filter(Book.id == book_id).first()\n\n def find_by_title(self, book_title, language_id):\n \"Get by title.\"\n return (\n self.session.query(Book)\n .filter(and_(Book.title == book_title, Book.language_id == language_id))\n .first()\n )\n\n\n# Source: lute/book/model.py\nclass Book: # pylint: disable=too-many-instance-attributes\n \"\"\"\n A book domain object, to create/edit lute.models.book.Books.\n\n Book language can be specified either by language_id, or\n language_name. language_name is useful for loading books via\n scripts/api. language_id takes precedence.\n \"\"\"\n\n def __init__(self):\n self.id = None\n self.language_id = None\n self.language_name = None\n self.title = None\n self.text = None\n self.source_uri = None\n self.audio_filename = None\n self.audio_current_pos = None\n self.audio_bookmarks = None\n self.book_tags = []\n\n self.threshold_page_tokens = 250\n self.split_by = \"paragraphs\"\n\n # The source file used for the book text.\n # Overrides the self.text if not None.\n self.text_source_path = None\n\n self.text_stream = None\n self.text_stream_filename = None\n\n # The source file used for audio.\n self.audio_source_path = None\n\n self.audio_stream = None\n self.audio_stream_filename = None\n\n def __repr__(self):\n return f\"\"\n\n def add_tag(self, tag):\n self.book_tags.append(tag)\n\n\n# Source: lute/book/service.py\nclass Service:\n \"Service.\"\n\n def _unique_fname(self, filename):\n \"\"\"\n Return secure name pre-pended with datetime string.\n \"\"\"\n current_datetime = datetime.now()\n formatted_datetime = current_datetime.strftime(\"%Y%m%d_%H%M%S\")\n _, ext = os.path.splitext(filename)\n ext = (ext or \"\").lower()\n newfilename = uuid.uuid4().hex\n return f\"{formatted_datetime}_{newfilename}{ext}\"\n\n def save_audio_file(self, audio_file_field_data):\n \"\"\"\n Save the file to disk, return its filename.\n \"\"\"\n filename = self._unique_fname(audio_file_field_data.filename)\n fp = os.path.join(current_app.env_config.useraudiopath, filename)\n audio_file_field_data.save(fp)\n return filename\n\n def book_data_from_url(self, url):\n \"\"\"\n Parse the url and load source data for a new Book.\n This returns a domain object, as the book is still unparsed.\n \"\"\"\n s = None\n try:\n timeout = 20 # seconds\n response = requests.get(url, timeout=timeout)\n response.raise_for_status()\n s = response.text\n except requests.exceptions.RequestException as e:\n msg = f\"Could not parse {url} (error: {str(e)})\"\n raise BookImportException(message=msg, cause=e) from e\n\n soup = BeautifulSoup(s, \"html.parser\")\n extracted_text = []\n\n # Add elements in order found.\n for element in soup.descendants:\n if element.name in (\"h1\", \"h2\", \"h3\", \"h4\", \"p\"):\n extracted_text.append(element.text)\n\n title_node = soup.find(\"title\")\n orig_title = title_node.string if title_node else url\n\n short_title = orig_title[:150]\n if len(orig_title) > 150:\n short_title += \" ...\"\n\n b = BookDataFromUrl()\n b.title = short_title\n b.source_uri = url\n b.text = \"\\n\\n\".join(extracted_text)\n return b\n\n def import_book(self, book, session):\n \"\"\"\n Save the book as a dbbook, parsing and saving files as needed.\n Returns new book created.\n \"\"\"\n\n def _raise_if_file_missing(p, fldname):\n if not os.path.exists(p):\n raise BookImportException(f\"Missing file {p} given in {fldname}\")\n\n def _raise_if_none(p, fldname):\n if p is None:\n raise BookImportException(f\"Must set {fldname}\")\n\n fte = FileTextExtraction()\n if book.text_source_path:\n _raise_if_file_missing(book.text_source_path, \"text_source_path\")\n tsp = book.text_source_path\n with open(tsp, mode=\"rb\") as stream:\n book.text = fte.get_file_content(tsp, stream)\n\n if book.text_stream:\n _raise_if_none(book.text_stream_filename, \"text_stream_filename\")\n book.text = fte.get_file_content(\n book.text_stream_filename, book.text_stream\n )\n\n if book.audio_source_path:\n _raise_if_file_missing(book.audio_source_path, \"audio_source_path\")\n newname = self._unique_fname(book.audio_source_path)\n fp = os.path.join(current_app.env_config.useraudiopath, newname)\n shutil.copy(book.audio_source_path, fp)\n book.audio_filename = newname\n\n if book.audio_stream:\n _raise_if_none(book.audio_stream_filename, \"audio_stream_filename\")\n newname = self._unique_fname(book.audio_stream_filename)\n fp = os.path.join(current_app.env_config.useraudiopath, newname)\n with open(fp, mode=\"wb\") as fcopy: # Use \"wb\" to write in binary mode\n while chunk := book.audio_stream.read(\n 8192\n ): # Read the stream in chunks (e.g., 8 KB)\n fcopy.write(chunk)\n book.audio_filename = newname\n\n repo = Repository(session)\n dbbook = repo.add(book)\n repo.commit()\n return dbbook", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 5888}, "tests/unit/ankiexport/test_field_mapping.py::198": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "SentenceLookup"], "enclosing_function": "test_sentence_lookup_finds_sentence_in_supplied_dict_or_does_db_call", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\nclass SentenceLookup:\n \"Sentence lookup, finds in a supplied dictionary or from db.\"\n\n def __init__(self, default_sentences_by_term_id, references_repo):\n \"init\"\n sdict = {}\n for k, v in default_sentences_by_term_id.items():\n sdict[int(k)] = v\n self.default_sentences_by_term_id = sdict\n self.references_repo = references_repo\n\n def get_sentence_for_term(self, term_id):\n \"Get sentence from the dict, or do a lookup.\"\n tid = int(term_id)\n if tid in self.default_sentences_by_term_id:\n return self.default_sentences_by_term_id[tid]\n\n refs = self.references_repo.find_references_by_id(term_id)\n term_refs = refs[\"term\"] or []\n if len(term_refs) == 0:\n return \"\"\n return term_refs[0].sentence", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 858}, "tests/unit/models/test_Setting.py::76": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["db"], "enclosing_function": "test_get_backup_settings", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/unit/db/setup/test_SqliteMigrator.py::76": {"resolved_imports": ["lute/db/setup/migrator.py"], "used_names": ["SqliteMigrator"], "enclosing_function": "test_migration_applied", "extracted_code": "# Source: lute/db/setup/migrator.py\nclass SqliteMigrator:\n \"\"\"\n Sqlite migrator class.\n\n Follows the principles documented in\n https://github.com/jzohrab/DbMigrator/blob/master/docs/managing_database_changes.md\n \"\"\"\n\n def __init__(self, location, repeatable):\n self.location = location\n self.repeatable = repeatable\n\n def has_migrations(self, conn):\n \"\"\"\n Return True if have non-applied migrations.\n \"\"\"\n outstanding = self._get_pending(conn)\n return len(outstanding) > 0\n\n def _get_pending(self, conn):\n \"\"\"\n Get all non-applied (one-time) migrations.\n \"\"\"\n allfiles = []\n with _change_directory(self.location):\n allfiles = [\n os.path.join(self.location, s)\n for s in os.listdir()\n if s.endswith(\".sql\")\n ]\n allfiles.sort()\n outstanding = [f for f in allfiles if self._should_apply(conn, f)]\n return outstanding\n\n def do_migration(self, conn):\n \"\"\"\n Run all migrations, then all repeatable migrations.\n \"\"\"\n self._process_folder(conn)\n self._process_repeatable(conn)\n\n def _process_folder(self, conn):\n \"\"\"\n Run all pending migrations. Write executed script to\n _migrations table.\n \"\"\"\n outstanding = self._get_pending(conn)\n for f in outstanding:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n self._add_migration_to_database(conn, f)\n\n def _process_repeatable(self, conn):\n \"\"\"\n Run all repeatable migrations.\n \"\"\"\n with _change_directory(self.repeatable):\n files = [\n os.path.join(self.repeatable, f)\n for f in os.listdir()\n if f.endswith(\".sql\")\n ]\n for f in files:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n\n def _should_apply(self, conn, filename):\n \"\"\"\n True if a migration hasn't been run yet.\n\n The file basename (no directory) is stored in the migration table.\n \"\"\"\n f = os.path.basename(filename)\n sql = f\"select count(filename) from _migrations where filename = '{f}'\"\n res = conn.execute(sql).fetchone()\n return res[0] == 0\n\n def _add_migration_to_database(self, conn, filename):\n \"\"\"\n Track the executed migration in _migrations.\n \"\"\"\n f = os.path.basename(filename)\n conn.execute(\"begin transaction\")\n conn.execute(f\"INSERT INTO _migrations values ('{f}')\")\n conn.execute(\"commit transaction\")\n\n def _process_file(self, conn, f):\n \"\"\"\n Run the given file.\n \"\"\"\n with open(f, \"r\", encoding=\"utf8\") as sql_file:\n commands = sql_file.read()\n self._exec_commands(conn, commands)\n\n def _exec_commands(self, conn, sql):\n \"\"\"\n Execute all commands in the given file.\n \"\"\"\n conn.executescript(sql)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3329}, "tests/unit/db/test_demo.py::58": {"resolved_imports": ["lute/db/__init__.py", "lute/db/demo.py", "lute/parse/registry.py"], "used_names": [], "enclosing_function": "test_smoke_test_load_demo_works", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/integration/ankiexport/test_smoke_anki_export.py::100": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py", "lute/models/srsexport.py", "lute/ankiexport/service.py"], "used_names": ["Service", "SrsExportSpec", "Term", "TermTag", "db", "json"], "enclosing_function": "test_smoke_get_post_data", "extracted_code": "# Source: lute/models/term.py\nclass TermTag(db.Model):\n \"Term tags.\"\n __tablename__ = \"tags\"\n\n id = db.Column(\"TgID\", db.Integer, primary_key=True)\n text = db.Column(\"TgText\", db.String(20))\n _comment = db.Column(\"TgComment\", db.String(200))\n\n def __init__(self, text, comment=None):\n self.text = text\n self.comment = comment\n\n @property\n def comment(self):\n \"Comment getter.\"\n return self._comment\n\n # TODO zzfuture fix: TgComment should be nullable\n # The current schema has the TgComment NOT NULL default '',\n # which was a legacy copy over from LWT. Really, this should\n # be a nullable column, and all blanks should be NULL.\n # Minor change, a nice-to-have.\n @comment.setter\n def comment(self, c):\n \"Set cleaned comment.\"\n self._comment = c if c is not None else \"\"\n\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/srsexport.py\nclass SrsExportSpec(db.Model):\n \"\"\"\n Srs export spec entity.\n \"\"\"\n\n __tablename__ = \"srsexportspecs\"\n\n id = db.Column(\"SrsID\", db.Integer, primary_key=True)\n export_name = db.Column(\n \"SrsExportName\", db.String(200), nullable=False, unique=True\n )\n criteria = db.Column(\"SrsCriteria\", db.String(1000), nullable=False)\n deck_name = db.Column(\"SrsDeckName\", db.String(200), nullable=False)\n note_type = db.Column(\"SrsNoteType\", db.String(200), nullable=False)\n field_mapping = db.Column(\"SrsFieldMapping\", db.String(1000), nullable=False)\n active = db.Column(\"SrsActive\", db.Boolean, nullable=False, default=True)\n\n\n# Source: lute/ankiexport/service.py\nclass Service:\n \"Srs export service.\"\n\n def __init__(\n self,\n anki_deck_names,\n anki_note_types_and_fields,\n export_specs,\n ):\n \"init\"\n self.anki_deck_names = anki_deck_names\n self.anki_note_types_and_fields = anki_note_types_and_fields\n self.export_specs = export_specs\n\n def validate_spec(self, spec):\n \"\"\"\n Returns array of errors if any for the given spec.\n \"\"\"\n if not spec.active:\n return []\n\n errors = []\n\n try:\n validate_criteria(spec.criteria)\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n if spec.deck_name not in self.anki_deck_names:\n errors.append(f'No deck name \"{spec.deck_name}\"')\n\n valid_note_type = spec.note_type in self.anki_note_types_and_fields\n if not valid_note_type:\n errors.append(f'No note type \"{spec.note_type}\"')\n\n mapping = None\n try:\n mapping = json.loads(spec.field_mapping)\n except json.decoder.JSONDecodeError:\n errors.append(\"Mapping is not valid json\")\n\n if valid_note_type and mapping:\n note_fields = self.anki_note_types_and_fields.get(spec.note_type, {})\n bad_fields = [f for f in mapping.keys() if f not in note_fields]\n if len(bad_fields) > 0:\n bad_fields = \", \".join(bad_fields)\n msg = f\"Note type {spec.note_type} does not have field(s): {bad_fields}\"\n errors.append(msg)\n\n if mapping:\n try:\n validate_mapping(json.loads(spec.field_mapping))\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n return errors\n\n def validate_specs(self):\n \"\"\"\n Return hash of spec ids and any config errors.\n \"\"\"\n failures = {}\n for spec in self.export_specs:\n v = self.validate_spec(spec)\n if len(v) != 0:\n failures[spec.id] = \"; \".join(v)\n return failures\n\n def validate_specs_failure_message(self):\n \"Failure message for alerts.\"\n failures = self.validate_specs()\n msgs = []\n for k, v in failures.items():\n spec = next(s for s in self.export_specs if s.id == k)\n msgs.append(f\"{spec.export_name}: {v}\")\n return msgs\n\n def _all_terms(self, term):\n \"Term and any parents.\"\n ret = [term]\n ret.extend(term.parents)\n return ret\n\n def _all_tags(self, term):\n \"Tags for term and all parents.\"\n ret = [tt.text for t in self._all_terms(term) for tt in t.term_tags]\n return sorted(list(set(ret)))\n\n # pylint: disable=too-many-arguments,too-many-positional-arguments\n def _build_ankiconnect_post_json(\n self,\n mapping,\n media_mappings,\n lute_and_term_tags,\n deck_name,\n model_name,\n ):\n \"Build post json for term using the mappings.\"\n\n post_actions = []\n for new_filename, original_url in media_mappings.items():\n hsh = {\n \"action\": \"storeMediaFile\",\n \"params\": {\n \"filename\": new_filename,\n \"url\": original_url,\n },\n }\n post_actions.append(hsh)\n\n post_actions.append(\n {\n \"action\": \"addNote\",\n \"params\": {\n \"note\": {\n \"deckName\": deck_name,\n \"modelName\": model_name,\n \"fields\": mapping,\n \"tags\": lute_and_term_tags,\n }\n },\n }\n )\n\n return {\"action\": \"multi\", \"params\": {\"actions\": post_actions}}\n\n def get_ankiconnect_post_data_for_term(self, term, base_url, sentence_lookup):\n \"\"\"\n Get post data for a single term.\n This assumes that all the specs are valid!\n Separate method for unit testing.\n \"\"\"\n use_exports = [\n spec\n for spec in self.export_specs\n if spec.active and evaluate_criteria(spec.criteria, term)\n ]\n # print(f\"Using {len(use_exports)} exports\")\n\n ret = {}\n for export in use_exports:\n mapping = json.loads(export.field_mapping)\n replacements, mmap = get_values_and_media_mapping(\n term, sentence_lookup, mapping\n )\n for k, v in mmap.items():\n mmap[k] = base_url + v\n updated_mapping = get_fields_and_final_values(mapping, replacements)\n tags = [\"lute\"] + self._all_tags(term)\n\n p = self._build_ankiconnect_post_json(\n updated_mapping,\n mmap,\n tags,\n export.deck_name,\n export.note_type,\n )\n ret[export.export_name] = p\n\n return ret\n\n def get_ankiconnect_post_data(\n self, term_ids, termid_sentences, base_url, db_session\n ):\n \"\"\"\n Build data to be posted.\n\n Throws if any validation failure or mapping failure, as it's\n annoying to handle partial failures.\n \"\"\"\n\n msgs = self.validate_specs_failure_message()\n if len(msgs) > 0:\n show_msgs = [f\"* {m}\" for m in msgs]\n show_msgs = \"\\n\".join(show_msgs)\n err_msg = \"Anki export configuration errors:\\n\" + show_msgs\n raise AnkiExportConfigurationError(err_msg)\n\n repo = TermRepository(db_session)\n\n refsrepo = ReferencesRepository(db_session)\n sentence_lookup = SentenceLookup(termid_sentences, refsrepo)\n\n ret = {}\n for tid in term_ids:\n term = repo.find(tid)\n pd = self.get_ankiconnect_post_data_for_term(\n term, base_url, sentence_lookup\n )\n if len(pd) > 0:\n ret[tid] = pd\n\n return ret", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 15070}, "tests/unit/themes/test_service.py::58": {"resolved_imports": ["lute/themes/service.py", "lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["Service", "UserSettingRepository", "db"], "enclosing_function": "test_next_theme_cycles_themes", "extracted_code": "# Source: lute/themes/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _css_path(self):\n \"\"\"\n Path to css in this folder.\n \"\"\"\n thisdir = os.path.dirname(__file__)\n theme_dir = os.path.join(thisdir, \"css\")\n return os.path.abspath(theme_dir)\n\n def list_themes(self):\n \"\"\"\n List of theme file names and user-readable name.\n \"\"\"\n\n def _make_display_name(s):\n ret = os.path.basename(s)\n ret = ret.replace(\".css\", \"\").replace(\"_\", \" \")\n return ret\n\n g = glob(os.path.join(self._css_path(), \"*.css\"))\n themes = [(os.path.basename(f), _make_display_name(f)) for f in g]\n theme_basenames = [t[0] for t in themes]\n\n g = glob(os.path.join(current_app.env_config.userthemespath, \"*.css\"))\n additional_user_themes = [\n (os.path.basename(f), _make_display_name(f))\n for f in g\n if os.path.basename(f) not in theme_basenames\n ]\n\n themes += additional_user_themes\n sorted_themes = sorted(themes, key=lambda x: x[1])\n return [default_entry] + sorted_themes\n\n def get_current_css(self):\n \"\"\"\n Return the current css pointed at by the current_theme user setting.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n if current_theme == default_entry[0]:\n return \"\"\n\n def _get_theme_css_in_dir(d):\n \"Get css, or '' if no file.\"\n fname = os.path.join(d, current_theme)\n if not os.path.exists(fname):\n return \"\"\n with open(fname, \"r\", encoding=\"utf-8\") as f:\n return f.read()\n\n ret = _get_theme_css_in_dir(self._css_path())\n add = _get_theme_css_in_dir(current_app.env_config.userthemespath)\n if add != \"\":\n ret += f\"\\n\\n/* Additional user css */\\n\\n{add}\"\n return ret\n\n def next_theme(self):\n \"\"\"\n Move to the next theme in the list of themes.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n themes = [t[0] for t in self.list_themes()]\n themes.append(default_entry[0])\n for i in range(0, len(themes)): # pylint: disable=consider-using-enumerate\n if themes[i] == current_theme:\n new_index = i + 1\n break\n repo.set_value(\"current_theme\", themes[new_index])\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/repositories.py\nclass UserSettingRepository(SettingRepositoryBase):\n \"Repository.\"\n\n def __init__(self, session):\n super().__init__(session, UserSetting)\n\n def key_exists_precheck(self, keyname):\n \"\"\"\n User keys must exist.\n \"\"\"\n if not self.key_exists(keyname):\n raise MissingUserSettingKeyException(keyname)\n\n def get_backup_settings(self):\n \"Convenience method.\"\n bs = BackupSettings()\n\n def _bool(v):\n return v in (1, \"1\", \"y\", True)\n\n bs.backup_enabled = _bool(self.get_value(\"backup_enabled\"))\n bs.backup_auto = _bool(self.get_value(\"backup_auto\"))\n bs.backup_warn = _bool(self.get_value(\"backup_warn\"))\n bs.backup_dir = self.get_value(\"backup_dir\")\n bs.backup_count = int(self.get_value(\"backup_count\") or 5)\n bs.last_backup_datetime = self.get_last_backup_datetime()\n return bs\n\n def get_last_backup_datetime(self):\n \"Get the last_backup_datetime as int, or None.\"\n v = self.get_value(\"lastbackup\")\n if v is None:\n return None\n return int(v)\n\n def set_last_backup_datetime(self, v):\n \"Set and save the last backup time.\"\n self.set_value(\"lastbackup\", v)\n self.session.commit()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3977}, "tests/orm/test_Book.py::138": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["TextBookmark", "assert_record_count_equals", "assert_sql_result", "db"], "enclosing_function": "test_delete_book_cascade_deletes_bookmarks", "extracted_code": "# Source: lute/models/book.py\nclass TextBookmark(db.Model):\n \"\"\"\n Bookmarks for a given Book page\n\n The TextBookmark includes a title\n \"\"\"\n\n __tablename__ = \"textbookmarks\"\n\n id = db.Column(\"TbID\", db.Integer, primary_key=True)\n tx_id = db.Column(\n \"TbTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"CASCADE\"),\n nullable=False,\n )\n title = db.Column(\"TbTitle\", db.Text, nullable=False)\n\n text = db.relationship(\"Text\", back_populates=\"bookmarks\")\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 565}, "tests/unit/parse/test_JapaneseParser.py::108": {"resolved_imports": ["lute/parse/mecab_parser.py", "lute/models/term.py", "lute/settings/current.py", "lute/parse/base.py"], "used_names": ["JapaneseParser", "current_settings"], "enclosing_function": "test_reading_setting", "extracted_code": "# Source: lute/parse/mecab_parser.py\nclass JapaneseParser(AbstractParser):\n \"\"\"\n Japanese parser.\n\n This is only supported if mecab is installed.\n\n The parser uses natto-py library, and so should\n be able to find mecab automatically; if it can't,\n you may need to set the MECAB_PATH env variable,\n managed by UserSettingRepository.set_value(\"mecab_path\", p)\n \"\"\"\n\n _is_supported = None\n _old_mecab_path = None\n\n @classmethod\n def is_supported(cls):\n \"\"\"\n True if a natto MeCab can be instantiated,\n otherwise false.\n \"\"\"\n\n mecab_path = current_settings.get(\"mecab_path\", \"\") or \"\"\n mecab_path = mecab_path.strip()\n path_unchanged = mecab_path == JapaneseParser._old_mecab_path\n if path_unchanged and JapaneseParser._is_supported is not None:\n return JapaneseParser._is_supported\n\n # Natto uses the MECAB_PATH env key if it's set.\n env_key = \"MECAB_PATH\"\n if mecab_path != \"\":\n os.environ[env_key] = mecab_path\n else:\n os.environ.pop(env_key, None)\n\n mecab_works = False\n\n # Calling MeCab() prints to stderr even if the\n # exception is caught. Suppress that output noise.\n temp_err = StringIO()\n try:\n sys.stderr = temp_err\n MeCab()\n mecab_works = True\n except: # pylint: disable=bare-except\n mecab_works = False\n finally:\n sys.stderr = sys.__stderr__\n\n JapaneseParser._old_mecab_path = mecab_path\n JapaneseParser._is_supported = mecab_works\n return mecab_works\n\n @classmethod\n def name(cls):\n return \"Japanese\"\n\n def get_parsed_tokens(self, text: str, language) -> List[ParsedToken]:\n \"Parse the string using MeCab.\"\n text = re.sub(r\"[ \\t]+\", \" \", text).strip()\n\n lines = []\n\n # If the string contains a \"\\n\", MeCab appears to silently\n # remove it. Splitting it works (ref test_JapaneseParser).\n # Flags: ref https://github.com/buruzaemon/natto-py:\n # -F = node format\n # -U = unknown format\n # -E = EOP format\n with MeCab(r\"-F %m\\t%t\\t%h\\n -U %m\\t%t\\t%h\\n -E EOP\\t3\\t7\\n\") as nm:\n for para in text.split(\"\\n\"):\n for n in nm.parse(para, as_nodes=True):\n lines.append(n.feature)\n\n lines = [\n n.strip().split(\"\\t\") for n in lines if n is not None and n.strip() != \"\"\n ]\n\n # Production bug: JP parsing with MeCab would sometimes return a line\n # \"0\\t4\" before an end-of-paragraph \"EOP\\t3\\t7\", reasons unknown. These\n # \"0\\t4\" tokens don't have any function, and cause problems in subsequent\n # steps of the processing in line_to_token(), so just remove them.\n lines = [n for n in lines if len(n) == 3]\n\n def line_to_token(lin):\n \"Convert parsed line to a ParsedToken.\"\n term, node_type, third = lin\n is_eos = term in language.regexp_split_sentences\n if term == \"EOP\" and third == \"7\":\n term = \"¶\"\n\n # Node type values ref\n # https://github.com/buruzaemon/natto-py/wiki/\n # Node-Parsing-char_type\n #\n # The repeat character is sometimes returned as a \"symbol\"\n # (node type = 3), so handle that specifically.\n is_word = node_type in \"2678\" or term == \"々\"\n return ParsedToken(term, is_word, is_eos or term == \"¶\")\n\n tokens = [line_to_token(lin) for lin in lines]\n return tokens\n\n # Hiragana is Unicode code block U+3040 - U+309F\n # ref https://stackoverflow.com/questions/72016049/\n # how-to-check-if-text-is-japanese-hiragana-in-python\n def _char_is_hiragana(self, c) -> bool:\n return \"\\u3040\" <= c <= \"\\u309F\"\n\n def _string_is_hiragana(self, s: str) -> bool:\n return all(self._char_is_hiragana(c) for c in s)\n\n def get_reading(self, text: str):\n \"\"\"\n Get the pronunciation for the given text.\n\n Returns None if the text is all hiragana, or the pronunciation\n doesn't add value (same as text).\n \"\"\"\n if self._string_is_hiragana(text):\n return None\n\n jp_reading_setting = current_settings.get(\"japanese_reading\", \"\").strip()\n if jp_reading_setting == \"\":\n # Don't set reading if nothing specified.\n return None\n\n flags = r\"-O yomi\"\n readings = []\n with MeCab(flags) as nm:\n for n in nm.parse(text, as_nodes=True):\n readings.append(n.feature)\n readings = [r.strip() for r in readings if r is not None and r.strip() != \"\"]\n\n ret = \"\".join(readings).strip()\n if ret in (\"\", text):\n return None\n\n if jp_reading_setting == \"katakana\":\n return ret\n if jp_reading_setting == \"hiragana\":\n return jaconv.kata2hira(ret)\n if jp_reading_setting == \"alphabet\":\n return jaconv.kata2alphabet(ret)\n raise RuntimeError(f\"Bad reading type {jp_reading_setting}\")\n\n\n# Source: lute/settings/current.py\ncurrent_settings = {}", "n_imports_parsed": 4, "n_files_resolved": 4, "n_chars_extracted": 5214}, "tests/unit/models/test_Language.py::41": {"resolved_imports": ["lute/db/__init__.py", "lute/db/demo.py", "lute/models/language.py", "lute/models/repositories.py"], "used_names": ["Language"], "enclosing_function": "test_new_language_has_sane_defaults", "extracted_code": "# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 5989}, "tests/unit/book/test_token_group_generator.py::28": {"resolved_imports": ["lute/book/model.py", "lute/parse/space_delimited_parser.py"], "used_names": ["SpaceDelimitedParser", "token_group_generator"], "enclosing_function": "scenario", "extracted_code": "# Source: lute/book/model.py\ndef token_group_generator(tokens, group_type, threshold=500):\n \"\"\"\n A generator that yields groups of ParsedTokens grouped by sentence or paragraph\n with each group containing at least the threshold number of tokens.\n \"\"\"\n current_group = []\n buff = []\n\n def trim_paras(tok_array):\n \"Remove para tokens from beginning and end.\"\n while tok_array and tok_array[0].is_end_of_paragraph:\n tok_array.pop(0)\n while tok_array and tok_array[-1].is_end_of_paragraph:\n tok_array.pop()\n return tok_array\n\n def _matches_group_delimiter(tok):\n if group_type == \"sentences\":\n return tok.is_end_of_sentence\n if group_type == \"paragraphs\":\n return tok.is_end_of_paragraph\n raise RuntimeError(\"Unhandled type \" + group_type)\n\n for token in tokens:\n buff.append(token)\n if _matches_group_delimiter(token):\n current_group.extend(buff)\n # pylint: disable=consider-using-generator\n current_count = sum([1 for t in current_group if t.is_word])\n buff = []\n\n # Yield if threshold exceeded.\n # Remove the final paragreph marker if it's there, it's not needed.\n if current_count > threshold:\n current_group = trim_paras(current_group)\n yield current_group\n current_group = []\n\n # Add any remaining tokens\n if buff:\n current_group.extend(buff)\n current_group = trim_paras(current_group)\n if current_group:\n yield current_group\n\n\n# Source: lute/parse/space_delimited_parser.py\nclass SpaceDelimitedParser(AbstractParser):\n \"\"\"\n A general parser for space-delimited languages,\n such as English, French, Spanish ... etc.\n \"\"\"\n\n @classmethod\n def name(cls):\n return \"Space Delimited\"\n\n @staticmethod\n @functools.lru_cache\n def compile_re_pattern(pattern: str, *args, **kwargs) -> re.Pattern:\n \"\"\"Compile regular expression pattern, cache result for fast re-use.\"\"\"\n return re.compile(pattern, *args, **kwargs)\n\n @staticmethod\n @functools.lru_cache\n def get_default_word_characters() -> str:\n \"\"\"Return default value for lang.word_characters.\"\"\"\n\n # Unicode categories reference: https://www.compart.com/en/unicode/category\n categories = set([\"Cf\", \"Ll\", \"Lm\", \"Lo\", \"Lt\", \"Lu\", \"Mc\", \"Mn\", \"Sk\"])\n\n # There are more than 130,000 characters across all these categories.\n # Expressing this a single character at a time, mostly using unicode\n # escape sequences like \\u1234 or \\U12345678, would require 1 megabyte.\n # Converting to ranges like \\u1234-\\u1256 requires only 10K.\n ranges = []\n current = None\n\n def add_current_to_ranges():\n def ucode(n):\n \"Unicode point for integer.\"\n fstring = r\"\\u{:04x}\" if n < 0x10000 else r\"\\U{:08x}\"\n return (fstring).format(n)\n\n start_code = ucode(current[0])\n if current[0] == current[1]:\n range_string = start_code\n else:\n endcode = ucode(current[1])\n range_string = f\"{start_code}-{endcode}\"\n ranges.append(range_string)\n\n for i in range(1, sys.maxunicode):\n if unicodedata.category(chr(i)) not in categories:\n if current is not None:\n add_current_to_ranges()\n current = None\n elif current is None:\n # Starting a new range.\n current = [i, i]\n else:\n # Extending existing range.\n current[1] = i\n\n if current is not None:\n add_current_to_ranges()\n\n return \"\".join(ranges)\n\n @staticmethod\n @functools.lru_cache\n def get_default_regexp_split_sentences() -> str:\n \"\"\"Return default value for lang.regexp_split_sentences.\"\"\"\n\n # Construct pattern from Unicode ATerm and STerm categories.\n # See: https://www.unicode.org/Public/UNIDATA/auxiliary/SentenceBreakProperty.txt\n # and: https://unicode.org/reports/tr29/\n\n # Also include colon, since that is used to separate speakers\n # and their dialog, and is a reasonable dividing point for\n # sentence translations.\n\n return \"\".join(\n [\n re.escape(\".!?:\"),\n # ATerm entries (other than \".\", covered above):\n r\"\\u2024\\uFE52\\uFF0E\",\n # STerm entries (other than \"!\" and \"?\", covered above):\n r\"\\u0589\",\n r\"\\u061D-\\u061F\\u06D4\",\n r\"\\u0700-\\u0702\",\n r\"\\u07F9\",\n r\"\\u0837\\u0839\\u083D\\u083E\",\n r\"\\u0964\\u0965\",\n r\"\\u104A\\u104B\",\n r\"\\u1362\\u1367\\u1368\",\n r\"\\u166E\",\n r\"\\u1735\\u1736\",\n r\"\\u17D4\\u17D5\",\n r\"\\u1803\\u1809\",\n r\"\\u1944\\u1945\",\n r\"\\u1AA8-\\u1AAB\",\n r\"\\u1B5A\\u1B5B\\u1B5E\\u1B5F\\u1B7D\\u1B7E\",\n r\"\\u1C3B\\u1C3C\",\n r\"\\u1C7E\\u1C7F\",\n r\"\\u203C\\u203D\\u2047-\\u2049\\u2E2E\\u2E3C\\u2E53\\u2E54\\u3002\",\n r\"\\uA4FF\",\n r\"\\uA60E\\uA60F\",\n r\"\\uA6F3\\uA6F7\",\n r\"\\uA876\\uA877\",\n r\"\\uA8CE\\uA8CF\",\n r\"\\uA92F\",\n r\"\\uA9C8\\uA9C9\",\n r\"\\uAA5D\\uAA5F\",\n r\"\\uAAF0\\uAAF1\\uABEB\",\n r\"\\uFE56\\uFE57\\uFF01\\uFF1F\\uFF61\",\n r\"\\U00010A56\\U00010A57\",\n r\"\\U00010F55-\\U00010F59\",\n r\"\\U00010F86-\\U00010F89\",\n r\"\\U00011047\\U00011048\",\n r\"\\U000110BE-\\U000110C1\",\n r\"\\U00011141-\\U00011143\",\n r\"\\U000111C5\\U000111C6\\U000111CD\\U000111DE\\U000111DF\",\n r\"\\U00011238\\U00011239\\U0001123B\\U0001123C\",\n r\"\\U000112A9\",\n r\"\\U0001144B\\U0001144C\",\n r\"\\U000115C2\\U000115C3\\U000115C9-\\U000115D7\",\n r\"\\U00011641\\U00011642\",\n r\"\\U0001173C-\\U0001173E\",\n r\"\\U00011944\\u00011946\",\n r\"\\U00011A42\\U00011A43\",\n r\"\\U00011A9B\\U00011A9C\",\n r\"\\U00011C41\\U00011C42\",\n r\"\\U00011EF7\\U00011EF8\",\n r\"\\U00011F43\\U00011F44\",\n r\"\\U00016A6E\\U00016A6F\",\n r\"\\U00016AF5\",\n r\"\\U00016B37\\U00016B38\\U00016B44\",\n r\"\\U00016E98\",\n r\"\\U0001BC9F\",\n r\"\\U0001DA88\",\n ]\n )\n\n def get_parsed_tokens(self, text: str, language) -> List[ParsedToken]:\n \"Return parsed tokens.\"\n\n # Remove extra spaces.\n clean_text = re.sub(r\" +\", \" \", text)\n\n # Remove zero-width spaces.\n clean_text = clean_text.replace(chr(0x200B), \"\")\n\n return self._parse_to_tokens(clean_text, language)\n\n def preg_match_capture(self, pattern, subject):\n \"\"\"\n Return the matched text and their start positions in the subject.\n\n E.g. search for r'cat' in \"there is a CAT and a Cat\" returns:\n [['CAT', 11], ['Cat', 21]]\n \"\"\"\n compiled = SpaceDelimitedParser.compile_re_pattern(pattern, flags=re.IGNORECASE)\n matches = compiled.finditer(subject)\n result = [[match.group(), match.start()] for match in matches]\n return result\n\n def _parse_to_tokens(self, text: str, lang):\n \"\"\"\n Returns ParsedToken array for given language.\n \"\"\"\n replacements = lang.character_substitutions.split(\"|\")\n for replacement in replacements:\n fromto = replacement.strip().split(\"=\")\n if len(fromto) >= 2:\n rfrom = fromto[0].strip()\n rto = fromto[1].strip()\n text = text.replace(rfrom, rto)\n\n text = text.replace(\"\\r\\n\", \"\\n\")\n text = text.replace(\"{\", \"[\")\n text = text.replace(\"}\", \"]\")\n\n tokens = []\n paras = text.split(\"\\n\")\n pcount = len(paras)\n for i, para in enumerate(paras):\n self.parse_para(para, lang, tokens)\n if i != (pcount - 1):\n tokens.append(ParsedToken(\"¶\", False, True))\n\n return tokens\n\n def parse_para(self, text: str, lang, tokens: List[ParsedToken]):\n \"\"\"\n Parse a string, appending the tokens to the list of tokens.\n \"\"\"\n termchar = lang.word_characters.strip()\n if not termchar:\n termchar = SpaceDelimitedParser.get_default_word_characters()\n\n splitex = lang.exceptions_split_sentences.replace(\".\", \"\\\\.\")\n pattern = rf\"({splitex}|[{termchar}]*)\"\n if splitex.strip() == \"\":\n pattern = rf\"([{termchar}]*)\"\n\n m = self.preg_match_capture(pattern, text)\n wordtoks = list(filter(lambda t: t[0] != \"\", m))\n\n def add_non_words(s):\n \"\"\"\n Add non-word token s to the list of tokens. If s\n matches any of the split_sentence values, mark it as an\n end-of-sentence.\n \"\"\"\n if not s:\n return\n splitchar = lang.regexp_split_sentences.strip()\n if not splitchar:\n splitchar = SpaceDelimitedParser.get_default_regexp_split_sentences()\n pattern = f\"[{re.escape(splitchar)}]\"\n has_eos = False\n if pattern != \"[]\": # Should never happen, but ...\n allmatches = self.preg_match_capture(pattern, s)\n has_eos = len(allmatches) > 0\n tokens.append(ParsedToken(s, False, has_eos))\n\n # For each wordtok, add all non-words before the wordtok, and\n # then add the wordtok.\n pos = 0\n for wt in wordtoks:\n w = wt[0]\n wp = wt[1]\n s = text[pos:wp]\n add_non_words(s)\n tokens.append(ParsedToken(w, True, False))\n pos = wp + len(w)\n\n # Add anything left over.\n s = text[pos:]\n add_non_words(s)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 10193}, "tests/unit/utils/test_formutils.py::15": {"resolved_imports": ["lute/db/__init__.py", "lute/utils/formutils.py", "lute/models/repositories.py"], "used_names": ["db", "language_choices"], "enclosing_function": "test_language_choices", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/utils/formutils.py\ndef language_choices(session, dummy_entry_placeholder=\"-\"):\n \"\"\"\n Return the list of languages for select boxes.\n\n If only one lang exists, only return that,\n otherwise add a '-' dummy entry at the top.\n \"\"\"\n langs = session.query(Language).order_by(Language.name).all()\n supported = [lang for lang in langs if lang.is_supported]\n lang_choices = [(s.id, s.name) for s in supported]\n # Add a dummy placeholder even if there are no languages.\n if len(lang_choices) != 1:\n lang_choices = [(0, dummy_entry_placeholder)] + lang_choices\n return lang_choices", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 675}, "tests/unit/models/test_TermTag.py::41": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["TermTagRepository", "db"], "enclosing_function": "test_find_by_text", "extracted_code": "# Source: lute/models/repositories.py\nclass TermTagRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, termtag_id):\n \"Get by ID.\"\n return self.session.query(TermTag).filter(TermTag.id == termtag_id).first()\n\n def find_by_text(self, text):\n \"Find a tag by text, or None if not found.\"\n return self.session.query(TermTag).filter(TermTag.text == text).first()\n\n def find_or_create_by_text(self, text):\n \"Return tag or create one.\"\n ret = self.find_by_text(text)\n if ret is not None:\n return ret\n return TermTag(text)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 699}, "tests/orm/test_Language.py::123": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["LanguageDictionary", "add_terms", "assert_record_count_equals", "assert_sql_result", "db", "make_text"], "enclosing_function": "test_delete_language_removes_book_and_terms", "extracted_code": "# Source: lute/models/language.py\nclass LanguageDictionary(db.Model):\n \"\"\"\n Language dictionary.\n \"\"\"\n\n __tablename__ = \"languagedicts\"\n\n id = db.Column(\"LdID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\n \"LdLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n language = db.relationship(\"Language\", back_populates=\"dictionaries\")\n usefor = db.Column(\"LdUseFor\", db.String(20), nullable=False)\n dicttype = db.Column(\"LdType\", db.String(20), nullable=False)\n dicturi = db.Column(\"LdDictURI\", db.String(200), nullable=False)\n is_active = db.Column(\"LdIsActive\", db.Boolean, default=True)\n sort_order = db.Column(\"LdSortOrder\", db.SmallInteger, nullable=False)\n\n # HACK: pre-pend '*' to URLs that need to open a new window.\n # This is a relic of the original code, and should be changed.\n # TODO remove-asterisk-hack: remove * from URL start.\n def make_uri(self):\n \"Hack add asterisk.\"\n prepend = \"*\" if self.dicttype == \"popuphtml\" else \"\"\n return f\"{prepend}{self.dicturi}\"\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 1137}, "tests/orm/test_Language.py::88": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Language", "LanguageDictionary", "LanguageRepository", "assert_sql_result", "db", "json"], "enclosing_function": "test_language_dictionaries_smoke_test", "extracted_code": "# Source: lute/models/language.py\nclass LanguageDictionary(db.Model):\n \"\"\"\n Language dictionary.\n \"\"\"\n\n __tablename__ = \"languagedicts\"\n\n id = db.Column(\"LdID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\n \"LdLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n language = db.relationship(\"Language\", back_populates=\"dictionaries\")\n usefor = db.Column(\"LdUseFor\", db.String(20), nullable=False)\n dicttype = db.Column(\"LdType\", db.String(20), nullable=False)\n dicturi = db.Column(\"LdDictURI\", db.String(200), nullable=False)\n is_active = db.Column(\"LdIsActive\", db.Boolean, default=True)\n sort_order = db.Column(\"LdSortOrder\", db.SmallInteger, nullable=False)\n\n # HACK: pre-pend '*' to URLs that need to open a new window.\n # This is a relic of the original code, and should be changed.\n # TODO remove-asterisk-hack: remove * from URL start.\n def make_uri(self):\n \"Hack add asterisk.\"\n prepend = \"*\" if self.dicttype == \"popuphtml\" else \"\"\n return f\"{prepend}{self.dicturi}\"\n\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/models/repositories.py\nclass LanguageRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, language_id):\n \"Get by ID.\"\n return self.session.query(Language).filter(Language.id == language_id).first()\n\n def find_by_name(self, name):\n \"Get by name.\"\n return (\n self.session.query(Language)\n .filter(func.lower(Language.name) == func.lower(name))\n .first()\n )\n\n def all_dictionaries(self):\n \"All dictionaries for all languages.\"\n lang_dicts = {}\n for lang in db.session.query(Language).all():\n lang_dicts[lang.id] = {\n \"term\": lang.active_dict_uris(\"terms\"),\n \"sentence\": lang.active_dict_uris(\"sentences\"),\n }\n return lang_dicts\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 7952}, "tests/unit/read/render/test_service.py::102": {"resolved_imports": ["lute/parse/base.py", "lute/read/render/service.py", "lute/db/__init__.py", "lute/models/term.py"], "used_names": ["ParsedToken", "Service", "Term", "add_terms", "assert_sql_result", "db", "make_text"], "enclosing_function": "test_smoke_get_paragraphs", "extracted_code": "# Source: lute/parse/base.py\nclass ParsedToken:\n \"\"\"\n A single parsed token from an input text.\n\n As tokens are created, the class counters\n (starting with cls_) are assigned to the ParsedToken\n and then incremented appropriately.\n \"\"\"\n\n # Class counters.\n cls_sentence_number = 0\n cls_order = 0\n\n @classmethod\n def reset_counters(cls):\n \"\"\"\n Reset all the counters.\n \"\"\"\n ParsedToken.cls_sentence_number = 0\n ParsedToken.cls_order = 0\n\n def __init__(self, token: str, is_word: bool, is_end_of_sentence: bool = False):\n self.token = token\n self.is_word = is_word\n self.is_end_of_sentence = is_end_of_sentence\n\n ParsedToken.cls_order += 1\n self.order = ParsedToken.cls_order\n\n self.sentence_number = ParsedToken.cls_sentence_number\n\n # Increment counters after the TextToken has been\n # completed, so that it belongs to the correct\n # sentence.\n if self.is_end_of_sentence:\n ParsedToken.cls_sentence_number += 1\n\n @property\n def is_end_of_paragraph(self):\n return self.token.strip() == \"¶\"\n\n def __repr__(self):\n attrs = [\n f\"word: {self.is_word}\",\n f\"eos: {self.is_end_of_sentence}\",\n # f\"sent: {self.sentence_number}\",\n ]\n attrs = \", \".join(attrs)\n return f'<\"{self.token}\" ({attrs})>'\n\n\n# Source: lute/read/render/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def find_all_Terms_in_string(self, s, language): # pylint: disable=too-many-locals\n \"\"\"\n Find all terms contained in the string s.\n\n For example\n - given s = \"Here is a cat\"\n - given terms in the db: [ \"cat\", \"a cat\", \"dog\" ]\n\n This would return the terms \"cat\" and \"a cat\".\n \"\"\"\n cleaned = re.sub(r\" +\", \" \", s)\n tokens = language.get_parsed_tokens(cleaned)\n return self._find_all_terms_in_tokens(tokens, language)\n\n def _get_multiword_terms(self, language):\n \"Get all multiword terms.\"\n sql = sqltext(\n \"\"\"\n SELECT WoID, WoTextLC FROM words\n WHERE WoLgID=:language_id and WoTokenCount>1\n \"\"\"\n )\n sql = sql.bindparams(language_id=language.id)\n return self.session.execute(sql).all()\n\n def _find_all_multi_word_term_text_lcs_in_content(self, text_lcs, language):\n \"Find multiword terms, return list of text_lcs.\"\n\n # There are a few ways of finding multi-word Terms\n # (with token_count > 1) in the content:\n #\n # 1. load each mword term text_lc via sql and check.\n # 2. using the model\n # 3. SQL with \"LIKE\"\n #\n # During reasonable test runs with my data, the times in seconds\n # for each are similar (~0.02, ~0.05, ~0.025). This method is\n # only used for small amounts of data, and the user experience hit\n # is negligible, so I'll use the first method which IMO is the clearest\n # code.\n\n zws = \"\\u200B\" # zero-width space\n content = zws + zws.join(text_lcs) + zws\n\n # Method 1:\n reclist = self._get_multiword_terms(language)\n return [p[1] for p in reclist if f\"{zws}{p[1]}{zws}\" in content]\n\n ## # Method 2: use the model.\n ## contained_term_qry = self.session.query(Term).filter(\n ## Term.language == language,\n ## Term.token_count > 1,\n ## func.instr(content, Term.text_lc) > 0,\n ## )\n ## return [r.text_lc for r in contained_term_qry.all()]\n\n ## # Method 3: Query with LIKE\n ## sql = sqltext(\n ## \"\"\"\n ## SELECT WoTextLC FROM words\n ## WHERE WoLgID=:lid and WoTokenCount>1\n ## AND :content LIKE '%' || :zws || WoTextLC || :zws || '%'\n ## \"\"\"\n ## )\n ## sql = sql.bindparams(lid=language.id, content=content, zws=zws)\n ## recs = self.session.execute(sql).all()\n ## return [r[0] for r in recs]\n\n def _find_all_terms_in_tokens(self, tokens, language, kwtree=None):\n \"\"\"\n Find all terms contained in the (ordered) parsed tokens tokens.\n\n For example\n - given tokens = \"Here\", \" \", \"is\", \" \", \"a\", \" \", \"cat\"\n - given terms in the db: [ \"cat\", \"a/ /cat\", \"dog\" ]\n\n This would return the terms \"cat\" and \"a/ /cat\".\n\n Method:\n - build list of lowercase text in the tokens\n - append all multword term strings that exist in the content\n - query for Terms that exist in the list\n\n Note: this method only uses indexes for multiword terms, as any\n content analyzed is first parsed into tokens before being passed\n to this routine. There's no need to search for single-word Terms\n in the tokenized strings, they can be found by a simple query.\n \"\"\"\n\n # Performance: About half of the time in this routine is spent in\n # Step 1 (finding multiword terms), the rest in step 2 (the actual\n # query).\n # dt = DebugTimer(\"_find_all_terms_in_tokens\", display=True)\n\n parser = language.parser\n text_lcs = [parser.get_lowercase(t.token) for t in tokens]\n\n # Step 1: get the multiwords in the content.\n if kwtree is None:\n mword_terms = self._find_all_multi_word_term_text_lcs_in_content(\n text_lcs, language\n )\n else:\n results = kwtree.search_all(text_lcs)\n mword_terms = [r[0] for r in results]\n # dt.step(\"filtered mword terms\")\n\n # Step 2: load the Term objects.\n #\n # The Term fetch is actually performant -- there is no\n # real difference between loading the Term objects versus\n # loading raw data with SQL and getting dicts.\n #\n # Code for getting raw data:\n # param_keys = [f\"w{i}\" for i, _ in enumerate(text_lcs)]\n # keys_placeholders = ','.join([f\":{k}\" for k in param_keys])\n # param_dict = dict(zip(param_keys, text_lcs))\n # param_dict[\"langid\"] = language.id\n # sql = sqltext(f\"\"\"SELECT WoID, WoTextLC FROM words\n # WHERE WoLgID=:langid and WoTextLC in ({keys_placeholders})\"\"\")\n # sql = sql.bindparams(language.id, *text_lcs)\n # results = self.session.execute(sql, param_dict).fetchall()\n text_lcs.extend(mword_terms)\n tok_strings = list(set(text_lcs))\n terms_matching_tokens_qry = self.session.query(Term).filter(\n Term.text_lc.in_(tok_strings), Term.language == language\n )\n all_terms = terms_matching_tokens_qry.all()\n # dt.step(\"exec query\")\n\n return all_terms\n\n def get_textitems(self, s, language, multiword_term_indexer=None):\n \"\"\"\n Get array of TextItems for the string s.\n\n The multiword_term_indexer is a big performance boost, but takes\n time to initialize.\n \"\"\"\n # Hacky reset of state of ParsedToken state.\n # _Shouldn't_ be needed but doesn't hurt, even if it's lame.\n ParsedToken.reset_counters()\n\n cleaned = re.sub(r\" +\", \" \", s)\n tokens = language.get_parsed_tokens(cleaned)\n terms = self._find_all_terms_in_tokens(tokens, language, multiword_term_indexer)\n textitems = calc_get_textitems(tokens, terms, language, multiword_term_indexer)\n return textitems\n\n def get_multiword_indexer(self, language):\n \"Return indexer loaded with all multiword terms.\"\n mw = MultiwordTermIndexer()\n for r in self._get_multiword_terms(language):\n mw.add(r[1])\n return mw\n\n def get_paragraphs(self, s, language):\n \"\"\"\n Get array of arrays of TextItems for the given string s.\n\n This doesn't use an indexer, as it should only be used\n for a single page of text!\n \"\"\"\n textitems = self.get_textitems(s, language)\n\n def _split_textitems_by_paragraph(textitems):\n \"Split by ¶\"\n ret = []\n curr_para = []\n for t in textitems:\n if t.text == \"¶\":\n ret.append(curr_para)\n curr_para = []\n else:\n curr_para.append(t)\n if len(curr_para) > 0:\n ret.append(curr_para)\n return ret\n\n def _split_by_sentence_number(p):\n sentences = [\n list(sentence)\n for _, sentence in itertools.groupby(p, key=lambda t: t.sentence_number)\n ]\n for s in sentences:\n s[0].add_html_class(\"sentencestart\")\n return sentences\n\n paras = [\n _split_by_sentence_number(list(sentences))\n for sentences in _split_textitems_by_paragraph(textitems)\n ]\n\n return paras\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 16389}, "tests/unit/backup/test_backup.py::103": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["Service", "db", "os"], "enclosing_function": "test_backup_writes_file_to_output_dir", "extracted_code": "# Source: lute/backup/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def create_backup(self, app_config, settings, is_manual=False, suffix=None):\n \"\"\"\n Create backup using current app config, settings.\n\n is_manual is True if this is a user-triggered manual\n backup, otherwise is False.\n\n suffix can be specified for test.\n\n settings are from BackupSettings.\n - backup_enabled\n - backup_dir\n - backup_auto\n - backup_warn\n - backup_count\n - last_backup_datetime\n \"\"\"\n if not os.path.exists(settings.backup_dir):\n raise BackupException(\"Missing directory \" + settings.backup_dir)\n\n # def _print_now(msg):\n # \"Timing helper for when implement audio backup.\"\n # now = datetime.now().strftime(\"%H-%M-%S\")\n # print(f\"{now} - {msg}\", flush=True)\n\n self._mirror_images_dir(app_config.userimagespath, settings.backup_dir)\n\n prefix = \"manual_\" if is_manual else \"\"\n if suffix is None:\n suffix = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n fname = f\"{prefix}lute_backup_{suffix}.db\"\n backupfile = os.path.join(settings.backup_dir, fname)\n\n f = self._create_db_backup(app_config.dbfilename, backupfile)\n self._remove_excess_backups(settings.backup_count, settings.backup_dir)\n return f\n\n def should_run_auto_backup(self, backup_settings):\n \"\"\"\n True (if applicable) if last backup was old.\n \"\"\"\n bs = backup_settings\n if bs.backup_enabled is False or bs.backup_auto is False:\n return False\n\n last = bs.last_backup_datetime\n if last is None:\n return True\n\n curr = int(time.time())\n diff = curr - last\n return diff > 24 * 60 * 60\n\n def backup_warning(self, backup_settings):\n \"Get warning if needed.\"\n if not backup_settings.backup_warn:\n return \"\"\n\n have_books = self.session.query(self.session.query(Book).exists()).scalar()\n have_terms = self.session.query(self.session.query(Term).exists()).scalar()\n if have_books is False and have_terms is False:\n return \"\"\n\n last = backup_settings.last_backup_datetime\n if last is None:\n return \"Never backed up.\"\n\n curr = int(time.time())\n diff = curr - last\n old_backup_msg = \"Last backup was more than 1 week ago.\"\n if diff > 7 * 24 * 60 * 60:\n return old_backup_msg\n\n return \"\"\n\n def _create_db_backup(self, dbfilename, backupfile):\n \"Make a backup.\"\n shutil.copy(dbfilename, backupfile)\n f = f\"{backupfile}.gz\"\n with open(backupfile, \"rb\") as in_file, gzip.open(\n f, \"wb\", compresslevel=4\n ) as out_file:\n shutil.copyfileobj(in_file, out_file)\n os.remove(backupfile)\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n return f\n\n def skip_this_backup(self):\n \"Set the last backup time to today.\"\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n\n def _remove_excess_backups(self, count, outdir):\n \"Remove old backups.\"\n files = [f for f in self.list_backups(outdir) if not f.is_manual]\n files.sort(reverse=True)\n to_remove = files[count:]\n for f in to_remove:\n os.remove(f.filepath)\n\n def _mirror_images_dir(self, userimagespath, outdir):\n \"Copy the images to backup.\"\n target_dir = os.path.join(outdir, \"userimages_backup\")\n target_dir = os.path.abspath(target_dir)\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n shutil.copytree(userimagespath, target_dir, dirs_exist_ok=True)\n\n def list_backups(self, outdir) -> List[DatabaseBackupFile]:\n \"List all backup files.\"\n return [\n DatabaseBackupFile(os.path.join(outdir, f))\n for f in os.listdir(outdir)\n if re.match(r\"(manual_)?lute_backup_\", f)\n ]\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 6395}, "tests/unit/read/render/test_get_string_indexes.py::61": {"resolved_imports": ["lute/read/render/calculate_textitems.py"], "used_names": ["get_string_indexes"], "enclosing_function": "test_get_string_indexes_scenario", "extracted_code": "# Source: lute/read/render/calculate_textitems.py\ndef get_string_indexes(strings, content):\n \"\"\"\n Returns list of arrays: [[string, index], ...]\n\n e.g., _get_string_indexes([\"is a\", \"cat\"], \"here is a cat\")\n returns [(\"is a\", 1), (\"cat\", 3)].\n\n strings and content must be lowercased!\n \"\"\"\n searchcontent = zws + content + zws\n zwsindexes = [index for index, letter in enumerate(searchcontent) if letter == zws]\n\n ret = []\n\n for s in strings:\n # \"(?=())\" is required because sometimes the search pattern can\n # overlap -- e.g. _b_b_ has _b_ *twice*.\n # https://stackoverflow.com/questions/5616822/\n # how-to-use-regex-to-find-all-overlapping-matches\n pattern = rf\"(?=({re.escape(zws + s + zws)}))\"\n add_matches = [\n (s, zwsindexes.index(m.start()))\n for m in re.finditer(pattern, searchcontent)\n ]\n ret.extend(add_matches)\n\n return ret", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 948}, "tests/unit/config/test_app_config.py::28": {"resolved_imports": ["lute/config/app_config.py"], "used_names": ["AppConfig"], "enclosing_function": "test_valid_config", "extracted_code": "# Source: lute/config/app_config.py\nclass AppConfig: # pylint: disable=too-many-instance-attributes\n \"\"\"\n Configuration wrapper around yaml file.\n\n Adds various properties for lint-time checking.\n \"\"\"\n\n def __init__(self, config_file_path):\n \"\"\"\n Load the required configuration file.\n \"\"\"\n self._load_config(config_file_path)\n\n def _load_config(self, config_file_path):\n \"\"\"\n Load and validate the config file.\n \"\"\"\n with open(config_file_path, \"r\", encoding=\"utf-8\") as cf:\n config = yaml.safe_load(cf)\n\n if not isinstance(config, dict):\n raise RuntimeError(\n f\"File at {config_file_path} is invalid or is not a yaml dictionary.\"\n )\n\n self.env = config.get(\"ENV\", None)\n if self.env not in [\"prod\", \"dev\"]:\n raise ValueError(f\"ENV must be prod or dev, was {self.env}.\")\n\n self.is_docker = bool(config.get(\"IS_DOCKER\", False))\n\n # Database name.\n self.dbname = config.get(\"DBNAME\", None)\n if self.dbname is None:\n raise ValueError(\"Config file must have 'DBNAME'\")\n\n # Various invoke tasks in /tasks.py check if the database is a\n # test_ db prior to running some destructive action.\n self.is_test_db = self.dbname.startswith(\"test_\")\n\n # Path to user data.\n self.datapath = config.get(\"DATAPATH\", self._get_appdata_dir())\n self.plugin_datapath = os.path.join(self.datapath, \"plugins\")\n self.userimagespath = os.path.join(self.datapath, \"userimages\")\n self.useraudiopath = os.path.join(self.datapath, \"useraudio\")\n self.userthemespath = os.path.join(self.datapath, \"userthemes\")\n self.temppath = os.path.join(self.datapath, \"temp\")\n self.dbfilename = os.path.join(self.datapath, self.dbname)\n\n # Path to db backup.\n # When Lute starts up, it backs up the db\n # if migrations are going to be applied, just in case.\n # Hidden directory as a hint to the the user that\n # this is a system dir.\n self.system_backup_path = os.path.join(self.datapath, \".system_db_backups\")\n\n # Default backup path for user, can be overridden in settings.\n self.default_user_backup_path = config.get(\n \"BACKUP_PATH\", os.path.join(self.datapath, \"backups\")\n )\n\n def _get_appdata_dir(self):\n \"Get user's appdata directory from platformdirs.\"\n dirs = PlatformDirs(\"Lute3\", \"Lute3\")\n return dirs.user_data_dir\n\n @property\n def sqliteconnstring(self):\n \"Full sqlite connection string.\"\n return f\"sqlite:///{self.dbfilename}\"\n\n @staticmethod\n def configdir():\n \"Return the path to the configuration file directory.\"\n return os.path.dirname(os.path.realpath(__file__))\n\n @staticmethod\n def default_config_filename():\n \"Return the path to the default configuration file.\"\n thisdir = AppConfig.configdir()\n return os.path.join(thisdir, \"config.yml\")", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 3053}, "tests/unit/parse/test_SpaceDelimitedParser.py::172": {"resolved_imports": ["lute/parse/space_delimited_parser.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_zero_width_joiner_retained", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/acceptance/conftest.py::542": {"resolved_imports": [], "used_names": ["parsers", "when"], "enclosing_function": "when_hover", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/orm/test_Book.py::40": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_save_book", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 47}, "tests/unit/db/test_data_cleanup.py::43": {"resolved_imports": ["lute/db/__init__.py", "lute/db/data_cleanup.py"], "used_names": ["assert_sql_result", "clean_data", "datetime", "db", "make_text"], "enclosing_function": "test_cleanup_loads_missing_sentence_textlc", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/db/data_cleanup.py\ndef clean_data(session, output_function):\n \"Clean all data as required, sending messages to output_function.\"\n _set_texts_word_count(session, output_function)\n _load_sentence_textlc(session, output_function)\n _update_term_images(session, output_function)", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 350}, "tests/unit/parse/test_JapaneseParser.py::95": {"resolved_imports": ["lute/parse/mecab_parser.py", "lute/models/term.py", "lute/settings/current.py", "lute/parse/base.py"], "used_names": ["JapaneseParser"], "enclosing_function": "test_readings", "extracted_code": "# Source: lute/parse/mecab_parser.py\nclass JapaneseParser(AbstractParser):\n \"\"\"\n Japanese parser.\n\n This is only supported if mecab is installed.\n\n The parser uses natto-py library, and so should\n be able to find mecab automatically; if it can't,\n you may need to set the MECAB_PATH env variable,\n managed by UserSettingRepository.set_value(\"mecab_path\", p)\n \"\"\"\n\n _is_supported = None\n _old_mecab_path = None\n\n @classmethod\n def is_supported(cls):\n \"\"\"\n True if a natto MeCab can be instantiated,\n otherwise false.\n \"\"\"\n\n mecab_path = current_settings.get(\"mecab_path\", \"\") or \"\"\n mecab_path = mecab_path.strip()\n path_unchanged = mecab_path == JapaneseParser._old_mecab_path\n if path_unchanged and JapaneseParser._is_supported is not None:\n return JapaneseParser._is_supported\n\n # Natto uses the MECAB_PATH env key if it's set.\n env_key = \"MECAB_PATH\"\n if mecab_path != \"\":\n os.environ[env_key] = mecab_path\n else:\n os.environ.pop(env_key, None)\n\n mecab_works = False\n\n # Calling MeCab() prints to stderr even if the\n # exception is caught. Suppress that output noise.\n temp_err = StringIO()\n try:\n sys.stderr = temp_err\n MeCab()\n mecab_works = True\n except: # pylint: disable=bare-except\n mecab_works = False\n finally:\n sys.stderr = sys.__stderr__\n\n JapaneseParser._old_mecab_path = mecab_path\n JapaneseParser._is_supported = mecab_works\n return mecab_works\n\n @classmethod\n def name(cls):\n return \"Japanese\"\n\n def get_parsed_tokens(self, text: str, language) -> List[ParsedToken]:\n \"Parse the string using MeCab.\"\n text = re.sub(r\"[ \\t]+\", \" \", text).strip()\n\n lines = []\n\n # If the string contains a \"\\n\", MeCab appears to silently\n # remove it. Splitting it works (ref test_JapaneseParser).\n # Flags: ref https://github.com/buruzaemon/natto-py:\n # -F = node format\n # -U = unknown format\n # -E = EOP format\n with MeCab(r\"-F %m\\t%t\\t%h\\n -U %m\\t%t\\t%h\\n -E EOP\\t3\\t7\\n\") as nm:\n for para in text.split(\"\\n\"):\n for n in nm.parse(para, as_nodes=True):\n lines.append(n.feature)\n\n lines = [\n n.strip().split(\"\\t\") for n in lines if n is not None and n.strip() != \"\"\n ]\n\n # Production bug: JP parsing with MeCab would sometimes return a line\n # \"0\\t4\" before an end-of-paragraph \"EOP\\t3\\t7\", reasons unknown. These\n # \"0\\t4\" tokens don't have any function, and cause problems in subsequent\n # steps of the processing in line_to_token(), so just remove them.\n lines = [n for n in lines if len(n) == 3]\n\n def line_to_token(lin):\n \"Convert parsed line to a ParsedToken.\"\n term, node_type, third = lin\n is_eos = term in language.regexp_split_sentences\n if term == \"EOP\" and third == \"7\":\n term = \"¶\"\n\n # Node type values ref\n # https://github.com/buruzaemon/natto-py/wiki/\n # Node-Parsing-char_type\n #\n # The repeat character is sometimes returned as a \"symbol\"\n # (node type = 3), so handle that specifically.\n is_word = node_type in \"2678\" or term == \"々\"\n return ParsedToken(term, is_word, is_eos or term == \"¶\")\n\n tokens = [line_to_token(lin) for lin in lines]\n return tokens\n\n # Hiragana is Unicode code block U+3040 - U+309F\n # ref https://stackoverflow.com/questions/72016049/\n # how-to-check-if-text-is-japanese-hiragana-in-python\n def _char_is_hiragana(self, c) -> bool:\n return \"\\u3040\" <= c <= \"\\u309F\"\n\n def _string_is_hiragana(self, s: str) -> bool:\n return all(self._char_is_hiragana(c) for c in s)\n\n def get_reading(self, text: str):\n \"\"\"\n Get the pronunciation for the given text.\n\n Returns None if the text is all hiragana, or the pronunciation\n doesn't add value (same as text).\n \"\"\"\n if self._string_is_hiragana(text):\n return None\n\n jp_reading_setting = current_settings.get(\"japanese_reading\", \"\").strip()\n if jp_reading_setting == \"\":\n # Don't set reading if nothing specified.\n return None\n\n flags = r\"-O yomi\"\n readings = []\n with MeCab(flags) as nm:\n for n in nm.parse(text, as_nodes=True):\n readings.append(n.feature)\n readings = [r.strip() for r in readings if r is not None and r.strip() != \"\"]\n\n ret = \"\".join(readings).strip()\n if ret in (\"\", text):\n return None\n\n if jp_reading_setting == \"katakana\":\n return ret\n if jp_reading_setting == \"hiragana\":\n return jaconv.kata2hira(ret)\n if jp_reading_setting == \"alphabet\":\n return jaconv.kata2alphabet(ret)\n raise RuntimeError(f\"Bad reading type {jp_reading_setting}\")", "n_imports_parsed": 4, "n_files_resolved": 4, "n_chars_extracted": 5155}, "tests/unit/ankiexport/test_criteria.py::53": {"resolved_imports": ["lute/ankiexport/criteria.py", "lute/ankiexport/exceptions.py"], "used_names": ["evaluate_criteria", "pytest"], "enclosing_function": "test_criteria", "extracted_code": "# Source: lute/ankiexport/criteria.py\ndef evaluate_criteria(s, term):\n \"Parse the criteria, return True or False for the given term.\"\n # pylint: disable=too-many-locals\n\n if (s or \"\").strip() == \"\":\n return True\n\n def has_any_matching_tags(tagvals):\n term_tags = [t.text for t in term.term_tags]\n return any(e in term_tags for e in tagvals)\n\n def has_any_matching_parent_tags(tagvals):\n ptags = []\n for p in term.parents:\n ptags.extend([t.text for t in p.term_tags])\n return any(e in ptags for e in tagvals)\n\n def has_any_matching_all_tags(tagvals):\n alltags = [t.text for t in term.term_tags]\n for p in term.parents:\n alltags.extend([t.text for t in p.term_tags])\n return any(e in alltags for e in tagvals)\n\n def matches_lang(lang):\n return term.language.name == lang[0]\n\n def check_has_images():\n \"True if term or any parent has image.\"\n pi = [p.get_current_image() is not None for p in term.parents]\n return term.get_current_image() is not None or any(pi)\n\n def check_has(args):\n \"Check has:x\"\n has_item = args[0]\n if has_item == \"image\":\n return check_has_images()\n raise RuntimeError(f\"Unhandled has check for {has_item}\")\n\n def get_binary_operator(opstring):\n \"Return lambda matching op.\"\n opMap = {\n \"<\": lambda a, b: a < b,\n \"<=\": lambda a, b: a <= b,\n \">\": lambda a, b: a > b,\n \">=\": lambda a, b: a >= b,\n \"!=\": lambda a, b: a != b,\n \"=\": lambda a, b: a == b,\n \"==\": lambda a, b: a == b,\n }\n return opMap[opstring]\n\n def check_parent_count(args):\n \"Check parents.\"\n opstring, val = args\n oplambda = get_binary_operator(opstring)\n pcount = len(term.parents)\n return oplambda(pcount, val)\n\n def check_status_val(args):\n \"Check status.\"\n opstring, val = args\n oplambda = get_binary_operator(opstring)\n return oplambda(term.status, val)\n\n ### class BoolNot:\n ### \"Not unary operator.\"\n ### def __init__(self, t):\n ### self.arg = t[0][1]\n ### def __bool__(self) -> bool:\n ### v = bool(self.arg)\n ### return not v\n ### def __str__(self) -> str:\n ### return \"~\" + str(self.arg)\n ### __repr__ = __str__\n\n class BoolBinOp:\n \"Binary operation.\"\n repr_symbol: str = \"\"\n eval_fn: Callable[[Iterable[bool]], bool] = lambda _: False\n\n def __init__(self, t):\n self.args = t[0][0::2]\n\n def __str__(self) -> str:\n sep = f\" {self.repr_symbol} \"\n return f\"({sep.join(map(str, self.args))})\"\n\n def __bool__(self) -> bool:\n return self.eval_fn(bool(a) for a in self.args)\n\n class BoolAnd(BoolBinOp):\n repr_symbol = \"&\"\n eval_fn = all\n\n class BoolOr(BoolBinOp):\n repr_symbol = \"|\"\n eval_fn = any\n\n quoteval = QuotedString(quoteChar='\"')\n quotedString.setParseAction(pp.removeQuotes)\n list_of_values = pp.delimitedList(quotedString)\n\n tagvallist = Suppress(\"[\") + list_of_values + Suppress(\"]\")\n tagcrit = tagvallist | quoteval\n\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n all_tag_matcher = Suppress(Literal(\"all.tags\") + Literal(\":\")) + tagcrit\n\n lang_matcher = Suppress(\"language\") + Suppress(\":\") + quoteval\n\n has_options = Literal(\"image\")\n has_matcher = Suppress(\"has\") + Suppress(\":\") + has_options\n\n comparison_op = one_of(\"< <= > >= != = == <>\")\n integer = Word(nums).setParseAction(lambda x: int(x[0]))\n\n parent_count_matcher = (\n Suppress(\"parents\")\n + Suppress(\".\")\n + Suppress(\"count\")\n + comparison_op\n + integer\n )\n\n status_matcher = Suppress(\"status\") + comparison_op + integer\n\n and_keyword = Keyword(\"and\")\n or_keyword = Keyword(\"or\")\n\n multi_check = infixNotation(\n tag_matcher.set_parse_action(has_any_matching_tags)\n | parents_tag_matcher.set_parse_action(has_any_matching_parent_tags)\n | all_tag_matcher.set_parse_action(has_any_matching_all_tags)\n | lang_matcher.set_parse_action(matches_lang)\n | has_matcher.set_parse_action(check_has)\n | parent_count_matcher.set_parse_action(check_parent_count)\n | status_matcher.set_parse_action(check_status_val),\n [\n (and_keyword, 2, opAssoc.LEFT, BoolAnd),\n (or_keyword, 2, opAssoc.LEFT, BoolOr),\n ],\n )\n\n try:\n result = multi_check.parseString(s, parseAll=True)\n return bool(result[0])\n except pp.ParseException as ex:\n msg = f\"Criteria syntax error at position {ex.loc} or later: {ex.line}\"\n raise AnkiExportConfigurationError(msg) from ex", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4969}, "tests/unit/language/test_service.py::56": {"resolved_imports": ["lute/language/service.py", "lute/db/__init__.py", "lute/utils/debug_helpers.py"], "used_names": ["Service", "db"], "enclosing_function": "test_get_language_def", "extracted_code": "# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2195}, "tests/features/test_term_import.py::95": {"resolved_imports": ["lute/db/__init__.py", "lute/models/language.py", "lute/language/service.py", "lute/models/term.py", "lute/models/repositories.py", "lute/termimport/service.py"], "used_names": ["parsers", "then"], "enclosing_function": "succeed_with_status", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/unit/backup/test_backup.py::168": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["Service", "db"], "enclosing_function": "test_autobackup_returns_true_if_never_backed_up", "extracted_code": "# Source: lute/backup/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def create_backup(self, app_config, settings, is_manual=False, suffix=None):\n \"\"\"\n Create backup using current app config, settings.\n\n is_manual is True if this is a user-triggered manual\n backup, otherwise is False.\n\n suffix can be specified for test.\n\n settings are from BackupSettings.\n - backup_enabled\n - backup_dir\n - backup_auto\n - backup_warn\n - backup_count\n - last_backup_datetime\n \"\"\"\n if not os.path.exists(settings.backup_dir):\n raise BackupException(\"Missing directory \" + settings.backup_dir)\n\n # def _print_now(msg):\n # \"Timing helper for when implement audio backup.\"\n # now = datetime.now().strftime(\"%H-%M-%S\")\n # print(f\"{now} - {msg}\", flush=True)\n\n self._mirror_images_dir(app_config.userimagespath, settings.backup_dir)\n\n prefix = \"manual_\" if is_manual else \"\"\n if suffix is None:\n suffix = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n fname = f\"{prefix}lute_backup_{suffix}.db\"\n backupfile = os.path.join(settings.backup_dir, fname)\n\n f = self._create_db_backup(app_config.dbfilename, backupfile)\n self._remove_excess_backups(settings.backup_count, settings.backup_dir)\n return f\n\n def should_run_auto_backup(self, backup_settings):\n \"\"\"\n True (if applicable) if last backup was old.\n \"\"\"\n bs = backup_settings\n if bs.backup_enabled is False or bs.backup_auto is False:\n return False\n\n last = bs.last_backup_datetime\n if last is None:\n return True\n\n curr = int(time.time())\n diff = curr - last\n return diff > 24 * 60 * 60\n\n def backup_warning(self, backup_settings):\n \"Get warning if needed.\"\n if not backup_settings.backup_warn:\n return \"\"\n\n have_books = self.session.query(self.session.query(Book).exists()).scalar()\n have_terms = self.session.query(self.session.query(Term).exists()).scalar()\n if have_books is False and have_terms is False:\n return \"\"\n\n last = backup_settings.last_backup_datetime\n if last is None:\n return \"Never backed up.\"\n\n curr = int(time.time())\n diff = curr - last\n old_backup_msg = \"Last backup was more than 1 week ago.\"\n if diff > 7 * 24 * 60 * 60:\n return old_backup_msg\n\n return \"\"\n\n def _create_db_backup(self, dbfilename, backupfile):\n \"Make a backup.\"\n shutil.copy(dbfilename, backupfile)\n f = f\"{backupfile}.gz\"\n with open(backupfile, \"rb\") as in_file, gzip.open(\n f, \"wb\", compresslevel=4\n ) as out_file:\n shutil.copyfileobj(in_file, out_file)\n os.remove(backupfile)\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n return f\n\n def skip_this_backup(self):\n \"Set the last backup time to today.\"\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n\n def _remove_excess_backups(self, count, outdir):\n \"Remove old backups.\"\n files = [f for f in self.list_backups(outdir) if not f.is_manual]\n files.sort(reverse=True)\n to_remove = files[count:]\n for f in to_remove:\n os.remove(f.filepath)\n\n def _mirror_images_dir(self, userimagespath, outdir):\n \"Copy the images to backup.\"\n target_dir = os.path.join(outdir, \"userimages_backup\")\n target_dir = os.path.abspath(target_dir)\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n shutil.copytree(userimagespath, target_dir, dirs_exist_ok=True)\n\n def list_backups(self, outdir) -> List[DatabaseBackupFile]:\n \"List all backup files.\"\n return [\n DatabaseBackupFile(os.path.join(outdir, f))\n for f in os.listdir(outdir)\n if re.match(r\"(manual_)?lute_backup_\", f)\n ]\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 6395}, "plugins/lute-khmer/tests/test_KhmerParser.py::18": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_dummy_test", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "plugins/lute-khmer/tests/test_KhmerParser.py::36": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["Term"], "enclosing_function": "test_token_count", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7421}, "tests/unit/models/test_Setting.py::77": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["db"], "enclosing_function": "test_get_backup_settings", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/unit/db/setup/test_SqliteMigrator.py::53": {"resolved_imports": ["lute/db/setup/migrator.py"], "used_names": ["SqliteMigrator"], "enclosing_function": "test_no_migrations", "extracted_code": "# Source: lute/db/setup/migrator.py\nclass SqliteMigrator:\n \"\"\"\n Sqlite migrator class.\n\n Follows the principles documented in\n https://github.com/jzohrab/DbMigrator/blob/master/docs/managing_database_changes.md\n \"\"\"\n\n def __init__(self, location, repeatable):\n self.location = location\n self.repeatable = repeatable\n\n def has_migrations(self, conn):\n \"\"\"\n Return True if have non-applied migrations.\n \"\"\"\n outstanding = self._get_pending(conn)\n return len(outstanding) > 0\n\n def _get_pending(self, conn):\n \"\"\"\n Get all non-applied (one-time) migrations.\n \"\"\"\n allfiles = []\n with _change_directory(self.location):\n allfiles = [\n os.path.join(self.location, s)\n for s in os.listdir()\n if s.endswith(\".sql\")\n ]\n allfiles.sort()\n outstanding = [f for f in allfiles if self._should_apply(conn, f)]\n return outstanding\n\n def do_migration(self, conn):\n \"\"\"\n Run all migrations, then all repeatable migrations.\n \"\"\"\n self._process_folder(conn)\n self._process_repeatable(conn)\n\n def _process_folder(self, conn):\n \"\"\"\n Run all pending migrations. Write executed script to\n _migrations table.\n \"\"\"\n outstanding = self._get_pending(conn)\n for f in outstanding:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n self._add_migration_to_database(conn, f)\n\n def _process_repeatable(self, conn):\n \"\"\"\n Run all repeatable migrations.\n \"\"\"\n with _change_directory(self.repeatable):\n files = [\n os.path.join(self.repeatable, f)\n for f in os.listdir()\n if f.endswith(\".sql\")\n ]\n for f in files:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n\n def _should_apply(self, conn, filename):\n \"\"\"\n True if a migration hasn't been run yet.\n\n The file basename (no directory) is stored in the migration table.\n \"\"\"\n f = os.path.basename(filename)\n sql = f\"select count(filename) from _migrations where filename = '{f}'\"\n res = conn.execute(sql).fetchone()\n return res[0] == 0\n\n def _add_migration_to_database(self, conn, filename):\n \"\"\"\n Track the executed migration in _migrations.\n \"\"\"\n f = os.path.basename(filename)\n conn.execute(\"begin transaction\")\n conn.execute(f\"INSERT INTO _migrations values ('{f}')\")\n conn.execute(\"commit transaction\")\n\n def _process_file(self, conn, f):\n \"\"\"\n Run the given file.\n \"\"\"\n with open(f, \"r\", encoding=\"utf8\") as sql_file:\n commands = sql_file.read()\n self._exec_commands(conn, commands)\n\n def _exec_commands(self, conn, sql):\n \"\"\"\n Execute all commands in the given file.\n \"\"\"\n conn.executescript(sql)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3329}, "tests/unit/parse/test_SpaceDelimitedParser.py::141": {"resolved_imports": ["lute/parse/space_delimited_parser.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_quick_checks", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "plugins/_template_/tests/test_LangNameParser.py::106": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["LangNameParser"], "enclosing_function": "todo_test_readings", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/models/test_Book_add_remove_pages.py::68": {"resolved_imports": ["lute/db/__init__.py"], "used_names": ["db", "make_book"], "enclosing_function": "test_add_page_before_first", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 47}, "tests/unit/term/test_Term_status_follow.py::108": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["db"], "enclosing_function": "test_parent_status_propagates_down", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/unit/themes/test_service.py::56": {"resolved_imports": ["lute/themes/service.py", "lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["Service", "UserSettingRepository", "db"], "enclosing_function": "test_next_theme_cycles_themes", "extracted_code": "# Source: lute/themes/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _css_path(self):\n \"\"\"\n Path to css in this folder.\n \"\"\"\n thisdir = os.path.dirname(__file__)\n theme_dir = os.path.join(thisdir, \"css\")\n return os.path.abspath(theme_dir)\n\n def list_themes(self):\n \"\"\"\n List of theme file names and user-readable name.\n \"\"\"\n\n def _make_display_name(s):\n ret = os.path.basename(s)\n ret = ret.replace(\".css\", \"\").replace(\"_\", \" \")\n return ret\n\n g = glob(os.path.join(self._css_path(), \"*.css\"))\n themes = [(os.path.basename(f), _make_display_name(f)) for f in g]\n theme_basenames = [t[0] for t in themes]\n\n g = glob(os.path.join(current_app.env_config.userthemespath, \"*.css\"))\n additional_user_themes = [\n (os.path.basename(f), _make_display_name(f))\n for f in g\n if os.path.basename(f) not in theme_basenames\n ]\n\n themes += additional_user_themes\n sorted_themes = sorted(themes, key=lambda x: x[1])\n return [default_entry] + sorted_themes\n\n def get_current_css(self):\n \"\"\"\n Return the current css pointed at by the current_theme user setting.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n if current_theme == default_entry[0]:\n return \"\"\n\n def _get_theme_css_in_dir(d):\n \"Get css, or '' if no file.\"\n fname = os.path.join(d, current_theme)\n if not os.path.exists(fname):\n return \"\"\n with open(fname, \"r\", encoding=\"utf-8\") as f:\n return f.read()\n\n ret = _get_theme_css_in_dir(self._css_path())\n add = _get_theme_css_in_dir(current_app.env_config.userthemespath)\n if add != \"\":\n ret += f\"\\n\\n/* Additional user css */\\n\\n{add}\"\n return ret\n\n def next_theme(self):\n \"\"\"\n Move to the next theme in the list of themes.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n themes = [t[0] for t in self.list_themes()]\n themes.append(default_entry[0])\n for i in range(0, len(themes)): # pylint: disable=consider-using-enumerate\n if themes[i] == current_theme:\n new_index = i + 1\n break\n repo.set_value(\"current_theme\", themes[new_index])\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/repositories.py\nclass UserSettingRepository(SettingRepositoryBase):\n \"Repository.\"\n\n def __init__(self, session):\n super().__init__(session, UserSetting)\n\n def key_exists_precheck(self, keyname):\n \"\"\"\n User keys must exist.\n \"\"\"\n if not self.key_exists(keyname):\n raise MissingUserSettingKeyException(keyname)\n\n def get_backup_settings(self):\n \"Convenience method.\"\n bs = BackupSettings()\n\n def _bool(v):\n return v in (1, \"1\", \"y\", True)\n\n bs.backup_enabled = _bool(self.get_value(\"backup_enabled\"))\n bs.backup_auto = _bool(self.get_value(\"backup_auto\"))\n bs.backup_warn = _bool(self.get_value(\"backup_warn\"))\n bs.backup_dir = self.get_value(\"backup_dir\")\n bs.backup_count = int(self.get_value(\"backup_count\") or 5)\n bs.last_backup_datetime = self.get_last_backup_datetime()\n return bs\n\n def get_last_backup_datetime(self):\n \"Get the last_backup_datetime as int, or None.\"\n v = self.get_value(\"lastbackup\")\n if v is None:\n return None\n return int(v)\n\n def set_last_backup_datetime(self, v):\n \"Set and save the last backup time.\"\n self.set_value(\"lastbackup\", v)\n self.session.commit()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3977}, "tests/unit/ankiexport/test_field_mapping.py::129": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "get_values_and_media_mapping"], "enclosing_function": "test_tag_replacements", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\ndef get_values_and_media_mapping(term, sentence_lookup, mapping):\n \"\"\"\n Get the value replacements to be put in the mapping, and build\n dict of new filenames to original filenames.\n \"\"\"\n\n def all_translations():\n ret = [term.translation or \"\"]\n for p in term.parents:\n if p.translation not in ret:\n ret.append(p.translation or \"\")\n return [r for r in ret if r.strip() != \"\"]\n\n def parse_keys_needing_calculation(calculate_keys, media_mappings):\n \"\"\"\n Build a parser for some keys in the mapping string, return\n calculated value to use in the mapping. SIDE EFFECT:\n adds ankiconnect post actions to post_actions if needed\n (e.g. for image uploads).\n\n e.g. the mapping \"article: { tags:[\"der\", \"die\", \"das\"] }\"\n needs to be parsed to extract certain tags from the current\n term.\n \"\"\"\n\n def _filtered_tags_in_term_list(term_list, tagvals):\n \"Get all unique tags.\"\n # tagvals is a pyparsing ParseResults, use list() to convert to strings.\n ttext = [tt.text for t in term_list for tt in t.term_tags]\n ttext = sorted(list(set(ttext)))\n ftags = [tt for tt in ttext if tt in list(tagvals)]\n return \", \".join(ftags)\n\n def get_filtered_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list([term], tagvals)\n\n def get_filtered_parents_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list(term.parents, tagvals)\n\n def handle_image(_):\n id_images = [\n (t, t.get_current_image())\n for t in _all_terms(term)\n if t.get_current_image() is not None\n ]\n image_srcs = []\n for t, imgfilename in id_images:\n new_filename = f\"LUTE_TERM_{t.id}.jpg\"\n image_url = f\"/userimages/{t.language.id}/{imgfilename}\"\n media_mappings[new_filename] = image_url\n image_srcs.append(f'')\n\n return \"\".join(image_srcs)\n\n def handle_sentences(_):\n \"Get sample sentence for term.\"\n if term.id is None:\n # Dummy parse.\n return \"\"\n return sentence_lookup.get_sentence_for_term(term.id)\n\n quotedString.setParseAction(pp.removeQuotes)\n tagvallist = Suppress(\"[\") + pp.delimitedList(quotedString) + Suppress(\"]\")\n tagcrit = tagvallist | QuotedString(quoteChar='\"')\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n\n image = Suppress(\"image\")\n sentence = Suppress(\"sentence\")\n\n matcher = (\n tag_matcher.set_parse_action(get_filtered_tags)\n | parents_tag_matcher.set_parse_action(get_filtered_parents_tags)\n | image.set_parse_action(handle_image)\n | sentence.set_parse_action(handle_sentences)\n )\n\n calc_replacements = {\n # Matchers return the value that should be used as the\n # replacement value for the given mapping string. e.g.\n # tags[\"der\", \"die\"] returns \"der\" if term.tags = [\"der\", \"x\"]\n k: matcher.parseString(k).asList()[0]\n for k in calculate_keys\n }\n\n return calc_replacements\n\n def remove_zws(replacements_dict):\n cleaned = {}\n for key, value in replacements_dict.items():\n if isinstance(value, str):\n cleaned[key] = value.replace(\"\\u200B\", \"\")\n else:\n cleaned[key] = value\n return cleaned\n\n # One-for-one replacements in the mapping string.\n # e.g. \"{ id }\" is replaced by term.termid.\n replacements = {\n \"id\": term.id,\n \"term\": term.text,\n \"language\": term.language.name,\n \"parents\": \", \".join([p.text for p in term.parents]),\n \"tags\": \", \".join(sorted({tt.text for tt in term.term_tags})),\n \"translation\": \"
\".join(all_translations()),\n \"pronunciation\": term.romanization,\n \"parents.pronunciation\": \", \".join(\n [p.romanization or \"\" for p in term.parents]\n ),\n }\n\n mapping_string = \"; \".join(mapping.values())\n calc_keys = [\n k\n for k in set(re.findall(r\"{\\s*(.*?)\\s*}\", mapping_string))\n if k not in replacements\n ]\n\n media_mappings = {}\n calc_replacements = parse_keys_needing_calculation(calc_keys, media_mappings)\n\n final_replacements = {**replacements, **calc_replacements}\n cleaned = remove_zws(final_replacements)\n return (cleaned, media_mappings)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4848}, "tests/unit/db/setup/test_Setup.py::229": {"resolved_imports": ["lute/db/setup/main.py", "lute/db/setup/migrator.py"], "used_names": ["BackupManager", "Setup", "closing", "gzip", "os", "sqlite3"], "enclosing_function": "test_existing_database_with_migrations", "extracted_code": "# Source: lute/db/setup/main.py\nclass BackupManager: # pylint: disable=too-few-public-methods\n \"\"\"\n Creates db backups when needed, prunes old backups.\n \"\"\"\n\n def __init__(self, file_to_backup, backup_directory, max_number_of_backups):\n self.file_to_backup = file_to_backup\n self.backup_directory = backup_directory\n self.max_number_of_backups = max_number_of_backups\n\n def do_backup(self, next_backup_datetime=None):\n \"\"\"\n Perform the db file backup to backup_dir,\n pruning old backups.\n \"\"\"\n\n if next_backup_datetime is None:\n now = datetime.now()\n next_backup_datetime = now.strftime(\"%Y%m%d-%H%M%S-%f\")\n\n bname = os.path.basename(self.file_to_backup)\n backup_filename = f\"{bname}.{next_backup_datetime}.gz\"\n backup_path = os.path.join(self.backup_directory, backup_filename)\n\n os.makedirs(self.backup_directory, exist_ok=True)\n\n # Copy the file to the backup directory and gzip it\n with open(self.file_to_backup, \"rb\") as source_file, gzip.open(\n backup_path, \"wb\"\n ) as backup_file:\n shutil.copyfileobj(source_file, backup_file)\n assert os.path.exists(backup_path)\n\n # List all backup files in the directory, sorted by name.\n # Since this includes the timestamp, the oldest files will be\n # listed first.\n globname = f\"{bname}.*.gz\"\n globpath = os.path.join(self.backup_directory, globname)\n backup_files = glob.glob(globpath)\n backup_files.sort(key=os.path.basename)\n\n # Delete excess backup files if necessary\n while len(backup_files) > self.max_number_of_backups:\n file_to_delete = backup_files.pop(0)\n os.remove(file_to_delete)\n\nclass Setup: # pylint: disable=too-few-public-methods\n \"\"\"\n Main setup class, coordinates other classes.\n \"\"\"\n\n def __init__( # pylint: disable=too-many-arguments,too-many-positional-arguments\n self,\n db_filename: str,\n baseline_schema_file: str,\n backup_manager: BackupManager,\n migrator: SqliteMigrator,\n output_func=None,\n ):\n self._db_filename = db_filename\n self._baseline_schema_file = baseline_schema_file\n self._backup_mgr = backup_manager\n self._migrator = migrator\n self._output_func = output_func\n\n def setup(self):\n \"\"\"\n Do database setup, making backup if necessary, running migrations.\n \"\"\"\n new_db = False\n has_migrations = False\n\n if not os.path.exists(self._db_filename):\n new_db = True\n # Note openin a connection creates a db file,\n # so this has to be done after the existence\n # check.\n with closing(self._open_connection()) as conn:\n self._create_baseline(conn)\n\n with closing(self._open_connection()) as conn:\n has_migrations = self._migrator.has_migrations(conn)\n\n # Don't do a backup with an open connection ...\n # I don't _think_ it matters, but better to be safe.\n def null_print(s): # pylint: disable=unused-argument\n pass\n\n outfunc = self._output_func or null_print\n if not new_db and has_migrations:\n outfunc(\"Creating backup before running migrations ...\")\n self._backup_mgr.do_backup()\n outfunc(\"Done backup.\")\n\n with closing(self._open_connection()) as conn:\n self._migrator.do_migration(conn)\n\n def _open_connection(self):\n \"\"\"\n Get connection to db_filename. Callers must close.\n \"\"\"\n return sqlite3.connect(self._db_filename, detect_types=sqlite3.PARSE_DECLTYPES)\n\n def _create_baseline(self, conn):\n \"\"\"\n Create baseline database.\n \"\"\"\n b = self._baseline_schema_file\n with open(b, \"r\", encoding=\"utf8\") as f:\n sql = f.read()\n conn.executescript(sql)", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 3995}, "tests/unit/db/setup/test_Setup.py::212": {"resolved_imports": ["lute/db/setup/main.py", "lute/db/setup/migrator.py"], "used_names": ["closing", "sqlite3"], "enclosing_function": "assert_tables", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/parse/test_JapaneseParser.py::17": {"resolved_imports": ["lute/parse/mecab_parser.py", "lute/models/term.py", "lute/settings/current.py", "lute/parse/base.py"], "used_names": ["Term"], "enclosing_function": "test_token_count", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 4, "n_files_resolved": 4, "n_chars_extracted": 7421}, "tests/orm/test_Language.py::122": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["LanguageDictionary", "add_terms", "assert_record_count_equals", "assert_sql_result", "db", "make_text"], "enclosing_function": "test_delete_language_removes_book_and_terms", "extracted_code": "# Source: lute/models/language.py\nclass LanguageDictionary(db.Model):\n \"\"\"\n Language dictionary.\n \"\"\"\n\n __tablename__ = \"languagedicts\"\n\n id = db.Column(\"LdID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\n \"LdLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n language = db.relationship(\"Language\", back_populates=\"dictionaries\")\n usefor = db.Column(\"LdUseFor\", db.String(20), nullable=False)\n dicttype = db.Column(\"LdType\", db.String(20), nullable=False)\n dicturi = db.Column(\"LdDictURI\", db.String(200), nullable=False)\n is_active = db.Column(\"LdIsActive\", db.Boolean, default=True)\n sort_order = db.Column(\"LdSortOrder\", db.SmallInteger, nullable=False)\n\n # HACK: pre-pend '*' to URLs that need to open a new window.\n # This is a relic of the original code, and should be changed.\n # TODO remove-asterisk-hack: remove * from URL start.\n def make_uri(self):\n \"Hack add asterisk.\"\n prepend = \"*\" if self.dicttype == \"popuphtml\" else \"\"\n return f\"{prepend}{self.dicturi}\"\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 1137}, "tests/unit/models/test_Book_add_remove_pages.py::55": {"resolved_imports": ["lute/db/__init__.py"], "used_names": ["assert_sql_result", "db", "make_book"], "enclosing_function": "test_can_add_page", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 47}, "tests/unit/language/test_service.py::16": {"resolved_imports": ["lute/language/service.py", "lute/db/__init__.py", "lute/utils/debug_helpers.py"], "used_names": ["Service", "db"], "enclosing_function": "test_get_all_lang_defs", "extracted_code": "# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2195}, "tests/unit/parse/test_SpaceDelimitedParser.py::44": {"resolved_imports": ["lute/parse/space_delimited_parser.py", "lute/parse/base.py"], "used_names": ["SpaceDelimitedParser"], "enclosing_function": "assert_string_equals", "extracted_code": "# Source: lute/parse/space_delimited_parser.py\nclass SpaceDelimitedParser(AbstractParser):\n \"\"\"\n A general parser for space-delimited languages,\n such as English, French, Spanish ... etc.\n \"\"\"\n\n @classmethod\n def name(cls):\n return \"Space Delimited\"\n\n @staticmethod\n @functools.lru_cache\n def compile_re_pattern(pattern: str, *args, **kwargs) -> re.Pattern:\n \"\"\"Compile regular expression pattern, cache result for fast re-use.\"\"\"\n return re.compile(pattern, *args, **kwargs)\n\n @staticmethod\n @functools.lru_cache\n def get_default_word_characters() -> str:\n \"\"\"Return default value for lang.word_characters.\"\"\"\n\n # Unicode categories reference: https://www.compart.com/en/unicode/category\n categories = set([\"Cf\", \"Ll\", \"Lm\", \"Lo\", \"Lt\", \"Lu\", \"Mc\", \"Mn\", \"Sk\"])\n\n # There are more than 130,000 characters across all these categories.\n # Expressing this a single character at a time, mostly using unicode\n # escape sequences like \\u1234 or \\U12345678, would require 1 megabyte.\n # Converting to ranges like \\u1234-\\u1256 requires only 10K.\n ranges = []\n current = None\n\n def add_current_to_ranges():\n def ucode(n):\n \"Unicode point for integer.\"\n fstring = r\"\\u{:04x}\" if n < 0x10000 else r\"\\U{:08x}\"\n return (fstring).format(n)\n\n start_code = ucode(current[0])\n if current[0] == current[1]:\n range_string = start_code\n else:\n endcode = ucode(current[1])\n range_string = f\"{start_code}-{endcode}\"\n ranges.append(range_string)\n\n for i in range(1, sys.maxunicode):\n if unicodedata.category(chr(i)) not in categories:\n if current is not None:\n add_current_to_ranges()\n current = None\n elif current is None:\n # Starting a new range.\n current = [i, i]\n else:\n # Extending existing range.\n current[1] = i\n\n if current is not None:\n add_current_to_ranges()\n\n return \"\".join(ranges)\n\n @staticmethod\n @functools.lru_cache\n def get_default_regexp_split_sentences() -> str:\n \"\"\"Return default value for lang.regexp_split_sentences.\"\"\"\n\n # Construct pattern from Unicode ATerm and STerm categories.\n # See: https://www.unicode.org/Public/UNIDATA/auxiliary/SentenceBreakProperty.txt\n # and: https://unicode.org/reports/tr29/\n\n # Also include colon, since that is used to separate speakers\n # and their dialog, and is a reasonable dividing point for\n # sentence translations.\n\n return \"\".join(\n [\n re.escape(\".!?:\"),\n # ATerm entries (other than \".\", covered above):\n r\"\\u2024\\uFE52\\uFF0E\",\n # STerm entries (other than \"!\" and \"?\", covered above):\n r\"\\u0589\",\n r\"\\u061D-\\u061F\\u06D4\",\n r\"\\u0700-\\u0702\",\n r\"\\u07F9\",\n r\"\\u0837\\u0839\\u083D\\u083E\",\n r\"\\u0964\\u0965\",\n r\"\\u104A\\u104B\",\n r\"\\u1362\\u1367\\u1368\",\n r\"\\u166E\",\n r\"\\u1735\\u1736\",\n r\"\\u17D4\\u17D5\",\n r\"\\u1803\\u1809\",\n r\"\\u1944\\u1945\",\n r\"\\u1AA8-\\u1AAB\",\n r\"\\u1B5A\\u1B5B\\u1B5E\\u1B5F\\u1B7D\\u1B7E\",\n r\"\\u1C3B\\u1C3C\",\n r\"\\u1C7E\\u1C7F\",\n r\"\\u203C\\u203D\\u2047-\\u2049\\u2E2E\\u2E3C\\u2E53\\u2E54\\u3002\",\n r\"\\uA4FF\",\n r\"\\uA60E\\uA60F\",\n r\"\\uA6F3\\uA6F7\",\n r\"\\uA876\\uA877\",\n r\"\\uA8CE\\uA8CF\",\n r\"\\uA92F\",\n r\"\\uA9C8\\uA9C9\",\n r\"\\uAA5D\\uAA5F\",\n r\"\\uAAF0\\uAAF1\\uABEB\",\n r\"\\uFE56\\uFE57\\uFF01\\uFF1F\\uFF61\",\n r\"\\U00010A56\\U00010A57\",\n r\"\\U00010F55-\\U00010F59\",\n r\"\\U00010F86-\\U00010F89\",\n r\"\\U00011047\\U00011048\",\n r\"\\U000110BE-\\U000110C1\",\n r\"\\U00011141-\\U00011143\",\n r\"\\U000111C5\\U000111C6\\U000111CD\\U000111DE\\U000111DF\",\n r\"\\U00011238\\U00011239\\U0001123B\\U0001123C\",\n r\"\\U000112A9\",\n r\"\\U0001144B\\U0001144C\",\n r\"\\U000115C2\\U000115C3\\U000115C9-\\U000115D7\",\n r\"\\U00011641\\U00011642\",\n r\"\\U0001173C-\\U0001173E\",\n r\"\\U00011944\\u00011946\",\n r\"\\U00011A42\\U00011A43\",\n r\"\\U00011A9B\\U00011A9C\",\n r\"\\U00011C41\\U00011C42\",\n r\"\\U00011EF7\\U00011EF8\",\n r\"\\U00011F43\\U00011F44\",\n r\"\\U00016A6E\\U00016A6F\",\n r\"\\U00016AF5\",\n r\"\\U00016B37\\U00016B38\\U00016B44\",\n r\"\\U00016E98\",\n r\"\\U0001BC9F\",\n r\"\\U0001DA88\",\n ]\n )\n\n def get_parsed_tokens(self, text: str, language) -> List[ParsedToken]:\n \"Return parsed tokens.\"\n\n # Remove extra spaces.\n clean_text = re.sub(r\" +\", \" \", text)\n\n # Remove zero-width spaces.\n clean_text = clean_text.replace(chr(0x200B), \"\")\n\n return self._parse_to_tokens(clean_text, language)\n\n def preg_match_capture(self, pattern, subject):\n \"\"\"\n Return the matched text and their start positions in the subject.\n\n E.g. search for r'cat' in \"there is a CAT and a Cat\" returns:\n [['CAT', 11], ['Cat', 21]]\n \"\"\"\n compiled = SpaceDelimitedParser.compile_re_pattern(pattern, flags=re.IGNORECASE)\n matches = compiled.finditer(subject)\n result = [[match.group(), match.start()] for match in matches]\n return result\n\n def _parse_to_tokens(self, text: str, lang):\n \"\"\"\n Returns ParsedToken array for given language.\n \"\"\"\n replacements = lang.character_substitutions.split(\"|\")\n for replacement in replacements:\n fromto = replacement.strip().split(\"=\")\n if len(fromto) >= 2:\n rfrom = fromto[0].strip()\n rto = fromto[1].strip()\n text = text.replace(rfrom, rto)\n\n text = text.replace(\"\\r\\n\", \"\\n\")\n text = text.replace(\"{\", \"[\")\n text = text.replace(\"}\", \"]\")\n\n tokens = []\n paras = text.split(\"\\n\")\n pcount = len(paras)\n for i, para in enumerate(paras):\n self.parse_para(para, lang, tokens)\n if i != (pcount - 1):\n tokens.append(ParsedToken(\"¶\", False, True))\n\n return tokens\n\n def parse_para(self, text: str, lang, tokens: List[ParsedToken]):\n \"\"\"\n Parse a string, appending the tokens to the list of tokens.\n \"\"\"\n termchar = lang.word_characters.strip()\n if not termchar:\n termchar = SpaceDelimitedParser.get_default_word_characters()\n\n splitex = lang.exceptions_split_sentences.replace(\".\", \"\\\\.\")\n pattern = rf\"({splitex}|[{termchar}]*)\"\n if splitex.strip() == \"\":\n pattern = rf\"([{termchar}]*)\"\n\n m = self.preg_match_capture(pattern, text)\n wordtoks = list(filter(lambda t: t[0] != \"\", m))\n\n def add_non_words(s):\n \"\"\"\n Add non-word token s to the list of tokens. If s\n matches any of the split_sentence values, mark it as an\n end-of-sentence.\n \"\"\"\n if not s:\n return\n splitchar = lang.regexp_split_sentences.strip()\n if not splitchar:\n splitchar = SpaceDelimitedParser.get_default_regexp_split_sentences()\n pattern = f\"[{re.escape(splitchar)}]\"\n has_eos = False\n if pattern != \"[]\": # Should never happen, but ...\n allmatches = self.preg_match_capture(pattern, s)\n has_eos = len(allmatches) > 0\n tokens.append(ParsedToken(s, False, has_eos))\n\n # For each wordtok, add all non-words before the wordtok, and\n # then add the wordtok.\n pos = 0\n for wt in wordtoks:\n w = wt[0]\n wp = wt[1]\n s = text[pos:wp]\n add_non_words(s)\n tokens.append(ParsedToken(w, True, False))\n pos = wp + len(w)\n\n # Add anything left over.\n s = text[pos:]\n add_non_words(s)", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 8581}, "tests/unit/models/test_Book_add_remove_pages.py::26": {"resolved_imports": ["lute/db/__init__.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "assert_add", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 47}, "tests/unit/term/test_service_bulk_updates.py::24": {"resolved_imports": ["lute/models/repositories.py", "lute/models/term.py", "lute/db/__init__.py", "lute/term/service.py"], "used_names": ["TermRepository", "db"], "enclosing_function": "assert_updated", "extracted_code": "# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 1134}, "tests/unit/ankiexport/test_service.py::72": {"resolved_imports": ["lute/models/srsexport.py", "lute/ankiexport/service.py"], "used_names": ["Service", "json", "pytest"], "enclosing_function": "test_validate_spec_returns_array_of_errors", "extracted_code": "# Source: lute/ankiexport/service.py\nclass Service:\n \"Srs export service.\"\n\n def __init__(\n self,\n anki_deck_names,\n anki_note_types_and_fields,\n export_specs,\n ):\n \"init\"\n self.anki_deck_names = anki_deck_names\n self.anki_note_types_and_fields = anki_note_types_and_fields\n self.export_specs = export_specs\n\n def validate_spec(self, spec):\n \"\"\"\n Returns array of errors if any for the given spec.\n \"\"\"\n if not spec.active:\n return []\n\n errors = []\n\n try:\n validate_criteria(spec.criteria)\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n if spec.deck_name not in self.anki_deck_names:\n errors.append(f'No deck name \"{spec.deck_name}\"')\n\n valid_note_type = spec.note_type in self.anki_note_types_and_fields\n if not valid_note_type:\n errors.append(f'No note type \"{spec.note_type}\"')\n\n mapping = None\n try:\n mapping = json.loads(spec.field_mapping)\n except json.decoder.JSONDecodeError:\n errors.append(\"Mapping is not valid json\")\n\n if valid_note_type and mapping:\n note_fields = self.anki_note_types_and_fields.get(spec.note_type, {})\n bad_fields = [f for f in mapping.keys() if f not in note_fields]\n if len(bad_fields) > 0:\n bad_fields = \", \".join(bad_fields)\n msg = f\"Note type {spec.note_type} does not have field(s): {bad_fields}\"\n errors.append(msg)\n\n if mapping:\n try:\n validate_mapping(json.loads(spec.field_mapping))\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n return errors\n\n def validate_specs(self):\n \"\"\"\n Return hash of spec ids and any config errors.\n \"\"\"\n failures = {}\n for spec in self.export_specs:\n v = self.validate_spec(spec)\n if len(v) != 0:\n failures[spec.id] = \"; \".join(v)\n return failures\n\n def validate_specs_failure_message(self):\n \"Failure message for alerts.\"\n failures = self.validate_specs()\n msgs = []\n for k, v in failures.items():\n spec = next(s for s in self.export_specs if s.id == k)\n msgs.append(f\"{spec.export_name}: {v}\")\n return msgs\n\n def _all_terms(self, term):\n \"Term and any parents.\"\n ret = [term]\n ret.extend(term.parents)\n return ret\n\n def _all_tags(self, term):\n \"Tags for term and all parents.\"\n ret = [tt.text for t in self._all_terms(term) for tt in t.term_tags]\n return sorted(list(set(ret)))\n\n # pylint: disable=too-many-arguments,too-many-positional-arguments\n def _build_ankiconnect_post_json(\n self,\n mapping,\n media_mappings,\n lute_and_term_tags,\n deck_name,\n model_name,\n ):\n \"Build post json for term using the mappings.\"\n\n post_actions = []\n for new_filename, original_url in media_mappings.items():\n hsh = {\n \"action\": \"storeMediaFile\",\n \"params\": {\n \"filename\": new_filename,\n \"url\": original_url,\n },\n }\n post_actions.append(hsh)\n\n post_actions.append(\n {\n \"action\": \"addNote\",\n \"params\": {\n \"note\": {\n \"deckName\": deck_name,\n \"modelName\": model_name,\n \"fields\": mapping,\n \"tags\": lute_and_term_tags,\n }\n },\n }\n )\n\n return {\"action\": \"multi\", \"params\": {\"actions\": post_actions}}\n\n def get_ankiconnect_post_data_for_term(self, term, base_url, sentence_lookup):\n \"\"\"\n Get post data for a single term.\n This assumes that all the specs are valid!\n Separate method for unit testing.\n \"\"\"\n use_exports = [\n spec\n for spec in self.export_specs\n if spec.active and evaluate_criteria(spec.criteria, term)\n ]\n # print(f\"Using {len(use_exports)} exports\")\n\n ret = {}\n for export in use_exports:\n mapping = json.loads(export.field_mapping)\n replacements, mmap = get_values_and_media_mapping(\n term, sentence_lookup, mapping\n )\n for k, v in mmap.items():\n mmap[k] = base_url + v\n updated_mapping = get_fields_and_final_values(mapping, replacements)\n tags = [\"lute\"] + self._all_tags(term)\n\n p = self._build_ankiconnect_post_json(\n updated_mapping,\n mmap,\n tags,\n export.deck_name,\n export.note_type,\n )\n ret[export.export_name] = p\n\n return ret\n\n def get_ankiconnect_post_data(\n self, term_ids, termid_sentences, base_url, db_session\n ):\n \"\"\"\n Build data to be posted.\n\n Throws if any validation failure or mapping failure, as it's\n annoying to handle partial failures.\n \"\"\"\n\n msgs = self.validate_specs_failure_message()\n if len(msgs) > 0:\n show_msgs = [f\"* {m}\" for m in msgs]\n show_msgs = \"\\n\".join(show_msgs)\n err_msg = \"Anki export configuration errors:\\n\" + show_msgs\n raise AnkiExportConfigurationError(err_msg)\n\n repo = TermRepository(db_session)\n\n refsrepo = ReferencesRepository(db_session)\n sentence_lookup = SentenceLookup(termid_sentences, refsrepo)\n\n ret = {}\n for tid in term_ids:\n term = repo.find(tid)\n pd = self.get_ankiconnect_post_data_for_term(\n term, base_url, sentence_lookup\n )\n if len(pd) > 0:\n ret[tid] = pd\n\n return ret", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 6075}, "plugins/_template_/tests/test_LangNameParser.py::101": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["LangNameParser"], "enclosing_function": "todo_test_readings", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/backup/test_backup.py::194": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["Service", "assert_record_count_equals", "datetime", "db"], "enclosing_function": "test_warn_if_last_backup_never_happened_or_is_old", "extracted_code": "# Source: lute/backup/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def create_backup(self, app_config, settings, is_manual=False, suffix=None):\n \"\"\"\n Create backup using current app config, settings.\n\n is_manual is True if this is a user-triggered manual\n backup, otherwise is False.\n\n suffix can be specified for test.\n\n settings are from BackupSettings.\n - backup_enabled\n - backup_dir\n - backup_auto\n - backup_warn\n - backup_count\n - last_backup_datetime\n \"\"\"\n if not os.path.exists(settings.backup_dir):\n raise BackupException(\"Missing directory \" + settings.backup_dir)\n\n # def _print_now(msg):\n # \"Timing helper for when implement audio backup.\"\n # now = datetime.now().strftime(\"%H-%M-%S\")\n # print(f\"{now} - {msg}\", flush=True)\n\n self._mirror_images_dir(app_config.userimagespath, settings.backup_dir)\n\n prefix = \"manual_\" if is_manual else \"\"\n if suffix is None:\n suffix = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n fname = f\"{prefix}lute_backup_{suffix}.db\"\n backupfile = os.path.join(settings.backup_dir, fname)\n\n f = self._create_db_backup(app_config.dbfilename, backupfile)\n self._remove_excess_backups(settings.backup_count, settings.backup_dir)\n return f\n\n def should_run_auto_backup(self, backup_settings):\n \"\"\"\n True (if applicable) if last backup was old.\n \"\"\"\n bs = backup_settings\n if bs.backup_enabled is False or bs.backup_auto is False:\n return False\n\n last = bs.last_backup_datetime\n if last is None:\n return True\n\n curr = int(time.time())\n diff = curr - last\n return diff > 24 * 60 * 60\n\n def backup_warning(self, backup_settings):\n \"Get warning if needed.\"\n if not backup_settings.backup_warn:\n return \"\"\n\n have_books = self.session.query(self.session.query(Book).exists()).scalar()\n have_terms = self.session.query(self.session.query(Term).exists()).scalar()\n if have_books is False and have_terms is False:\n return \"\"\n\n last = backup_settings.last_backup_datetime\n if last is None:\n return \"Never backed up.\"\n\n curr = int(time.time())\n diff = curr - last\n old_backup_msg = \"Last backup was more than 1 week ago.\"\n if diff > 7 * 24 * 60 * 60:\n return old_backup_msg\n\n return \"\"\n\n def _create_db_backup(self, dbfilename, backupfile):\n \"Make a backup.\"\n shutil.copy(dbfilename, backupfile)\n f = f\"{backupfile}.gz\"\n with open(backupfile, \"rb\") as in_file, gzip.open(\n f, \"wb\", compresslevel=4\n ) as out_file:\n shutil.copyfileobj(in_file, out_file)\n os.remove(backupfile)\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n return f\n\n def skip_this_backup(self):\n \"Set the last backup time to today.\"\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n\n def _remove_excess_backups(self, count, outdir):\n \"Remove old backups.\"\n files = [f for f in self.list_backups(outdir) if not f.is_manual]\n files.sort(reverse=True)\n to_remove = files[count:]\n for f in to_remove:\n os.remove(f.filepath)\n\n def _mirror_images_dir(self, userimagespath, outdir):\n \"Copy the images to backup.\"\n target_dir = os.path.join(outdir, \"userimages_backup\")\n target_dir = os.path.abspath(target_dir)\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n shutil.copytree(userimagespath, target_dir, dirs_exist_ok=True)\n\n def list_backups(self, outdir) -> List[DatabaseBackupFile]:\n \"List all backup files.\"\n return [\n DatabaseBackupFile(os.path.join(outdir, f))\n for f in os.listdir(outdir)\n if re.match(r\"(manual_)?lute_backup_\", f)\n ]\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 6395}, "tests/features/test_term_import.py::97": {"resolved_imports": ["lute/db/__init__.py", "lute/models/language.py", "lute/language/service.py", "lute/models/term.py", "lute/models/repositories.py", "lute/termimport/service.py"], "used_names": ["parsers", "then"], "enclosing_function": "succeed_with_status", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/features/test_rendering.py::108": {"resolved_imports": ["lute/db/__init__.py", "lute/models/language.py", "lute/language/service.py", "lute/term/model.py", "lute/read/render/service.py", "lute/read/service.py"], "used_names": ["db"], "enclosing_function": "_assert_stringized_equals", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 9, "n_files_resolved": 6, "n_chars_extracted": 47}, "tests/orm/test_Book.py::108": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["Book", "BookStats", "db"], "enclosing_function": "test_load_book_loads_lang", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass BookStats(db.Model):\n \"The stats table.\"\n __tablename__ = \"bookstats\"\n\n BkID = db.Column(db.Integer, primary_key=True)\n distinctterms = db.Column(db.Integer)\n distinctunknowns = db.Column(db.Integer)\n unknownpercent = db.Column(db.Integer)\n status_distribution = db.Column(db.String, nullable=True)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 4102}, "tests/acceptance/conftest.py::406": {"resolved_imports": [], "used_names": ["parsers", "when"], "enclosing_function": "when_add_page", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/unit/models/test_Book_add_remove_pages.py::67": {"resolved_imports": ["lute/db/__init__.py"], "used_names": ["db", "make_book"], "enclosing_function": "test_add_page_before_first", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 47}, "tests/unit/backup/test_backup.py::260": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["DatabaseBackupFile", "patch"], "enclosing_function": "test_database_backup_file_size_formatting", "extracted_code": "# Source: lute/backup/service.py\nclass DatabaseBackupFile:\n \"\"\"\n A representation of a lute backup file to hold metadata attributes.\n \"\"\"\n\n def __init__(self, filepath: Union[str, os.PathLike]):\n if not os.path.exists(filepath):\n raise BackupException(f\"No backup file at {filepath}.\")\n\n name = os.path.basename(filepath)\n if not re.match(r\"(manual_)?lute_backup_\", name):\n raise BackupException(f\"Not a valid lute database backup at {filepath}.\")\n\n self.filepath = filepath\n self.name = name\n self.is_manual = self.name.startswith(\"manual_\")\n\n def __lt__(self, other):\n return self.last_modified < other.last_modified\n\n @property\n def last_modified(self) -> datetime:\n return datetime.fromtimestamp(os.path.getmtime(self.filepath)).astimezone()\n\n @property\n def size_bytes(self) -> int:\n return os.path.getsize(self.filepath)\n\n @property\n def size(self) -> str:\n \"\"\"\n A human-readable string representation of the size of the file.\n\n Eg.\n 1746 bytes\n 4 kB\n 27 MB\n \"\"\"\n s = self.size_bytes\n if s >= 1e9:\n return f\"{round(s * 1e-9)} GB\"\n if s >= 1e6:\n return f\"{round(s * 1e-6)} MB\"\n if s >= 1e3:\n return f\"{round(s * 1e-3)} KB\"\n return f\"{s} bytes\"", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 1383}, "tests/unit/models/test_Setting.py::35": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_user_and_system_settings_do_not_intersect", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/unit/db/test_demo.py::113": {"resolved_imports": ["lute/db/__init__.py", "lute/db/demo.py", "lute/parse/registry.py"], "used_names": ["db", "text"], "enclosing_function": "test_tutorial_id_returned_if_present", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 47}, "tests/unit/read/render/test_multiword_indexer.py::53": {"resolved_imports": ["lute/read/render/multiword_indexer.py"], "used_names": ["MultiwordTermIndexer"], "enclosing_function": "test_can_search_multiple_times_with_different_tokens", "extracted_code": "# Source: lute/read/render/multiword_indexer.py\nclass MultiwordTermIndexer:\n \"\"\"\n Find terms in strings using ahocorapy.\n \"\"\"\n\n zws = \"\\u200B\" # zero-width space\n\n def __init__(self):\n self.kwtree = KeywordTree(case_insensitive=True)\n self.finalized = False\n\n def add(self, t):\n \"Add zws-enclosed term to tree.\"\n add_t = f\"{self.zws}{t}{self.zws}\"\n self.kwtree.add(add_t)\n\n def search_all(self, lc_tokens):\n \"Find all terms and starting token index.\"\n if not self.finalized:\n self.kwtree.finalize()\n self.finalized = True\n\n zws = self.zws\n content = zws + zws.join(lc_tokens) + zws\n zwsindexes = [i for i, char in enumerate(content) if char == zws]\n results = self.kwtree.search_all(content)\n\n for result in results:\n # print(f\"{result}\\n\", flush=True)\n t = result[0].strip(zws)\n charpos = result[1]\n index = zwsindexes.index(charpos)\n yield (t, index)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1035}, "plugins/lute-mandarin/tests/test_MandarinParser.py::95": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["MandarinParser"], "enclosing_function": "test_readings", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_service.py::32": {"resolved_imports": ["lute/models/srsexport.py", "lute/ankiexport/service.py"], "used_names": ["Service"], "enclosing_function": "test_validate_returns_empty_hash_if_all_ok", "extracted_code": "# Source: lute/ankiexport/service.py\nclass Service:\n \"Srs export service.\"\n\n def __init__(\n self,\n anki_deck_names,\n anki_note_types_and_fields,\n export_specs,\n ):\n \"init\"\n self.anki_deck_names = anki_deck_names\n self.anki_note_types_and_fields = anki_note_types_and_fields\n self.export_specs = export_specs\n\n def validate_spec(self, spec):\n \"\"\"\n Returns array of errors if any for the given spec.\n \"\"\"\n if not spec.active:\n return []\n\n errors = []\n\n try:\n validate_criteria(spec.criteria)\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n if spec.deck_name not in self.anki_deck_names:\n errors.append(f'No deck name \"{spec.deck_name}\"')\n\n valid_note_type = spec.note_type in self.anki_note_types_and_fields\n if not valid_note_type:\n errors.append(f'No note type \"{spec.note_type}\"')\n\n mapping = None\n try:\n mapping = json.loads(spec.field_mapping)\n except json.decoder.JSONDecodeError:\n errors.append(\"Mapping is not valid json\")\n\n if valid_note_type and mapping:\n note_fields = self.anki_note_types_and_fields.get(spec.note_type, {})\n bad_fields = [f for f in mapping.keys() if f not in note_fields]\n if len(bad_fields) > 0:\n bad_fields = \", \".join(bad_fields)\n msg = f\"Note type {spec.note_type} does not have field(s): {bad_fields}\"\n errors.append(msg)\n\n if mapping:\n try:\n validate_mapping(json.loads(spec.field_mapping))\n except AnkiExportConfigurationError as ex:\n errors.append(str(ex))\n\n return errors\n\n def validate_specs(self):\n \"\"\"\n Return hash of spec ids and any config errors.\n \"\"\"\n failures = {}\n for spec in self.export_specs:\n v = self.validate_spec(spec)\n if len(v) != 0:\n failures[spec.id] = \"; \".join(v)\n return failures\n\n def validate_specs_failure_message(self):\n \"Failure message for alerts.\"\n failures = self.validate_specs()\n msgs = []\n for k, v in failures.items():\n spec = next(s for s in self.export_specs if s.id == k)\n msgs.append(f\"{spec.export_name}: {v}\")\n return msgs\n\n def _all_terms(self, term):\n \"Term and any parents.\"\n ret = [term]\n ret.extend(term.parents)\n return ret\n\n def _all_tags(self, term):\n \"Tags for term and all parents.\"\n ret = [tt.text for t in self._all_terms(term) for tt in t.term_tags]\n return sorted(list(set(ret)))\n\n # pylint: disable=too-many-arguments,too-many-positional-arguments\n def _build_ankiconnect_post_json(\n self,\n mapping,\n media_mappings,\n lute_and_term_tags,\n deck_name,\n model_name,\n ):\n \"Build post json for term using the mappings.\"\n\n post_actions = []\n for new_filename, original_url in media_mappings.items():\n hsh = {\n \"action\": \"storeMediaFile\",\n \"params\": {\n \"filename\": new_filename,\n \"url\": original_url,\n },\n }\n post_actions.append(hsh)\n\n post_actions.append(\n {\n \"action\": \"addNote\",\n \"params\": {\n \"note\": {\n \"deckName\": deck_name,\n \"modelName\": model_name,\n \"fields\": mapping,\n \"tags\": lute_and_term_tags,\n }\n },\n }\n )\n\n return {\"action\": \"multi\", \"params\": {\"actions\": post_actions}}\n\n def get_ankiconnect_post_data_for_term(self, term, base_url, sentence_lookup):\n \"\"\"\n Get post data for a single term.\n This assumes that all the specs are valid!\n Separate method for unit testing.\n \"\"\"\n use_exports = [\n spec\n for spec in self.export_specs\n if spec.active and evaluate_criteria(spec.criteria, term)\n ]\n # print(f\"Using {len(use_exports)} exports\")\n\n ret = {}\n for export in use_exports:\n mapping = json.loads(export.field_mapping)\n replacements, mmap = get_values_and_media_mapping(\n term, sentence_lookup, mapping\n )\n for k, v in mmap.items():\n mmap[k] = base_url + v\n updated_mapping = get_fields_and_final_values(mapping, replacements)\n tags = [\"lute\"] + self._all_tags(term)\n\n p = self._build_ankiconnect_post_json(\n updated_mapping,\n mmap,\n tags,\n export.deck_name,\n export.note_type,\n )\n ret[export.export_name] = p\n\n return ret\n\n def get_ankiconnect_post_data(\n self, term_ids, termid_sentences, base_url, db_session\n ):\n \"\"\"\n Build data to be posted.\n\n Throws if any validation failure or mapping failure, as it's\n annoying to handle partial failures.\n \"\"\"\n\n msgs = self.validate_specs_failure_message()\n if len(msgs) > 0:\n show_msgs = [f\"* {m}\" for m in msgs]\n show_msgs = \"\\n\".join(show_msgs)\n err_msg = \"Anki export configuration errors:\\n\" + show_msgs\n raise AnkiExportConfigurationError(err_msg)\n\n repo = TermRepository(db_session)\n\n refsrepo = ReferencesRepository(db_session)\n sentence_lookup = SentenceLookup(termid_sentences, refsrepo)\n\n ret = {}\n for tid in term_ids:\n term = repo.find(tid)\n pd = self.get_ankiconnect_post_data_for_term(\n term, base_url, sentence_lookup\n )\n if len(pd) > 0:\n ret[tid] = pd\n\n return ret", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 6075}, "tests/unit/read/test_service.py::27": {"resolved_imports": ["lute/models/term.py", "lute/book/model.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Book", "Repository", "Service", "assert_record_count_equals", "db"], "enclosing_function": "test_mark_page_read", "extracted_code": "# Source: lute/book/model.py\nclass Book: # pylint: disable=too-many-instance-attributes\n \"\"\"\n A book domain object, to create/edit lute.models.book.Books.\n\n Book language can be specified either by language_id, or\n language_name. language_name is useful for loading books via\n scripts/api. language_id takes precedence.\n \"\"\"\n\n def __init__(self):\n self.id = None\n self.language_id = None\n self.language_name = None\n self.title = None\n self.text = None\n self.source_uri = None\n self.audio_filename = None\n self.audio_current_pos = None\n self.audio_bookmarks = None\n self.book_tags = []\n\n self.threshold_page_tokens = 250\n self.split_by = \"paragraphs\"\n\n # The source file used for the book text.\n # Overrides the self.text if not None.\n self.text_source_path = None\n\n self.text_stream = None\n self.text_stream_filename = None\n\n # The source file used for audio.\n self.audio_source_path = None\n\n self.audio_stream = None\n self.audio_stream_filename = None\n\n def __repr__(self):\n return f\"\"\n\n def add_tag(self, tag):\n self.book_tags.append(tag)\n\nclass Repository:\n \"\"\"\n Maps Book BO to and from lute.model.Book.\n \"\"\"\n\n def __init__(self, _session):\n self.session = _session\n self.book_repo = BookRepository(self.session)\n\n def load(self, book_id):\n \"Loads a Book business object for the DBBook.\"\n dbb = self.book_repo.find(book_id)\n if dbb is None:\n raise ValueError(f\"No book with id {book_id} found\")\n return self._build_business_book(dbb)\n\n def find_by_title(self, book_title, language_id):\n \"Loads a Book business object for the book with a given title.\"\n dbb = self.book_repo.find_by_title(book_title, language_id)\n if dbb is None:\n return None\n return self._build_business_book(dbb)\n\n def get_book_tags(self):\n \"Get all available book tags, helper method.\"\n bts = self.session.query(BookTag).all()\n return sorted([t.text for t in bts])\n\n def add(self, book):\n \"\"\"\n Add a book to be saved to the db session.\n Returns DBBook for tests and verification only,\n clients should not change it.\n \"\"\"\n dbbook = self._build_db_book(book)\n self.session.add(dbbook)\n return dbbook\n\n def delete(self, book):\n \"\"\"\n Delete.\n \"\"\"\n if book.id is None:\n raise ValueError(f\"book {book.title} not saved\")\n b = self.book_repo.find(book.id)\n self.session.delete(b)\n\n def commit(self):\n \"\"\"\n Commit everything.\n \"\"\"\n self.session.commit()\n\n def _split_text_at_page_breaks(self, txt):\n \"Break fulltext manually at lines consisting of '---' only.\"\n # Tried doing this with a regex without success.\n segments = []\n current_segment = \"\"\n for line in txt.split(\"\\n\"):\n if line.strip() == \"---\":\n segments.append(current_segment.strip())\n current_segment = \"\"\n else:\n current_segment += line + \"\\n\"\n if current_segment:\n segments.append(current_segment.strip())\n return segments\n\n def _split_pages(self, book, language):\n \"Split fulltext into pages, respecting sentences.\"\n\n pages = []\n for segment in self._split_text_at_page_breaks(book.text):\n tokens = language.parser.get_parsed_tokens(segment, language)\n for toks in token_group_generator(\n tokens, book.split_by, book.threshold_page_tokens\n ):\n s = \"\".join([t.token for t in toks])\n s = s.replace(\"\\r\", \"\").replace(\"¶\", \"\\n\")\n pages.append(s.strip())\n pages = [p for p in pages if p.strip() != \"\"]\n\n return pages\n\n def _build_db_book(self, book):\n \"Convert a book business object to a DBBook.\"\n\n lang_repo = LanguageRepository(self.session)\n lang = None\n if book.language_id:\n lang = lang_repo.find(book.language_id)\n elif book.language_name:\n lang = lang_repo.find_by_name(book.language_name)\n if lang is None:\n msg = f\"No language matching id={book.language_id} or name={book.language_name}\"\n raise RuntimeError(msg)\n\n b = None\n if book.id is None:\n pages = self._split_pages(book, lang)\n b = DBBook(book.title, lang)\n for index, page in enumerate(pages):\n _ = DBText(b, page, index + 1)\n else:\n b = self.book_repo.find(book.id)\n\n b.title = book.title\n b.source_uri = book.source_uri\n b.audio_filename = book.audio_filename\n b.audio_current_pos = book.audio_current_pos\n b.audio_bookmarks = book.audio_bookmarks\n\n btr = BookTagRepository(self.session)\n booktags = []\n for s in book.book_tags:\n booktags.append(btr.find_or_create_by_text(s))\n b.remove_all_book_tags()\n for tt in booktags:\n b.add_book_tag(tt)\n\n return b\n\n def _build_business_book(self, dbbook):\n \"Convert db book to Book.\"\n b = Book()\n b.id = dbbook.id\n b.language_id = dbbook.language.id\n b.language_name = dbbook.language.name\n b.title = dbbook.title\n b.text = None # Not returning this for now\n b.source_uri = dbbook.source_uri\n b.audio_filename = dbbook.audio_filename\n b.audio_current_pos = dbbook.audio_current_pos\n b.audio_bookmarks = dbbook.audio_bookmarks\n b.book_tags = [t.text for t in dbbook.book_tags]\n return b\n\n\n# Source: lute/read/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def mark_page_read(self, bookid, pagenum, mark_rest_as_known):\n \"Mark page as read, record stats, rest as known.\"\n br = BookRepository(self.session)\n book = br.find(bookid)\n text = book.text_at_page(pagenum)\n d = datetime.now()\n text.read_date = d\n\n w = WordsRead(text, d, text.word_count)\n self.session.add(text)\n self.session.add(w)\n self.session.commit()\n if mark_rest_as_known:\n self.set_unknowns_to_known(text)\n\n def set_unknowns_to_known(self, text: Text):\n \"\"\"\n Given a text, create new Terms with status Well-Known\n for any new Terms.\n \"\"\"\n rs = RenderService(self.session)\n paragraphs = rs.get_paragraphs(text.text, text.book.language)\n self._save_new_status_0_terms(paragraphs)\n\n unknowns = [\n ti.term\n for para in paragraphs\n for sentence in para\n for ti in sentence\n if ti.is_word and ti.term.status == 0\n ]\n\n batch_size = 100\n i = 0\n\n for t in unknowns:\n t.status = Status.WELLKNOWN\n self.session.add(t)\n i += 1\n if i % batch_size == 0:\n self.session.commit()\n\n # Commit any remaining.\n self.session.commit()\n\n def bulk_status_update(self, text: Text, terms_text_array, new_status):\n \"\"\"\n Given a text and list of terms, update or create new terms\n and set the status.\n \"\"\"\n language = text.book.language\n repo = Repository(self.session)\n for term_text in terms_text_array:\n t = repo.find_or_new(language.id, term_text)\n t.status = new_status\n repo.add(t)\n repo.commit()\n\n def _save_new_status_0_terms(self, paragraphs):\n \"Add status 0 terms for new textitems in paragraph.\"\n tis_with_new_terms = [\n ti\n for para in paragraphs\n for sentence in para\n for ti in sentence\n if ti.is_word and ti.term.id is None and ti.term.status == 0\n ]\n\n for ti in tis_with_new_terms:\n self.session.add(ti.term)\n self.session.commit()\n\n def _get_reading_data(self, dbbook, pagenum, track_page_open=False):\n \"Get paragraphs, set text.start_date if needed.\"\n text = dbbook.text_at_page(pagenum)\n text.load_sentences()\n svc = StatsService(self.session)\n svc.mark_stale(dbbook)\n\n if track_page_open:\n text.start_date = datetime.now()\n dbbook.current_tx_id = text.id\n\n self.session.add(dbbook)\n self.session.add(text)\n self.session.commit()\n\n lang = text.book.language\n rs = RenderService(self.session)\n paragraphs = rs.get_paragraphs(text.text, lang)\n self._save_new_status_0_terms(paragraphs)\n\n return paragraphs\n\n def get_paragraphs(self, dbbook, pagenum):\n \"Get the paragraphs for the book.\"\n return self._get_reading_data(dbbook, pagenum, False)\n\n def start_reading(self, dbbook, pagenum):\n \"Start reading a page in the book, getting paragraphs.\"\n return self._get_reading_data(dbbook, pagenum, True)\n\n def _sort_components(self, term, components):\n \"Sort components by min position in string and length.\"\n component_and_pos = []\n for c in components:\n c_indices = [\n loc[1] for loc in get_string_indexes([c.text_lc], term.text_lc)\n ]\n\n # Sometimes the components aren't found\n # in the string, which makes no sense ...\n # ref https://github.com/LuteOrg/lute-v3/issues/474\n if len(c_indices) > 0:\n component_and_pos.append([c, min(c_indices)])\n\n def compare(a, b):\n # Lowest position (closest to front of string) sorts first.\n if a[1] != b[1]:\n return -1 if (a[1] < b[1]) else 1\n # Longest sorts first.\n alen = len(a[0].text)\n blen = len(b[0].text)\n return -1 if (alen > blen) else 1\n\n component_and_pos.sort(key=functools.cmp_to_key(compare))\n return [c[0] for c in component_and_pos]\n\n def get_popup_data(self, termid):\n \"Get popup data, or None if popup shouldn't be shown.\"\n term = self.session.get(Term, termid)\n if term is None:\n return None\n\n repo = UserSettingRepository(self.session)\n show_components = int(repo.get_value(\"term_popup_show_components\")) == 1\n components = []\n if show_components:\n rs = RenderService(self.session)\n components = [\n c\n for c in rs.find_all_Terms_in_string(term.text, term.language)\n if c.id != term.id and c.status != Status.UNKNOWN\n ]\n\n t = TermPopup(term)\n if (\n t.show is False\n and t.image is None\n and len(term.parents) == 0\n and len(components) == 0\n ):\n # Nothing to show.\"\n return None\n\n parent_data = [TermPopup(p) for p in term.parents]\n\n promote_parent_trans = int(\n repo.get_value(\"term_popup_promote_parent_translation\")\n )\n if (promote_parent_trans == 1) and len(term.parents) == 1:\n ptrans = parent_data[0].translation\n if t.translation == \"\":\n t.translation = ptrans\n if t.translation == ptrans:\n parent_data[0].translation = \"\"\n\n component_data = [TermPopup(c) for c in self._sort_components(term, components)]\n\n t.parents = [p for p in parent_data if p.show]\n t.components = [c for c in component_data if c.show]\n return t\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 11853}, "tests/unit/models/test_Term.py::55": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Term", "text"], "enclosing_function": "test_term_left_as_is_if_its_an_exception", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 7421}, "tests/unit/term/test_service_bulk_updates.py::28": {"resolved_imports": ["lute/models/repositories.py", "lute/models/term.py", "lute/db/__init__.py", "lute/term/service.py"], "used_names": ["TermRepository", "db"], "enclosing_function": "assert_updated", "extracted_code": "# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 1134}, "tests/orm/test_Text.py::58": {"resolved_imports": ["lute/models/book.py", "lute/db/__init__.py"], "used_names": ["Book", "Text", "TextBookmark", "WordsRead", "assert_record_count_equals", "datetime", "db"], "enclosing_function": "test_delete_text_cascade_deletes_bookmarks_leaves_wordsread", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass Text(db.Model):\n \"\"\"\n Each page in a Book.\n \"\"\"\n\n __tablename__ = \"texts\"\n\n id = db.Column(\"TxID\", db.Integer, primary_key=True)\n _text = db.Column(\"TxText\", db.String, nullable=False)\n order = db.Column(\"TxOrder\", db.Integer)\n start_date = db.Column(\"TxStartDate\", db.DateTime, nullable=True)\n _read_date = db.Column(\"TxReadDate\", db.DateTime, nullable=True)\n bk_id = db.Column(\"TxBkID\", db.Integer, db.ForeignKey(\"books.BkID\"), nullable=False)\n word_count = db.Column(\"TxWordCount\", db.Integer, nullable=True)\n\n book = db.relationship(\"Book\", back_populates=\"texts\")\n bookmarks = db.relationship(\n \"TextBookmark\",\n back_populates=\"text\",\n cascade=\"all, delete-orphan\",\n )\n sentences = db.relationship(\n \"Sentence\",\n back_populates=\"text\",\n order_by=\"Sentence.order\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, book, text, order=1):\n self.book = book\n self.text = text\n self.order = order\n self.sentences = []\n\n @property\n def title(self):\n \"\"\"\n Text title is the book title + page fraction.\n \"\"\"\n b = self.book\n s = f\"({self.order}/{self.book.page_count})\"\n t = f\"{b.title} {s}\"\n return t\n\n @property\n def text(self):\n return self._text\n\n @text.setter\n def text(self, s):\n self._text = s\n if s.strip() == \"\":\n return\n toks = self._get_parsed_tokens()\n wordtoks = [t for t in toks if t.is_word]\n self.word_count = len(wordtoks)\n if self._read_date is not None:\n self._load_sentences_from_tokens(toks)\n\n @property\n def read_date(self):\n return self._read_date\n\n @read_date.setter\n def read_date(self, s):\n self._read_date = s\n # Ensure loaded.\n self.load_sentences()\n\n def _get_parsed_tokens(self):\n \"Return the tokens.\"\n lang = self.book.language\n return lang.parser.get_parsed_tokens(self.text, lang)\n\n def _load_sentences_from_tokens(self, parsedtokens):\n \"Save sentences using the tokens.\"\n parser = self.book.language.parser\n self._remove_sentences()\n curr_sentence_tokens = []\n sentence_num = 1\n\n def _add_current():\n \"Create and add sentence from current state.\"\n if curr_sentence_tokens:\n se = Sentence.from_tokens(curr_sentence_tokens, parser, sentence_num)\n self._add_sentence(se)\n # Reset for the next sentence.\n curr_sentence_tokens.clear()\n\n for pt in parsedtokens:\n curr_sentence_tokens.append(pt)\n if pt.is_end_of_sentence:\n _add_current()\n sentence_num += 1\n\n # Add any stragglers.\n _add_current()\n\n def load_sentences(self):\n \"\"\"\n Parse the current text and create Sentence objects.\n \"\"\"\n toks = self._get_parsed_tokens()\n self._load_sentences_from_tokens(toks)\n\n def _add_sentence(self, sentence):\n \"Add a sentence to the Text.\"\n if sentence not in self.sentences:\n self.sentences.append(sentence)\n sentence.text = self\n\n def _remove_sentences(self):\n \"Remove all sentence from the Text.\"\n for sentence in self.sentences:\n sentence.text = None\n self.sentences = []\n\nclass WordsRead(db.Model):\n \"\"\"\n Tracks reading events for Text entities.\n \"\"\"\n\n __tablename__ = \"wordsread\"\n id = db.Column(\"WrID\", db.Integer, primary_key=True)\n language_id = db.Column(\n \"WrLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n tx_id = db.Column(\n \"WrTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"SET NULL\"),\n nullable=True,\n )\n read_date = db.Column(\"WrReadDate\", db.DateTime, nullable=False)\n word_count = db.Column(\"WrWordCount\", db.Integer, nullable=False)\n\n def __init__(self, text, read_date, word_count):\n self.tx_id = text.id\n self.language_id = text.book.language.id\n self.read_date = read_date\n self.word_count = word_count\n\nclass TextBookmark(db.Model):\n \"\"\"\n Bookmarks for a given Book page\n\n The TextBookmark includes a title\n \"\"\"\n\n __tablename__ = \"textbookmarks\"\n\n id = db.Column(\"TbID\", db.Integer, primary_key=True)\n tx_id = db.Column(\n \"TbTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"CASCADE\"),\n nullable=False,\n )\n title = db.Column(\"TbTitle\", db.Text, nullable=False)\n\n text = db.relationship(\"Text\", back_populates=\"bookmarks\")\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8481}, "tests/unit/models/test_Term.py::56": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Term", "text"], "enclosing_function": "test_term_left_as_is_if_its_an_exception", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 7421}, "tests/unit/language/test_service.py::74": {"resolved_imports": ["lute/language/service.py", "lute/db/__init__.py", "lute/utils/debug_helpers.py"], "used_names": ["DebugTimer", "Service", "assert_sql_result", "db"], "enclosing_function": "test_load_def_loads_lang_and_stories", "extracted_code": "# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/utils/debug_helpers.py\nclass DebugTimer:\n \"\"\"\n Helper to log time.\n \"\"\"\n\n global_step_map = {}\n\n def __init__(self, name, display=True):\n self.start = time.process_time()\n self.curr_start = self.start\n self.name = name\n self.step_map = {}\n self.display = display\n if display:\n print(f\"{name} timer started\")\n\n def step(self, s):\n \"Dump time spent in step, total time since start.\"\n n = time.process_time()\n step_elapsed = n - self.curr_start\n total_step_elapsed = self.step_map.get(s, 0)\n total_step_elapsed += step_elapsed\n self.step_map[s] = total_step_elapsed\n\n if s != \"\":\n full_step_map_string = f\"{self.name} {s}\"\n global_step_elapsed = DebugTimer.global_step_map.get(\n full_step_map_string, 0\n )\n global_step_elapsed += step_elapsed\n DebugTimer.global_step_map[full_step_map_string] = global_step_elapsed\n\n total_elapsed = n - self.start\n self.curr_start = n\n\n if not self.display:\n return\n\n msg = \" \".join(\n [\n f\"{self.name} {s}:\",\n f\"step_elapsed: {step_elapsed:.6f},\",\n f\"total step_elapsed: {total_step_elapsed:.6f},\",\n f\"total_elapsed: {total_elapsed:.6f}\",\n ]\n )\n print(msg, flush=True)\n\n def summary(self):\n \"Print final step summary.\"\n print(f\"{self.name} summary ------------------\", flush=True)\n for k, v in self.step_map.items():\n print(f\" {k}: {v:.6f}\", flush=True)\n print(f\"end {self.name} summary --------------\", flush=True)\n\n @classmethod\n def clear_total_summary(cls):\n cls.global_step_map = {}\n\n @classmethod\n def total_summary(cls):\n \"Print final step summary.\"\n print(\"global summary ------------------\", flush=True)\n for k, v in cls.global_step_map.items():\n print(f\" {k}: {v:.6f}\", flush=True)\n print(\"end global summary --------------\", flush=True)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4318}, "tests/orm/test_Term.py::24": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_and_remove", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/orm/test_Term.py::172": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_replace_remove_image", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/book/test_stats.py::133": {"resolved_imports": ["lute/db/__init__.py", "lute/term/model.py", "lute/book/stats.py"], "used_names": ["assert_sql_result"], "enclosing_function": "assert_stats", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/backup/test_backup.py::108": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["Service", "db", "os"], "enclosing_function": "test_timestamp_added_to_db_name", "extracted_code": "# Source: lute/backup/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def create_backup(self, app_config, settings, is_manual=False, suffix=None):\n \"\"\"\n Create backup using current app config, settings.\n\n is_manual is True if this is a user-triggered manual\n backup, otherwise is False.\n\n suffix can be specified for test.\n\n settings are from BackupSettings.\n - backup_enabled\n - backup_dir\n - backup_auto\n - backup_warn\n - backup_count\n - last_backup_datetime\n \"\"\"\n if not os.path.exists(settings.backup_dir):\n raise BackupException(\"Missing directory \" + settings.backup_dir)\n\n # def _print_now(msg):\n # \"Timing helper for when implement audio backup.\"\n # now = datetime.now().strftime(\"%H-%M-%S\")\n # print(f\"{now} - {msg}\", flush=True)\n\n self._mirror_images_dir(app_config.userimagespath, settings.backup_dir)\n\n prefix = \"manual_\" if is_manual else \"\"\n if suffix is None:\n suffix = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n fname = f\"{prefix}lute_backup_{suffix}.db\"\n backupfile = os.path.join(settings.backup_dir, fname)\n\n f = self._create_db_backup(app_config.dbfilename, backupfile)\n self._remove_excess_backups(settings.backup_count, settings.backup_dir)\n return f\n\n def should_run_auto_backup(self, backup_settings):\n \"\"\"\n True (if applicable) if last backup was old.\n \"\"\"\n bs = backup_settings\n if bs.backup_enabled is False or bs.backup_auto is False:\n return False\n\n last = bs.last_backup_datetime\n if last is None:\n return True\n\n curr = int(time.time())\n diff = curr - last\n return diff > 24 * 60 * 60\n\n def backup_warning(self, backup_settings):\n \"Get warning if needed.\"\n if not backup_settings.backup_warn:\n return \"\"\n\n have_books = self.session.query(self.session.query(Book).exists()).scalar()\n have_terms = self.session.query(self.session.query(Term).exists()).scalar()\n if have_books is False and have_terms is False:\n return \"\"\n\n last = backup_settings.last_backup_datetime\n if last is None:\n return \"Never backed up.\"\n\n curr = int(time.time())\n diff = curr - last\n old_backup_msg = \"Last backup was more than 1 week ago.\"\n if diff > 7 * 24 * 60 * 60:\n return old_backup_msg\n\n return \"\"\n\n def _create_db_backup(self, dbfilename, backupfile):\n \"Make a backup.\"\n shutil.copy(dbfilename, backupfile)\n f = f\"{backupfile}.gz\"\n with open(backupfile, \"rb\") as in_file, gzip.open(\n f, \"wb\", compresslevel=4\n ) as out_file:\n shutil.copyfileobj(in_file, out_file)\n os.remove(backupfile)\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n return f\n\n def skip_this_backup(self):\n \"Set the last backup time to today.\"\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n\n def _remove_excess_backups(self, count, outdir):\n \"Remove old backups.\"\n files = [f for f in self.list_backups(outdir) if not f.is_manual]\n files.sort(reverse=True)\n to_remove = files[count:]\n for f in to_remove:\n os.remove(f.filepath)\n\n def _mirror_images_dir(self, userimagespath, outdir):\n \"Copy the images to backup.\"\n target_dir = os.path.join(outdir, \"userimages_backup\")\n target_dir = os.path.abspath(target_dir)\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n shutil.copytree(userimagespath, target_dir, dirs_exist_ok=True)\n\n def list_backups(self, outdir) -> List[DatabaseBackupFile]:\n \"List all backup files.\"\n return [\n DatabaseBackupFile(os.path.join(outdir, f))\n for f in os.listdir(outdir)\n if re.match(r\"(manual_)?lute_backup_\", f)\n ]\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 6395}, "tests/unit/term/test_Repository.py::378": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py", "lute/term/model.py"], "used_names": [], "enclosing_function": "test_update_child_add_existing_parent_does_not_change_parent_data_even_if_missing", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_field_mapping.py::90": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "get_values_and_media_mapping"], "enclosing_function": "test_basic_replacements", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\ndef get_values_and_media_mapping(term, sentence_lookup, mapping):\n \"\"\"\n Get the value replacements to be put in the mapping, and build\n dict of new filenames to original filenames.\n \"\"\"\n\n def all_translations():\n ret = [term.translation or \"\"]\n for p in term.parents:\n if p.translation not in ret:\n ret.append(p.translation or \"\")\n return [r for r in ret if r.strip() != \"\"]\n\n def parse_keys_needing_calculation(calculate_keys, media_mappings):\n \"\"\"\n Build a parser for some keys in the mapping string, return\n calculated value to use in the mapping. SIDE EFFECT:\n adds ankiconnect post actions to post_actions if needed\n (e.g. for image uploads).\n\n e.g. the mapping \"article: { tags:[\"der\", \"die\", \"das\"] }\"\n needs to be parsed to extract certain tags from the current\n term.\n \"\"\"\n\n def _filtered_tags_in_term_list(term_list, tagvals):\n \"Get all unique tags.\"\n # tagvals is a pyparsing ParseResults, use list() to convert to strings.\n ttext = [tt.text for t in term_list for tt in t.term_tags]\n ttext = sorted(list(set(ttext)))\n ftags = [tt for tt in ttext if tt in list(tagvals)]\n return \", \".join(ftags)\n\n def get_filtered_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list([term], tagvals)\n\n def get_filtered_parents_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list(term.parents, tagvals)\n\n def handle_image(_):\n id_images = [\n (t, t.get_current_image())\n for t in _all_terms(term)\n if t.get_current_image() is not None\n ]\n image_srcs = []\n for t, imgfilename in id_images:\n new_filename = f\"LUTE_TERM_{t.id}.jpg\"\n image_url = f\"/userimages/{t.language.id}/{imgfilename}\"\n media_mappings[new_filename] = image_url\n image_srcs.append(f'')\n\n return \"\".join(image_srcs)\n\n def handle_sentences(_):\n \"Get sample sentence for term.\"\n if term.id is None:\n # Dummy parse.\n return \"\"\n return sentence_lookup.get_sentence_for_term(term.id)\n\n quotedString.setParseAction(pp.removeQuotes)\n tagvallist = Suppress(\"[\") + pp.delimitedList(quotedString) + Suppress(\"]\")\n tagcrit = tagvallist | QuotedString(quoteChar='\"')\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n\n image = Suppress(\"image\")\n sentence = Suppress(\"sentence\")\n\n matcher = (\n tag_matcher.set_parse_action(get_filtered_tags)\n | parents_tag_matcher.set_parse_action(get_filtered_parents_tags)\n | image.set_parse_action(handle_image)\n | sentence.set_parse_action(handle_sentences)\n )\n\n calc_replacements = {\n # Matchers return the value that should be used as the\n # replacement value for the given mapping string. e.g.\n # tags[\"der\", \"die\"] returns \"der\" if term.tags = [\"der\", \"x\"]\n k: matcher.parseString(k).asList()[0]\n for k in calculate_keys\n }\n\n return calc_replacements\n\n def remove_zws(replacements_dict):\n cleaned = {}\n for key, value in replacements_dict.items():\n if isinstance(value, str):\n cleaned[key] = value.replace(\"\\u200B\", \"\")\n else:\n cleaned[key] = value\n return cleaned\n\n # One-for-one replacements in the mapping string.\n # e.g. \"{ id }\" is replaced by term.termid.\n replacements = {\n \"id\": term.id,\n \"term\": term.text,\n \"language\": term.language.name,\n \"parents\": \", \".join([p.text for p in term.parents]),\n \"tags\": \", \".join(sorted({tt.text for tt in term.term_tags})),\n \"translation\": \"
\".join(all_translations()),\n \"pronunciation\": term.romanization,\n \"parents.pronunciation\": \", \".join(\n [p.romanization or \"\" for p in term.parents]\n ),\n }\n\n mapping_string = \"; \".join(mapping.values())\n calc_keys = [\n k\n for k in set(re.findall(r\"{\\s*(.*?)\\s*}\", mapping_string))\n if k not in replacements\n ]\n\n media_mappings = {}\n calc_replacements = parse_keys_needing_calculation(calc_keys, media_mappings)\n\n final_replacements = {**replacements, **calc_replacements}\n cleaned = remove_zws(final_replacements)\n return (cleaned, media_mappings)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4848}, "tests/unit/term_parent_map/test_service.py::36": {"resolved_imports": ["lute/db/__init__.py", "lute/term_parent_map/service.py"], "used_names": [], "enclosing_function": "assert_file_content", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_field_mapping.py::196": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "SentenceLookup"], "enclosing_function": "test_sentence_lookup_finds_sentence_in_supplied_dict_or_does_db_call", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\nclass SentenceLookup:\n \"Sentence lookup, finds in a supplied dictionary or from db.\"\n\n def __init__(self, default_sentences_by_term_id, references_repo):\n \"init\"\n sdict = {}\n for k, v in default_sentences_by_term_id.items():\n sdict[int(k)] = v\n self.default_sentences_by_term_id = sdict\n self.references_repo = references_repo\n\n def get_sentence_for_term(self, term_id):\n \"Get sentence from the dict, or do a lookup.\"\n tid = int(term_id)\n if tid in self.default_sentences_by_term_id:\n return self.default_sentences_by_term_id[tid]\n\n refs = self.references_repo.find_references_by_id(term_id)\n term_refs = refs[\"term\"] or []\n if len(term_refs) == 0:\n return \"\"\n return term_refs[0].sentence", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 858}, "tests/orm/test_Language.py::37": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Language", "assert_sql_result", "db"], "enclosing_function": "test_save_new_language", "extracted_code": "# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 6039}, "tests/unit/book/test_stats.py::42": {"resolved_imports": ["lute/db/__init__.py", "lute/term/model.py", "lute/book/stats.py"], "used_names": ["Service", "db", "make_text"], "enclosing_function": "scenario", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/book/stats.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _last_n_pages(self, book, txindex, n):\n \"Get next n pages, or at least n pages.\"\n start_index = max(0, txindex - n)\n end_index = txindex + n\n texts = book.texts[start_index:end_index]\n return texts[-n:]\n\n def _get_sample_texts(self, book):\n \"Get texts to use as sample.\"\n txindex = 0\n if (book.current_tx_id or 0) != 0:\n for t in book.texts:\n if t.id == book.current_tx_id:\n break\n txindex += 1\n\n repo = UserSettingRepository(self.session)\n sample_size = int(repo.get_value(\"stats_calc_sample_size\") or 5)\n texts = self._last_n_pages(book, txindex, sample_size)\n return texts\n\n def calc_status_distribution(self, book):\n \"\"\"\n Calculate statuses and count of unique words per status.\n\n Does a full render of a small number of pages\n to calculate the distribution.\n \"\"\"\n\n # DebugTimer.clear_total_summary()\n # dt = DebugTimer(\"get_status_distribution\", display=False)\n texts = self._get_sample_texts(book)\n\n # Getting the individual paragraphs per page, and then combining,\n # is much faster than combining all pages into one giant page.\n service = RenderService(self.session)\n mw = service.get_multiword_indexer(book.language)\n textitems = []\n for tx in texts:\n textitems.extend(service.get_textitems(tx.text, book.language, mw))\n # # Old slower code:\n # text_sample = \"\\n\".join([t.text for t in texts])\n # paras = get_paragraphs(text_sample, book.language) ... etc.\n # dt.step(\"get_paragraphs\")\n\n textitems = [ti for ti in textitems if ti.is_word]\n statterms = {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 98: [], 99: []}\n for ti in textitems:\n statterms[ti.wo_status or 0].append(ti.text_lc)\n\n stats = {}\n for statusval, allterms in statterms.items():\n uniques = list(set(allterms))\n statterms[statusval] = uniques\n stats[statusval] = len(uniques)\n\n # dt.step(\"compiled\")\n # DebugTimer.total_summary()\n\n return stats\n\n def refresh_stats(self):\n \"Refresh stats for all books requiring update.\"\n sql = \"delete from bookstats where status_distribution is null\"\n self.session.execute(text(sql))\n self.session.commit()\n book_ids_with_stats = select(BookStats.BkID).scalar_subquery()\n books_to_update = (\n self.session.query(Book).filter(~Book.id.in_(book_ids_with_stats)).all()\n )\n books = [b for b in books_to_update if b.is_supported]\n for book in books:\n stats = self._calculate_stats(book)\n self._update_stats(book, stats)\n\n def mark_stale(self, book):\n \"Mark a book's stats as stale to force refresh.\"\n bk_id = book.id\n self.session.query(BookStats).filter_by(BkID=bk_id).delete()\n self.session.commit()\n\n def get_stats(self, book):\n \"Gets stats from the cache if available, or calculates.\"\n bk_id = book.id\n stats = self.session.query(BookStats).filter_by(BkID=bk_id).first()\n if stats is None or stats.status_distribution is None:\n newstats = self._calculate_stats(book)\n self._update_stats(book, newstats)\n stats = self.session.query(BookStats).filter_by(BkID=bk_id).first()\n return stats\n\n def _calculate_stats(self, book):\n \"Calc stats for the book using the status distribution.\"\n status_distribution = self.calc_status_distribution(book)\n unknowns = status_distribution[0]\n allunique = sum(status_distribution.values())\n\n percent = 0\n if allunique > 0: # In case not parsed.\n percent = round(100.0 * unknowns / allunique)\n\n return {\n \"allunique\": allunique,\n \"unknowns\": unknowns,\n \"percent\": percent,\n \"distribution\": json.dumps(status_distribution),\n }\n\n def _update_stats(self, book, stats):\n \"Update BookStats for the given book.\"\n s = self.session.query(BookStats).filter_by(BkID=book.id).first()\n if s is None:\n s = BookStats(BkID=book.id)\n s.distinctterms = stats[\"allunique\"]\n s.distinctunknowns = stats[\"unknowns\"]\n s.unknownpercent = stats[\"percent\"]\n s.status_distribution = stats[\"distribution\"]\n self.session.add(s)\n self.session.commit()", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 4720}, "tests/unit/models/test_Language.py::54": {"resolved_imports": ["lute/db/__init__.py", "lute/db/demo.py", "lute/models/language.py", "lute/models/repositories.py"], "used_names": ["Language", "LanguageRepository", "db"], "enclosing_function": "test_can_find_lang_by_name", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/language.py\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/models/repositories.py\nclass LanguageRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, language_id):\n \"Get by ID.\"\n return self.session.query(Language).filter(Language.id == language_id).first()\n\n def find_by_name(self, name):\n \"Get by name.\"\n return (\n self.session.query(Language)\n .filter(func.lower(Language.name) == func.lower(name))\n .first()\n )\n\n def all_dictionaries(self):\n \"All dictionaries for all languages.\"\n lang_dicts = {}\n for lang in db.session.query(Language).all():\n lang_dicts[lang.id] = {\n \"term\": lang.active_dict_uris(\"terms\"),\n \"sentence\": lang.active_dict_uris(\"sentences\"),\n }\n return lang_dicts", "n_imports_parsed": 5, "n_files_resolved": 4, "n_chars_extracted": 6897}, "tests/unit/read/render/test_calculate_textitems.py::36": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py", "lute/read/render/calculate_textitems.py"], "used_names": ["Term", "get_textitems"], "enclosing_function": "assert_renderable_equals", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/read/render/calculate_textitems.py\ndef get_textitems(tokens, terms, language, multiword_term_indexer=None):\n \"\"\"\n Return TextItems that will **actually be rendered**.\n\n Method to determine what should be rendered:\n\n - Create TextItems for all of the tokens, finding their\n starting index in the tokens.\n\n - \"Write\" the TextItems to an array in correctly sorted\n order, so that the correct TextItems take precendence\n in the final rendering.\n\n - Calculate any term overlaps.\n\n - Return the final list of TextItems that will actually\n be rendered.\n\n ---\n\n Applying the above algorithm to the example given in the class\n header:\n\n We have the following TextTokens A-I:\n\n A B C D E F G H I\n\n And given the following terms:\n \"A\" through \"I\" (single-word terms)\n \"B C\" (term J)\n \"E F G H I\" (K)\n \"F G\" (L)\n \"C D E\" (M)\n\n Creating TextItems for all of the terms, finding their starting\n indices in the tokens:\n\n TextToken index length\n ---- ----- ------\n [A] 0 1\n [B] 1 1\n ...\n [I] 8 1\n [B C] 1 2\n [E F G H I] 4 5\n [F G] 5 2\n [C D E] 2 3\n\n Sorting by index, then decreasing token count:\n\n TextToken index length ID (for later reference)\n ---- ----- ------ ------------------------\n [A] 0 1 t1\n [B C] 1 2 t2\n [B] 1 1 t3\n [C D E] 2 3 t4\n [C] 2 1 t5\n [D] 3 1 t6\n [E F G H I] 4 5 t7\n [E] 4 1 t8\n [F G] 5 2 t9\n [F] 5 1 t10\n [G] 6 1 t11\n [H] 7 1 t12\n [I] 8 1 t13\n\n Starting at the bottom of the above list and\n working upwards:\n\n - ID of [I] is written to index 8: [] [] [] [] [] [] [] [] [t13]\n - ID of [H] to index 7: [] [] [] [] [] [] [] [t12] [t13]\n - ...\n - [F G] to index 5 *and* 6: [] [] [] [] [] [t9] [t9] [t12] [t13]\n - [E] to index 4: [] [] [] [] [t8] [t9] [t9] [t12] [t13]\n - [E F G H I] to indexes 4-8: [] [] [] [] [t7] [t7] [t7] [t7] [t7]\n - ... etc\n\n Using the TextItem IDs, the resulting array would be:\n\n output array: [t1] [t2] [t2] [t4] [t4] [t7] [t7] [t7] [t7]\n [A] [B C] [-D E] [-F G H I]\n\n The only TextItems that will be shown are therefore:\n t1, t2, t3, t7\n\n To calculate what text is actually displayed, the count\n of each ID is used. e.g.:\n - ID t7 appears 4 times in the output array. The last 4 tokens of\n [E F G H I] are [F G H I], which will be used as t7's display text.\n - ID t2 appears 2 times. The last 2 tokens of [B C] are [B C],\n so that will be the display text. etc.\n \"\"\"\n # pylint: disable=too-many-locals\n\n # dt = DebugTimer(\"get_textitems\", display=False)\n\n new_unknown_terms = _create_missing_status_0_terms(tokens, terms, language)\n # dt.step(\"new_unknown_terms\")\n\n all_terms = terms + new_unknown_terms\n text_to_term = {dt.text_lc: dt for dt in all_terms}\n\n tokens_orig = [t.token for t in tokens]\n tokens_lc = [language.parser.get_lowercase(t) for t in tokens_orig]\n\n textitems = []\n\n def _add_textitem(index, text_lc, count):\n \"Add a TextItem for position index in tokens.\"\n text_orig = tokens_orig[index]\n if count > 1:\n text_orig = zws.join(tokens_orig[index : index + count])\n text_lc = zws.join(tokens_lc[index : index + count])\n sentence_number = tokens[index].sentence_number\n term = text_to_term.get(text_lc, None)\n ti = _make_textitem(index, text_orig, text_lc, count, sentence_number, term)\n textitems.append(ti)\n\n # Single-word terms.\n for index, _ in enumerate(tokens):\n _add_textitem(index, tokens_lc[index], 1)\n # dt.step(\"single word textitems\")\n\n # Multiword terms.\n if multiword_term_indexer is not None:\n for r in multiword_term_indexer.search_all(tokens_lc):\n mwt = text_to_term[r[0]]\n count = mwt.token_count\n _add_textitem(r[1], r[0], count)\n # dt.step(f\"get mw textitems w indexer\")\n else:\n multiword_terms = [t.text_lc for t in all_terms if t.token_count > 1]\n for e in get_string_indexes(multiword_terms, zws.join(tokens_lc)):\n count = e[0].count(zws) + 1\n _add_textitem(e[1], e[0], count)\n # dt.step(\"mw textitems without indexer\")\n\n # Sorting by index, then decreasing token count.\n textitems = sorted(textitems, key=lambda x: (x.index, -x.token_count))\n\n # \"Write out\" TextItems to the output array.\n output_textitem_ids = [None] * len(tokens)\n for ti in reversed(textitems):\n for c in range(ti.index, ti.index + ti.token_count):\n output_textitem_ids[c] = id(ti)\n\n # Calc display_counts; e.g. if a textitem's id shows up 3 times\n # in the output_textitem_ids, it should display 3 tokens.\n id_counts = dict(Counter(output_textitem_ids))\n for ti in textitems:\n ti.display_count = id_counts.get(id(ti), 0)\n # dt.step(\"display_count\")\n\n textitems = [ti for ti in textitems if ti.display_count > 0]\n\n current_paragraph = 0\n for ti in textitems:\n ti.paragraph_number = current_paragraph\n if ti.text == \"¶\":\n current_paragraph += 1\n # dt.step(\"paragraphs\")\n # dt.step(\"done\")\n\n return textitems", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 13156}, "tests/acceptance/conftest.py::509": {"resolved_imports": [], "used_names": ["then"], "enclosing_function": "then_reading_page_term_form_is_hidden", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 0, "n_chars_extracted": 0}, "tests/orm/test_Term.py::69": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_term_parent_with_two_children", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/read/render/test_service.py::128": {"resolved_imports": ["lute/parse/base.py", "lute/read/render/service.py", "lute/db/__init__.py", "lute/models/term.py"], "used_names": ["ParsedToken", "Service", "Term", "add_terms", "assert_sql_result", "db", "make_text"], "enclosing_function": "test_smoke_get_paragraphs", "extracted_code": "# Source: lute/parse/base.py\nclass ParsedToken:\n \"\"\"\n A single parsed token from an input text.\n\n As tokens are created, the class counters\n (starting with cls_) are assigned to the ParsedToken\n and then incremented appropriately.\n \"\"\"\n\n # Class counters.\n cls_sentence_number = 0\n cls_order = 0\n\n @classmethod\n def reset_counters(cls):\n \"\"\"\n Reset all the counters.\n \"\"\"\n ParsedToken.cls_sentence_number = 0\n ParsedToken.cls_order = 0\n\n def __init__(self, token: str, is_word: bool, is_end_of_sentence: bool = False):\n self.token = token\n self.is_word = is_word\n self.is_end_of_sentence = is_end_of_sentence\n\n ParsedToken.cls_order += 1\n self.order = ParsedToken.cls_order\n\n self.sentence_number = ParsedToken.cls_sentence_number\n\n # Increment counters after the TextToken has been\n # completed, so that it belongs to the correct\n # sentence.\n if self.is_end_of_sentence:\n ParsedToken.cls_sentence_number += 1\n\n @property\n def is_end_of_paragraph(self):\n return self.token.strip() == \"¶\"\n\n def __repr__(self):\n attrs = [\n f\"word: {self.is_word}\",\n f\"eos: {self.is_end_of_sentence}\",\n # f\"sent: {self.sentence_number}\",\n ]\n attrs = \", \".join(attrs)\n return f'<\"{self.token}\" ({attrs})>'\n\n\n# Source: lute/read/render/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def find_all_Terms_in_string(self, s, language): # pylint: disable=too-many-locals\n \"\"\"\n Find all terms contained in the string s.\n\n For example\n - given s = \"Here is a cat\"\n - given terms in the db: [ \"cat\", \"a cat\", \"dog\" ]\n\n This would return the terms \"cat\" and \"a cat\".\n \"\"\"\n cleaned = re.sub(r\" +\", \" \", s)\n tokens = language.get_parsed_tokens(cleaned)\n return self._find_all_terms_in_tokens(tokens, language)\n\n def _get_multiword_terms(self, language):\n \"Get all multiword terms.\"\n sql = sqltext(\n \"\"\"\n SELECT WoID, WoTextLC FROM words\n WHERE WoLgID=:language_id and WoTokenCount>1\n \"\"\"\n )\n sql = sql.bindparams(language_id=language.id)\n return self.session.execute(sql).all()\n\n def _find_all_multi_word_term_text_lcs_in_content(self, text_lcs, language):\n \"Find multiword terms, return list of text_lcs.\"\n\n # There are a few ways of finding multi-word Terms\n # (with token_count > 1) in the content:\n #\n # 1. load each mword term text_lc via sql and check.\n # 2. using the model\n # 3. SQL with \"LIKE\"\n #\n # During reasonable test runs with my data, the times in seconds\n # for each are similar (~0.02, ~0.05, ~0.025). This method is\n # only used for small amounts of data, and the user experience hit\n # is negligible, so I'll use the first method which IMO is the clearest\n # code.\n\n zws = \"\\u200B\" # zero-width space\n content = zws + zws.join(text_lcs) + zws\n\n # Method 1:\n reclist = self._get_multiword_terms(language)\n return [p[1] for p in reclist if f\"{zws}{p[1]}{zws}\" in content]\n\n ## # Method 2: use the model.\n ## contained_term_qry = self.session.query(Term).filter(\n ## Term.language == language,\n ## Term.token_count > 1,\n ## func.instr(content, Term.text_lc) > 0,\n ## )\n ## return [r.text_lc for r in contained_term_qry.all()]\n\n ## # Method 3: Query with LIKE\n ## sql = sqltext(\n ## \"\"\"\n ## SELECT WoTextLC FROM words\n ## WHERE WoLgID=:lid and WoTokenCount>1\n ## AND :content LIKE '%' || :zws || WoTextLC || :zws || '%'\n ## \"\"\"\n ## )\n ## sql = sql.bindparams(lid=language.id, content=content, zws=zws)\n ## recs = self.session.execute(sql).all()\n ## return [r[0] for r in recs]\n\n def _find_all_terms_in_tokens(self, tokens, language, kwtree=None):\n \"\"\"\n Find all terms contained in the (ordered) parsed tokens tokens.\n\n For example\n - given tokens = \"Here\", \" \", \"is\", \" \", \"a\", \" \", \"cat\"\n - given terms in the db: [ \"cat\", \"a/ /cat\", \"dog\" ]\n\n This would return the terms \"cat\" and \"a/ /cat\".\n\n Method:\n - build list of lowercase text in the tokens\n - append all multword term strings that exist in the content\n - query for Terms that exist in the list\n\n Note: this method only uses indexes for multiword terms, as any\n content analyzed is first parsed into tokens before being passed\n to this routine. There's no need to search for single-word Terms\n in the tokenized strings, they can be found by a simple query.\n \"\"\"\n\n # Performance: About half of the time in this routine is spent in\n # Step 1 (finding multiword terms), the rest in step 2 (the actual\n # query).\n # dt = DebugTimer(\"_find_all_terms_in_tokens\", display=True)\n\n parser = language.parser\n text_lcs = [parser.get_lowercase(t.token) for t in tokens]\n\n # Step 1: get the multiwords in the content.\n if kwtree is None:\n mword_terms = self._find_all_multi_word_term_text_lcs_in_content(\n text_lcs, language\n )\n else:\n results = kwtree.search_all(text_lcs)\n mword_terms = [r[0] for r in results]\n # dt.step(\"filtered mword terms\")\n\n # Step 2: load the Term objects.\n #\n # The Term fetch is actually performant -- there is no\n # real difference between loading the Term objects versus\n # loading raw data with SQL and getting dicts.\n #\n # Code for getting raw data:\n # param_keys = [f\"w{i}\" for i, _ in enumerate(text_lcs)]\n # keys_placeholders = ','.join([f\":{k}\" for k in param_keys])\n # param_dict = dict(zip(param_keys, text_lcs))\n # param_dict[\"langid\"] = language.id\n # sql = sqltext(f\"\"\"SELECT WoID, WoTextLC FROM words\n # WHERE WoLgID=:langid and WoTextLC in ({keys_placeholders})\"\"\")\n # sql = sql.bindparams(language.id, *text_lcs)\n # results = self.session.execute(sql, param_dict).fetchall()\n text_lcs.extend(mword_terms)\n tok_strings = list(set(text_lcs))\n terms_matching_tokens_qry = self.session.query(Term).filter(\n Term.text_lc.in_(tok_strings), Term.language == language\n )\n all_terms = terms_matching_tokens_qry.all()\n # dt.step(\"exec query\")\n\n return all_terms\n\n def get_textitems(self, s, language, multiword_term_indexer=None):\n \"\"\"\n Get array of TextItems for the string s.\n\n The multiword_term_indexer is a big performance boost, but takes\n time to initialize.\n \"\"\"\n # Hacky reset of state of ParsedToken state.\n # _Shouldn't_ be needed but doesn't hurt, even if it's lame.\n ParsedToken.reset_counters()\n\n cleaned = re.sub(r\" +\", \" \", s)\n tokens = language.get_parsed_tokens(cleaned)\n terms = self._find_all_terms_in_tokens(tokens, language, multiword_term_indexer)\n textitems = calc_get_textitems(tokens, terms, language, multiword_term_indexer)\n return textitems\n\n def get_multiword_indexer(self, language):\n \"Return indexer loaded with all multiword terms.\"\n mw = MultiwordTermIndexer()\n for r in self._get_multiword_terms(language):\n mw.add(r[1])\n return mw\n\n def get_paragraphs(self, s, language):\n \"\"\"\n Get array of arrays of TextItems for the given string s.\n\n This doesn't use an indexer, as it should only be used\n for a single page of text!\n \"\"\"\n textitems = self.get_textitems(s, language)\n\n def _split_textitems_by_paragraph(textitems):\n \"Split by ¶\"\n ret = []\n curr_para = []\n for t in textitems:\n if t.text == \"¶\":\n ret.append(curr_para)\n curr_para = []\n else:\n curr_para.append(t)\n if len(curr_para) > 0:\n ret.append(curr_para)\n return ret\n\n def _split_by_sentence_number(p):\n sentences = [\n list(sentence)\n for _, sentence in itertools.groupby(p, key=lambda t: t.sentence_number)\n ]\n for s in sentences:\n s[0].add_html_class(\"sentencestart\")\n return sentences\n\n paras = [\n _split_by_sentence_number(list(sentences))\n for sentences in _split_textitems_by_paragraph(textitems)\n ]\n\n return paras\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 16389}, "tests/unit/backup/test_backup.py::262": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["DatabaseBackupFile", "patch"], "enclosing_function": "test_database_backup_file_size_formatting", "extracted_code": "# Source: lute/backup/service.py\nclass DatabaseBackupFile:\n \"\"\"\n A representation of a lute backup file to hold metadata attributes.\n \"\"\"\n\n def __init__(self, filepath: Union[str, os.PathLike]):\n if not os.path.exists(filepath):\n raise BackupException(f\"No backup file at {filepath}.\")\n\n name = os.path.basename(filepath)\n if not re.match(r\"(manual_)?lute_backup_\", name):\n raise BackupException(f\"Not a valid lute database backup at {filepath}.\")\n\n self.filepath = filepath\n self.name = name\n self.is_manual = self.name.startswith(\"manual_\")\n\n def __lt__(self, other):\n return self.last_modified < other.last_modified\n\n @property\n def last_modified(self) -> datetime:\n return datetime.fromtimestamp(os.path.getmtime(self.filepath)).astimezone()\n\n @property\n def size_bytes(self) -> int:\n return os.path.getsize(self.filepath)\n\n @property\n def size(self) -> str:\n \"\"\"\n A human-readable string representation of the size of the file.\n\n Eg.\n 1746 bytes\n 4 kB\n 27 MB\n \"\"\"\n s = self.size_bytes\n if s >= 1e9:\n return f\"{round(s * 1e-9)} GB\"\n if s >= 1e6:\n return f\"{round(s * 1e-6)} MB\"\n if s >= 1e3:\n return f\"{round(s * 1e-3)} KB\"\n return f\"{s} bytes\"", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 1383}, "tests/unit/book/test_service.py::44": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py", "lute/book/model.py", "lute/book/service.py"], "used_names": ["Book", "BookRepository", "Service", "db", "os"], "enclosing_function": "test_create_book_from_file_paths", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/repositories.py\nclass BookRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, book_id):\n \"Get by ID.\"\n return self.session.query(Book).filter(Book.id == book_id).first()\n\n def find_by_title(self, book_title, language_id):\n \"Get by title.\"\n return (\n self.session.query(Book)\n .filter(and_(Book.title == book_title, Book.language_id == language_id))\n .first()\n )\n\n\n# Source: lute/book/model.py\nclass Book: # pylint: disable=too-many-instance-attributes\n \"\"\"\n A book domain object, to create/edit lute.models.book.Books.\n\n Book language can be specified either by language_id, or\n language_name. language_name is useful for loading books via\n scripts/api. language_id takes precedence.\n \"\"\"\n\n def __init__(self):\n self.id = None\n self.language_id = None\n self.language_name = None\n self.title = None\n self.text = None\n self.source_uri = None\n self.audio_filename = None\n self.audio_current_pos = None\n self.audio_bookmarks = None\n self.book_tags = []\n\n self.threshold_page_tokens = 250\n self.split_by = \"paragraphs\"\n\n # The source file used for the book text.\n # Overrides the self.text if not None.\n self.text_source_path = None\n\n self.text_stream = None\n self.text_stream_filename = None\n\n # The source file used for audio.\n self.audio_source_path = None\n\n self.audio_stream = None\n self.audio_stream_filename = None\n\n def __repr__(self):\n return f\"\"\n\n def add_tag(self, tag):\n self.book_tags.append(tag)\n\n\n# Source: lute/book/service.py\nclass Service:\n \"Service.\"\n\n def _unique_fname(self, filename):\n \"\"\"\n Return secure name pre-pended with datetime string.\n \"\"\"\n current_datetime = datetime.now()\n formatted_datetime = current_datetime.strftime(\"%Y%m%d_%H%M%S\")\n _, ext = os.path.splitext(filename)\n ext = (ext or \"\").lower()\n newfilename = uuid.uuid4().hex\n return f\"{formatted_datetime}_{newfilename}{ext}\"\n\n def save_audio_file(self, audio_file_field_data):\n \"\"\"\n Save the file to disk, return its filename.\n \"\"\"\n filename = self._unique_fname(audio_file_field_data.filename)\n fp = os.path.join(current_app.env_config.useraudiopath, filename)\n audio_file_field_data.save(fp)\n return filename\n\n def book_data_from_url(self, url):\n \"\"\"\n Parse the url and load source data for a new Book.\n This returns a domain object, as the book is still unparsed.\n \"\"\"\n s = None\n try:\n timeout = 20 # seconds\n response = requests.get(url, timeout=timeout)\n response.raise_for_status()\n s = response.text\n except requests.exceptions.RequestException as e:\n msg = f\"Could not parse {url} (error: {str(e)})\"\n raise BookImportException(message=msg, cause=e) from e\n\n soup = BeautifulSoup(s, \"html.parser\")\n extracted_text = []\n\n # Add elements in order found.\n for element in soup.descendants:\n if element.name in (\"h1\", \"h2\", \"h3\", \"h4\", \"p\"):\n extracted_text.append(element.text)\n\n title_node = soup.find(\"title\")\n orig_title = title_node.string if title_node else url\n\n short_title = orig_title[:150]\n if len(orig_title) > 150:\n short_title += \" ...\"\n\n b = BookDataFromUrl()\n b.title = short_title\n b.source_uri = url\n b.text = \"\\n\\n\".join(extracted_text)\n return b\n\n def import_book(self, book, session):\n \"\"\"\n Save the book as a dbbook, parsing and saving files as needed.\n Returns new book created.\n \"\"\"\n\n def _raise_if_file_missing(p, fldname):\n if not os.path.exists(p):\n raise BookImportException(f\"Missing file {p} given in {fldname}\")\n\n def _raise_if_none(p, fldname):\n if p is None:\n raise BookImportException(f\"Must set {fldname}\")\n\n fte = FileTextExtraction()\n if book.text_source_path:\n _raise_if_file_missing(book.text_source_path, \"text_source_path\")\n tsp = book.text_source_path\n with open(tsp, mode=\"rb\") as stream:\n book.text = fte.get_file_content(tsp, stream)\n\n if book.text_stream:\n _raise_if_none(book.text_stream_filename, \"text_stream_filename\")\n book.text = fte.get_file_content(\n book.text_stream_filename, book.text_stream\n )\n\n if book.audio_source_path:\n _raise_if_file_missing(book.audio_source_path, \"audio_source_path\")\n newname = self._unique_fname(book.audio_source_path)\n fp = os.path.join(current_app.env_config.useraudiopath, newname)\n shutil.copy(book.audio_source_path, fp)\n book.audio_filename = newname\n\n if book.audio_stream:\n _raise_if_none(book.audio_stream_filename, \"audio_stream_filename\")\n newname = self._unique_fname(book.audio_stream_filename)\n fp = os.path.join(current_app.env_config.useraudiopath, newname)\n with open(fp, mode=\"wb\") as fcopy: # Use \"wb\" to write in binary mode\n while chunk := book.audio_stream.read(\n 8192\n ): # Read the stream in chunks (e.g., 8 KB)\n fcopy.write(chunk)\n book.audio_filename = newname\n\n repo = Repository(session)\n dbbook = repo.add(book)\n repo.commit()\n return dbbook", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 5888}, "plugins/lute-mandarin/tests/test_MandarinParser.py::100": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["MandarinParser"], "enclosing_function": "test_readings", "extracted_code": "", "n_imports_parsed": 6, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/read/render/test_multiword_indexer.py::44": {"resolved_imports": ["lute/read/render/multiword_indexer.py"], "used_names": ["MultiwordTermIndexer", "pytest"], "enclosing_function": "test_scenario", "extracted_code": "# Source: lute/read/render/multiword_indexer.py\nclass MultiwordTermIndexer:\n \"\"\"\n Find terms in strings using ahocorapy.\n \"\"\"\n\n zws = \"\\u200B\" # zero-width space\n\n def __init__(self):\n self.kwtree = KeywordTree(case_insensitive=True)\n self.finalized = False\n\n def add(self, t):\n \"Add zws-enclosed term to tree.\"\n add_t = f\"{self.zws}{t}{self.zws}\"\n self.kwtree.add(add_t)\n\n def search_all(self, lc_tokens):\n \"Find all terms and starting token index.\"\n if not self.finalized:\n self.kwtree.finalize()\n self.finalized = True\n\n zws = self.zws\n content = zws + zws.join(lc_tokens) + zws\n zwsindexes = [i for i, char in enumerate(content) if char == zws]\n results = self.kwtree.search_all(content)\n\n for result in results:\n # print(f\"{result}\\n\", flush=True)\n t = result[0].strip(zws)\n charpos = result[1]\n index = zwsindexes.index(charpos)\n yield (t, index)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1035}, "tests/orm/test_Text.py::53": {"resolved_imports": ["lute/models/book.py", "lute/db/__init__.py"], "used_names": ["Book", "Text", "TextBookmark", "WordsRead", "assert_record_count_equals", "datetime", "db"], "enclosing_function": "test_delete_text_cascade_deletes_bookmarks_leaves_wordsread", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass Text(db.Model):\n \"\"\"\n Each page in a Book.\n \"\"\"\n\n __tablename__ = \"texts\"\n\n id = db.Column(\"TxID\", db.Integer, primary_key=True)\n _text = db.Column(\"TxText\", db.String, nullable=False)\n order = db.Column(\"TxOrder\", db.Integer)\n start_date = db.Column(\"TxStartDate\", db.DateTime, nullable=True)\n _read_date = db.Column(\"TxReadDate\", db.DateTime, nullable=True)\n bk_id = db.Column(\"TxBkID\", db.Integer, db.ForeignKey(\"books.BkID\"), nullable=False)\n word_count = db.Column(\"TxWordCount\", db.Integer, nullable=True)\n\n book = db.relationship(\"Book\", back_populates=\"texts\")\n bookmarks = db.relationship(\n \"TextBookmark\",\n back_populates=\"text\",\n cascade=\"all, delete-orphan\",\n )\n sentences = db.relationship(\n \"Sentence\",\n back_populates=\"text\",\n order_by=\"Sentence.order\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, book, text, order=1):\n self.book = book\n self.text = text\n self.order = order\n self.sentences = []\n\n @property\n def title(self):\n \"\"\"\n Text title is the book title + page fraction.\n \"\"\"\n b = self.book\n s = f\"({self.order}/{self.book.page_count})\"\n t = f\"{b.title} {s}\"\n return t\n\n @property\n def text(self):\n return self._text\n\n @text.setter\n def text(self, s):\n self._text = s\n if s.strip() == \"\":\n return\n toks = self._get_parsed_tokens()\n wordtoks = [t for t in toks if t.is_word]\n self.word_count = len(wordtoks)\n if self._read_date is not None:\n self._load_sentences_from_tokens(toks)\n\n @property\n def read_date(self):\n return self._read_date\n\n @read_date.setter\n def read_date(self, s):\n self._read_date = s\n # Ensure loaded.\n self.load_sentences()\n\n def _get_parsed_tokens(self):\n \"Return the tokens.\"\n lang = self.book.language\n return lang.parser.get_parsed_tokens(self.text, lang)\n\n def _load_sentences_from_tokens(self, parsedtokens):\n \"Save sentences using the tokens.\"\n parser = self.book.language.parser\n self._remove_sentences()\n curr_sentence_tokens = []\n sentence_num = 1\n\n def _add_current():\n \"Create and add sentence from current state.\"\n if curr_sentence_tokens:\n se = Sentence.from_tokens(curr_sentence_tokens, parser, sentence_num)\n self._add_sentence(se)\n # Reset for the next sentence.\n curr_sentence_tokens.clear()\n\n for pt in parsedtokens:\n curr_sentence_tokens.append(pt)\n if pt.is_end_of_sentence:\n _add_current()\n sentence_num += 1\n\n # Add any stragglers.\n _add_current()\n\n def load_sentences(self):\n \"\"\"\n Parse the current text and create Sentence objects.\n \"\"\"\n toks = self._get_parsed_tokens()\n self._load_sentences_from_tokens(toks)\n\n def _add_sentence(self, sentence):\n \"Add a sentence to the Text.\"\n if sentence not in self.sentences:\n self.sentences.append(sentence)\n sentence.text = self\n\n def _remove_sentences(self):\n \"Remove all sentence from the Text.\"\n for sentence in self.sentences:\n sentence.text = None\n self.sentences = []\n\nclass WordsRead(db.Model):\n \"\"\"\n Tracks reading events for Text entities.\n \"\"\"\n\n __tablename__ = \"wordsread\"\n id = db.Column(\"WrID\", db.Integer, primary_key=True)\n language_id = db.Column(\n \"WrLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n tx_id = db.Column(\n \"WrTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"SET NULL\"),\n nullable=True,\n )\n read_date = db.Column(\"WrReadDate\", db.DateTime, nullable=False)\n word_count = db.Column(\"WrWordCount\", db.Integer, nullable=False)\n\n def __init__(self, text, read_date, word_count):\n self.tx_id = text.id\n self.language_id = text.book.language.id\n self.read_date = read_date\n self.word_count = word_count\n\nclass TextBookmark(db.Model):\n \"\"\"\n Bookmarks for a given Book page\n\n The TextBookmark includes a title\n \"\"\"\n\n __tablename__ = \"textbookmarks\"\n\n id = db.Column(\"TbID\", db.Integer, primary_key=True)\n tx_id = db.Column(\n \"TbTxID\",\n db.Integer,\n db.ForeignKey(\"texts.TxID\", ondelete=\"CASCADE\"),\n nullable=False,\n )\n title = db.Column(\"TbTitle\", db.Text, nullable=False)\n\n text = db.relationship(\"Text\", back_populates=\"bookmarks\")\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 8481}, "tests/unit/backup/test_backup.py::102": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["Service", "db", "os"], "enclosing_function": "test_backup_writes_file_to_output_dir", "extracted_code": "# Source: lute/backup/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def create_backup(self, app_config, settings, is_manual=False, suffix=None):\n \"\"\"\n Create backup using current app config, settings.\n\n is_manual is True if this is a user-triggered manual\n backup, otherwise is False.\n\n suffix can be specified for test.\n\n settings are from BackupSettings.\n - backup_enabled\n - backup_dir\n - backup_auto\n - backup_warn\n - backup_count\n - last_backup_datetime\n \"\"\"\n if not os.path.exists(settings.backup_dir):\n raise BackupException(\"Missing directory \" + settings.backup_dir)\n\n # def _print_now(msg):\n # \"Timing helper for when implement audio backup.\"\n # now = datetime.now().strftime(\"%H-%M-%S\")\n # print(f\"{now} - {msg}\", flush=True)\n\n self._mirror_images_dir(app_config.userimagespath, settings.backup_dir)\n\n prefix = \"manual_\" if is_manual else \"\"\n if suffix is None:\n suffix = datetime.now().strftime(\"%Y-%m-%d_%H%M%S\")\n fname = f\"{prefix}lute_backup_{suffix}.db\"\n backupfile = os.path.join(settings.backup_dir, fname)\n\n f = self._create_db_backup(app_config.dbfilename, backupfile)\n self._remove_excess_backups(settings.backup_count, settings.backup_dir)\n return f\n\n def should_run_auto_backup(self, backup_settings):\n \"\"\"\n True (if applicable) if last backup was old.\n \"\"\"\n bs = backup_settings\n if bs.backup_enabled is False or bs.backup_auto is False:\n return False\n\n last = bs.last_backup_datetime\n if last is None:\n return True\n\n curr = int(time.time())\n diff = curr - last\n return diff > 24 * 60 * 60\n\n def backup_warning(self, backup_settings):\n \"Get warning if needed.\"\n if not backup_settings.backup_warn:\n return \"\"\n\n have_books = self.session.query(self.session.query(Book).exists()).scalar()\n have_terms = self.session.query(self.session.query(Term).exists()).scalar()\n if have_books is False and have_terms is False:\n return \"\"\n\n last = backup_settings.last_backup_datetime\n if last is None:\n return \"Never backed up.\"\n\n curr = int(time.time())\n diff = curr - last\n old_backup_msg = \"Last backup was more than 1 week ago.\"\n if diff > 7 * 24 * 60 * 60:\n return old_backup_msg\n\n return \"\"\n\n def _create_db_backup(self, dbfilename, backupfile):\n \"Make a backup.\"\n shutil.copy(dbfilename, backupfile)\n f = f\"{backupfile}.gz\"\n with open(backupfile, \"rb\") as in_file, gzip.open(\n f, \"wb\", compresslevel=4\n ) as out_file:\n shutil.copyfileobj(in_file, out_file)\n os.remove(backupfile)\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n return f\n\n def skip_this_backup(self):\n \"Set the last backup time to today.\"\n r = UserSettingRepository(self.session)\n r.set_last_backup_datetime(int(time.time()))\n\n def _remove_excess_backups(self, count, outdir):\n \"Remove old backups.\"\n files = [f for f in self.list_backups(outdir) if not f.is_manual]\n files.sort(reverse=True)\n to_remove = files[count:]\n for f in to_remove:\n os.remove(f.filepath)\n\n def _mirror_images_dir(self, userimagespath, outdir):\n \"Copy the images to backup.\"\n target_dir = os.path.join(outdir, \"userimages_backup\")\n target_dir = os.path.abspath(target_dir)\n if not os.path.exists(target_dir):\n os.mkdir(target_dir)\n shutil.copytree(userimagespath, target_dir, dirs_exist_ok=True)\n\n def list_backups(self, outdir) -> List[DatabaseBackupFile]:\n \"List all backup files.\"\n return [\n DatabaseBackupFile(os.path.join(outdir, f))\n for f in os.listdir(outdir)\n if re.match(r\"(manual_)?lute_backup_\", f)\n ]\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 6395}, "tests/unit/cli/test_language_term_export.py::71": {"resolved_imports": ["lute/cli/language_term_export.py", "lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/db/demo.py"], "used_names": ["Term", "TermRepository", "db"], "enclosing_function": "_find", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 5, "n_chars_extracted": 8558}, "tests/orm/test_Term.py::177": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_replace_remove_image", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/parse/test_SpaceDelimitedParser.py::148": {"resolved_imports": ["lute/parse/space_delimited_parser.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_quick_checks", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/features/test_term_import.py::96": {"resolved_imports": ["lute/db/__init__.py", "lute/models/language.py", "lute/language/service.py", "lute/models/term.py", "lute/models/repositories.py", "lute/termimport/service.py"], "used_names": ["parsers", "then"], "enclosing_function": "succeed_with_status", "extracted_code": "", "n_imports_parsed": 11, "n_files_resolved": 6, "n_chars_extracted": 0}, "tests/unit/ankiexport/test_field_mapping.py::137": {"resolved_imports": ["lute/ankiexport/exceptions.py", "lute/ankiexport/field_mapping.py"], "used_names": ["Mock", "get_values_and_media_mapping"], "enclosing_function": "test_filtered_tag_replacements", "extracted_code": "# Source: lute/ankiexport/field_mapping.py\ndef get_values_and_media_mapping(term, sentence_lookup, mapping):\n \"\"\"\n Get the value replacements to be put in the mapping, and build\n dict of new filenames to original filenames.\n \"\"\"\n\n def all_translations():\n ret = [term.translation or \"\"]\n for p in term.parents:\n if p.translation not in ret:\n ret.append(p.translation or \"\")\n return [r for r in ret if r.strip() != \"\"]\n\n def parse_keys_needing_calculation(calculate_keys, media_mappings):\n \"\"\"\n Build a parser for some keys in the mapping string, return\n calculated value to use in the mapping. SIDE EFFECT:\n adds ankiconnect post actions to post_actions if needed\n (e.g. for image uploads).\n\n e.g. the mapping \"article: { tags:[\"der\", \"die\", \"das\"] }\"\n needs to be parsed to extract certain tags from the current\n term.\n \"\"\"\n\n def _filtered_tags_in_term_list(term_list, tagvals):\n \"Get all unique tags.\"\n # tagvals is a pyparsing ParseResults, use list() to convert to strings.\n ttext = [tt.text for t in term_list for tt in t.term_tags]\n ttext = sorted(list(set(ttext)))\n ftags = [tt for tt in ttext if tt in list(tagvals)]\n return \", \".join(ftags)\n\n def get_filtered_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list([term], tagvals)\n\n def get_filtered_parents_tags(tagvals):\n \"Get term tags matching the list.\"\n return _filtered_tags_in_term_list(term.parents, tagvals)\n\n def handle_image(_):\n id_images = [\n (t, t.get_current_image())\n for t in _all_terms(term)\n if t.get_current_image() is not None\n ]\n image_srcs = []\n for t, imgfilename in id_images:\n new_filename = f\"LUTE_TERM_{t.id}.jpg\"\n image_url = f\"/userimages/{t.language.id}/{imgfilename}\"\n media_mappings[new_filename] = image_url\n image_srcs.append(f'')\n\n return \"\".join(image_srcs)\n\n def handle_sentences(_):\n \"Get sample sentence for term.\"\n if term.id is None:\n # Dummy parse.\n return \"\"\n return sentence_lookup.get_sentence_for_term(term.id)\n\n quotedString.setParseAction(pp.removeQuotes)\n tagvallist = Suppress(\"[\") + pp.delimitedList(quotedString) + Suppress(\"]\")\n tagcrit = tagvallist | QuotedString(quoteChar='\"')\n tag_matcher = Suppress(Literal(\"tags\") + Literal(\":\")) + tagcrit\n parents_tag_matcher = Suppress(Literal(\"parents.tags\") + Literal(\":\")) + tagcrit\n\n image = Suppress(\"image\")\n sentence = Suppress(\"sentence\")\n\n matcher = (\n tag_matcher.set_parse_action(get_filtered_tags)\n | parents_tag_matcher.set_parse_action(get_filtered_parents_tags)\n | image.set_parse_action(handle_image)\n | sentence.set_parse_action(handle_sentences)\n )\n\n calc_replacements = {\n # Matchers return the value that should be used as the\n # replacement value for the given mapping string. e.g.\n # tags[\"der\", \"die\"] returns \"der\" if term.tags = [\"der\", \"x\"]\n k: matcher.parseString(k).asList()[0]\n for k in calculate_keys\n }\n\n return calc_replacements\n\n def remove_zws(replacements_dict):\n cleaned = {}\n for key, value in replacements_dict.items():\n if isinstance(value, str):\n cleaned[key] = value.replace(\"\\u200B\", \"\")\n else:\n cleaned[key] = value\n return cleaned\n\n # One-for-one replacements in the mapping string.\n # e.g. \"{ id }\" is replaced by term.termid.\n replacements = {\n \"id\": term.id,\n \"term\": term.text,\n \"language\": term.language.name,\n \"parents\": \", \".join([p.text for p in term.parents]),\n \"tags\": \", \".join(sorted({tt.text for tt in term.term_tags})),\n \"translation\": \"
\".join(all_translations()),\n \"pronunciation\": term.romanization,\n \"parents.pronunciation\": \", \".join(\n [p.romanization or \"\" for p in term.parents]\n ),\n }\n\n mapping_string = \"; \".join(mapping.values())\n calc_keys = [\n k\n for k in set(re.findall(r\"{\\s*(.*?)\\s*}\", mapping_string))\n if k not in replacements\n ]\n\n media_mappings = {}\n calc_replacements = parse_keys_needing_calculation(calc_keys, media_mappings)\n\n final_replacements = {**replacements, **calc_replacements}\n cleaned = remove_zws(final_replacements)\n return (cleaned, media_mappings)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 4848}, "tests/orm/test_Book.py::107": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["Book", "BookStats", "db"], "enclosing_function": "test_load_book_loads_lang", "extracted_code": "# Source: lute/models/book.py\nclass Book(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Book entity.\n \"\"\"\n\n __tablename__ = \"books\"\n\n id = db.Column(\"BkID\", db.SmallInteger, primary_key=True)\n title = db.Column(\"BkTitle\", db.String(length=200))\n language_id = db.Column(\n \"BkLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n source_uri = db.Column(\"BkSourceURI\", db.String(length=1000))\n current_tx_id = db.Column(\"BkCurrentTxID\", db.Integer, default=0)\n archived = db.Column(\"BkArchived\", db.Boolean, default=False)\n\n audio_filename = db.Column(\"BkAudioFilename\", db.String)\n audio_current_pos = db.Column(\"BkAudioCurrentPos\", db.Float)\n audio_bookmarks = db.Column(\"BkAudioBookmarks\", db.String)\n\n language = db.relationship(\"Language\")\n texts = db.relationship(\n \"Text\",\n back_populates=\"book\",\n order_by=\"Text.order\",\n cascade=\"all, delete-orphan\",\n )\n book_tags = db.relationship(\"BookTag\", secondary=\"booktags\")\n\n def __init__(self, title=None, language=None, source_uri=None):\n self.title = title\n self.language = language\n self.source_uri = source_uri\n self.texts = []\n self.book_tags = []\n\n def __repr__(self):\n return f\"\"\n\n def remove_all_book_tags(self):\n self.book_tags = []\n\n def add_book_tag(self, book_tag):\n if book_tag not in self.book_tags:\n self.book_tags.append(book_tag)\n\n def remove_book_tag(self, book_tag):\n self.book_tags.remove(book_tag)\n\n @property\n def page_count(self):\n return len(self.texts)\n\n def page_in_range(self, n):\n \"Return page number that is in the book's page count.\"\n ret = max(n, 1)\n ret = min(ret, self.page_count)\n return ret\n\n def text_at_page(self, n):\n \"Return the text object at page n.\"\n pagenum = self.page_in_range(n)\n return self.texts[pagenum - 1]\n\n def _add_page(self, new_pagenum):\n \"Add new page, increment other page orders.\"\n pages_after = [t for t in self.texts if t.order >= new_pagenum]\n for t in pages_after:\n t.order = t.order + 1\n t = Text(None, \"\", new_pagenum)\n # TODO fix_refs: None first arg is garbage code. Passing self\n # as the text's book causes a \"SAWarning: Object of type\n # not in session, add operation along 'Book.texts' will\n # not proceed\" warning ... so adding the text to the book\n # manually is needed. The book's language is required to\n # correctly parse the Text's text though ...\n self.texts.append(t)\n return t\n\n def add_page_before(self, pagenum):\n \"Add page before page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum))\n\n def add_page_after(self, pagenum):\n \"Add page after page n, renumber all subsequent pages, return new page.\"\n return self._add_page(self.page_in_range(pagenum) + 1)\n\n def remove_page(self, pagenum):\n \"Remove page, renumber all subsequent pages.\"\n # Don't delete page of single-page books.\n if len(self.texts) == 1:\n return\n texts = [t for t in self.texts if t.order == pagenum]\n if len(texts) == 0:\n return\n texts[0].book = None\n pages_after = [t for t in self.texts if t.order > pagenum]\n for t in pages_after:\n t.order = t.order - 1\n\n @property\n def is_supported(self):\n \"True if the book's language's parser is supported.\"\n return self.language.is_supported\n\nclass BookStats(db.Model):\n \"The stats table.\"\n __tablename__ = \"bookstats\"\n\n BkID = db.Column(db.Integer, primary_key=True)\n distinctterms = db.Column(db.Integer)\n distinctunknowns = db.Column(db.Integer)\n unknownpercent = db.Column(db.Integer)\n status_distribution = db.Column(db.String, nullable=True)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 4102}, "tests/unit/themes/test_service.py::16": {"resolved_imports": ["lute/themes/service.py", "lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["Service", "db"], "enclosing_function": "test_list_themes", "extracted_code": "# Source: lute/themes/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _css_path(self):\n \"\"\"\n Path to css in this folder.\n \"\"\"\n thisdir = os.path.dirname(__file__)\n theme_dir = os.path.join(thisdir, \"css\")\n return os.path.abspath(theme_dir)\n\n def list_themes(self):\n \"\"\"\n List of theme file names and user-readable name.\n \"\"\"\n\n def _make_display_name(s):\n ret = os.path.basename(s)\n ret = ret.replace(\".css\", \"\").replace(\"_\", \" \")\n return ret\n\n g = glob(os.path.join(self._css_path(), \"*.css\"))\n themes = [(os.path.basename(f), _make_display_name(f)) for f in g]\n theme_basenames = [t[0] for t in themes]\n\n g = glob(os.path.join(current_app.env_config.userthemespath, \"*.css\"))\n additional_user_themes = [\n (os.path.basename(f), _make_display_name(f))\n for f in g\n if os.path.basename(f) not in theme_basenames\n ]\n\n themes += additional_user_themes\n sorted_themes = sorted(themes, key=lambda x: x[1])\n return [default_entry] + sorted_themes\n\n def get_current_css(self):\n \"\"\"\n Return the current css pointed at by the current_theme user setting.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n if current_theme == default_entry[0]:\n return \"\"\n\n def _get_theme_css_in_dir(d):\n \"Get css, or '' if no file.\"\n fname = os.path.join(d, current_theme)\n if not os.path.exists(fname):\n return \"\"\n with open(fname, \"r\", encoding=\"utf-8\") as f:\n return f.read()\n\n ret = _get_theme_css_in_dir(self._css_path())\n add = _get_theme_css_in_dir(current_app.env_config.userthemespath)\n if add != \"\":\n ret += f\"\\n\\n/* Additional user css */\\n\\n{add}\"\n return ret\n\n def next_theme(self):\n \"\"\"\n Move to the next theme in the list of themes.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n themes = [t[0] for t in self.list_themes()]\n themes.append(default_entry[0])\n for i in range(0, len(themes)): # pylint: disable=consider-using-enumerate\n if themes[i] == current_theme:\n new_index = i + 1\n break\n repo.set_value(\"current_theme\", themes[new_index])\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2663}, "tests/unit/book/test_Repository.py::166": {"resolved_imports": ["lute/db/__init__.py", "lute/book/model.py"], "used_names": [], "enclosing_function": "test_get_tags", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/term/test_service_bulk_updates.py::119": {"resolved_imports": ["lute/models/repositories.py", "lute/models/term.py", "lute/db/__init__.py", "lute/term/service.py"], "used_names": ["BulkTermUpdateData", "add_terms"], "enclosing_function": "test_set_status", "extracted_code": "# Source: lute/term/service.py\nclass BulkTermUpdateData:\n \"Bulk updates\"\n term_ids: List[int] = field(default_factory=list)\n lowercase_terms: bool = False\n remove_parents: bool = False\n parent_id: Optional[int] = None\n parent_text: Optional[str] = None\n change_status: bool = False\n status_value: Optional[int] = None\n add_tags: List[str] = field(default_factory=list)\n remove_tags: List[str] = field(default_factory=list)", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 452}, "plugins/_template_/tests/test_LangNameParser.py::20": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": [], "enclosing_function": "test_dummy_test", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/unit/models/test_Term.py::225": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Term", "TermImage", "TermRepository", "assert_sql_result", "db"], "enclosing_function": "test_delete_empty_image_records", "extracted_code": "# Source: lute/models/term.py\nclass TermImage(db.Model):\n \"Term images.\"\n __tablename__ = \"wordimages\"\n\n id = db.Column(\"WiID\", db.Integer, primary_key=True)\n term_id = db.Column(\n \"WiWoID\", db.Integer, db.ForeignKey(\"words.WoID\"), nullable=False\n )\n term = db.relationship(\"Term\", back_populates=\"images\")\n source = db.Column(\"WiSource\", db.String(500))\n\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/models/repositories.py\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 8912}, "tests/unit/themes/test_service.py::27": {"resolved_imports": ["lute/themes/service.py", "lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["Service", "UserSettingRepository", "db"], "enclosing_function": "test_default_theme_is_blank_css", "extracted_code": "# Source: lute/themes/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _css_path(self):\n \"\"\"\n Path to css in this folder.\n \"\"\"\n thisdir = os.path.dirname(__file__)\n theme_dir = os.path.join(thisdir, \"css\")\n return os.path.abspath(theme_dir)\n\n def list_themes(self):\n \"\"\"\n List of theme file names and user-readable name.\n \"\"\"\n\n def _make_display_name(s):\n ret = os.path.basename(s)\n ret = ret.replace(\".css\", \"\").replace(\"_\", \" \")\n return ret\n\n g = glob(os.path.join(self._css_path(), \"*.css\"))\n themes = [(os.path.basename(f), _make_display_name(f)) for f in g]\n theme_basenames = [t[0] for t in themes]\n\n g = glob(os.path.join(current_app.env_config.userthemespath, \"*.css\"))\n additional_user_themes = [\n (os.path.basename(f), _make_display_name(f))\n for f in g\n if os.path.basename(f) not in theme_basenames\n ]\n\n themes += additional_user_themes\n sorted_themes = sorted(themes, key=lambda x: x[1])\n return [default_entry] + sorted_themes\n\n def get_current_css(self):\n \"\"\"\n Return the current css pointed at by the current_theme user setting.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n if current_theme == default_entry[0]:\n return \"\"\n\n def _get_theme_css_in_dir(d):\n \"Get css, or '' if no file.\"\n fname = os.path.join(d, current_theme)\n if not os.path.exists(fname):\n return \"\"\n with open(fname, \"r\", encoding=\"utf-8\") as f:\n return f.read()\n\n ret = _get_theme_css_in_dir(self._css_path())\n add = _get_theme_css_in_dir(current_app.env_config.userthemespath)\n if add != \"\":\n ret += f\"\\n\\n/* Additional user css */\\n\\n{add}\"\n return ret\n\n def next_theme(self):\n \"\"\"\n Move to the next theme in the list of themes.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n themes = [t[0] for t in self.list_themes()]\n themes.append(default_entry[0])\n for i in range(0, len(themes)): # pylint: disable=consider-using-enumerate\n if themes[i] == current_theme:\n new_index = i + 1\n break\n repo.set_value(\"current_theme\", themes[new_index])\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/repositories.py\nclass UserSettingRepository(SettingRepositoryBase):\n \"Repository.\"\n\n def __init__(self, session):\n super().__init__(session, UserSetting)\n\n def key_exists_precheck(self, keyname):\n \"\"\"\n User keys must exist.\n \"\"\"\n if not self.key_exists(keyname):\n raise MissingUserSettingKeyException(keyname)\n\n def get_backup_settings(self):\n \"Convenience method.\"\n bs = BackupSettings()\n\n def _bool(v):\n return v in (1, \"1\", \"y\", True)\n\n bs.backup_enabled = _bool(self.get_value(\"backup_enabled\"))\n bs.backup_auto = _bool(self.get_value(\"backup_auto\"))\n bs.backup_warn = _bool(self.get_value(\"backup_warn\"))\n bs.backup_dir = self.get_value(\"backup_dir\")\n bs.backup_count = int(self.get_value(\"backup_count\") or 5)\n bs.last_backup_datetime = self.get_last_backup_datetime()\n return bs\n\n def get_last_backup_datetime(self):\n \"Get the last_backup_datetime as int, or None.\"\n v = self.get_value(\"lastbackup\")\n if v is None:\n return None\n return int(v)\n\n def set_last_backup_datetime(self, v):\n \"Set and save the last backup time.\"\n self.set_value(\"lastbackup\", v)\n self.session.commit()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 3977}, "tests/orm/test_Book.py::37": {"resolved_imports": ["lute/models/book.py", "lute/read/service.py", "lute/book/stats.py", "lute/db/__init__.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_save_book", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 47}, "tests/orm/test_Term.py::214": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_remove_flash_message", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/models/test_Term.py::263": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "datetime", "db", "text"], "enclosing_function": "test_changing_status_of_status_0_term_resets_WoCreated", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 7471}, "tests/orm/test_Language.py::85": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["Language", "LanguageDictionary", "LanguageRepository", "assert_sql_result", "db", "json"], "enclosing_function": "test_language_dictionaries_smoke_test", "extracted_code": "# Source: lute/models/language.py\nclass LanguageDictionary(db.Model):\n \"\"\"\n Language dictionary.\n \"\"\"\n\n __tablename__ = \"languagedicts\"\n\n id = db.Column(\"LdID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\n \"LdLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n language = db.relationship(\"Language\", back_populates=\"dictionaries\")\n usefor = db.Column(\"LdUseFor\", db.String(20), nullable=False)\n dicttype = db.Column(\"LdType\", db.String(20), nullable=False)\n dicturi = db.Column(\"LdDictURI\", db.String(200), nullable=False)\n is_active = db.Column(\"LdIsActive\", db.Boolean, default=True)\n sort_order = db.Column(\"LdSortOrder\", db.SmallInteger, nullable=False)\n\n # HACK: pre-pend '*' to URLs that need to open a new window.\n # This is a relic of the original code, and should be changed.\n # TODO remove-asterisk-hack: remove * from URL start.\n def make_uri(self):\n \"Hack add asterisk.\"\n prepend = \"*\" if self.dicttype == \"popuphtml\" else \"\"\n return f\"{prepend}{self.dicturi}\"\n\nclass Language(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Language entity.\n \"\"\"\n\n __tablename__ = \"languages\"\n\n id = db.Column(\"LgID\", db.SmallInteger, primary_key=True)\n name = db.Column(\"LgName\", db.String(40))\n\n dictionaries = db.relationship(\n \"LanguageDictionary\",\n back_populates=\"language\",\n order_by=\"LanguageDictionary.sort_order\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n\n character_substitutions = db.Column(\"LgCharacterSubstitutions\", db.String(500))\n regexp_split_sentences = db.Column(\"LgRegexpSplitSentences\", db.String(500))\n exceptions_split_sentences = db.Column(\"LgExceptionsSplitSentences\", db.String(500))\n _word_characters = db.Column(\"LgRegexpWordCharacters\", db.String(500))\n right_to_left = db.Column(\"LgRightToLeft\", db.Boolean)\n show_romanization = db.Column(\"LgShowRomanization\", db.Boolean)\n parser_type = db.Column(\"LgParserType\", db.String(20))\n\n def __init__(self):\n self.character_substitutions = \"´='|`='|’='|‘='|...=…|..=‥\"\n self.regexp_split_sentences = \".!?\"\n self.exceptions_split_sentences = \"Mr.|Mrs.|Dr.|[A-Z].|Vd.|Vds.\"\n self.word_characters = \"a-zA-ZÀ-ÖØ-öø-ȳáéíóúÁÉÍÓÚñÑ\"\n self.right_to_left = False\n self.show_romanization = False\n self.parser_type = \"spacedel\"\n self.dictionaries = []\n\n def __repr__(self):\n return f\"\"\n\n def _get_python_regex_pattern(self, s):\n \"\"\"\n Old Lute v2 ran in php, so the language word chars regex\n could look like this:\n\n x{0600}-x{06FF}x{FE70}-x{FEFC} (where x = backslash-x)\n\n This needs to be converted to the python equivalent, e.g.\n\n u0600-u06FFuFE70-uFEFC (where u = backslash-u)\n \"\"\"\n\n def convert_match(match):\n # Convert backslash-x{XXXX} to backslash-uXXXX\n hex_value = match.group(1)\n return f\"\\\\u{hex_value}\"\n\n ret = re.sub(r\"\\\\x{([0-9A-Fa-f]+)}\", convert_match, s)\n return ret\n\n @property\n def word_characters(self):\n return self._get_python_regex_pattern(self._word_characters)\n\n @word_characters.setter\n def word_characters(self, s):\n self._word_characters = self._get_python_regex_pattern(s)\n\n def active_dict_uris(self, use_for):\n \"Get sorted uris for active dicts of correct type.\"\n actives = [d for d in self.dictionaries if d.is_active and d.usefor == use_for]\n sorted_actives = sorted(actives, key=lambda x: x.sort_order)\n return [d.make_uri() for d in sorted_actives]\n\n @property\n def sentence_dict_uris(self):\n return self.active_dict_uris(\"sentences\")\n\n @property\n def parser(self):\n \"Note: this throws if the parser is not supported!!!\"\n return get_parser(self.parser_type)\n\n @property\n def is_supported(self):\n \"True if the language's parser is supported.\"\n return is_supported(self.parser_type)\n\n def get_parsed_tokens(self, s):\n return self.parser.get_parsed_tokens(s, self)\n\n def get_lowercase(self, s) -> str:\n return self.parser.get_lowercase(s)\n\n def to_dict(self):\n \"Return dictionary of data, for serialization.\"\n ret = {}\n ret[\"name\"] = self.name\n ret[\"dictionaries\"] = []\n for d in self.dictionaries:\n dd = {}\n dd[\"for\"] = d.usefor\n dd[\"type\"] = d.dicttype.replace(\"html\", \"\")\n dd[\"url\"] = d.dicturi\n dd[\"active\"] = d.is_active\n ret[\"dictionaries\"].append(dd)\n ret[\"show_romanization\"] = self.show_romanization\n ret[\"right_to_left\"] = self.right_to_left\n ret[\"parser_type\"] = self.parser_type\n ret[\"character_substitutions\"] = self.character_substitutions\n ret[\"split_sentences\"] = self.regexp_split_sentences\n ret[\"split_sentence_exceptions\"] = self.exceptions_split_sentences\n ret[\"word_chars\"] = self.word_characters\n return ret\n\n @staticmethod\n def from_dict(d):\n \"Create new Language from dictionary d.\"\n\n lang = Language()\n\n def load(key, method):\n if key in d:\n val = d[key]\n # Handle boolean values\n if isinstance(val, str):\n temp = val.lower()\n if temp == \"true\":\n val = True\n elif temp == \"false\":\n val = False\n setattr(lang, method, val)\n\n # Define mappings for fields\n mappings = {\n \"name\": \"name\",\n \"show_romanization\": \"show_romanization\",\n \"right_to_left\": \"right_to_left\",\n \"parser_type\": \"parser_type\",\n \"character_substitutions\": \"character_substitutions\",\n \"split_sentences\": \"regexp_split_sentences\",\n \"split_sentence_exceptions\": \"exceptions_split_sentences\",\n \"word_chars\": \"word_characters\",\n }\n\n for key in d.keys():\n funcname = mappings.get(key, \"\")\n if funcname:\n load(key, funcname)\n\n ld_sort = 1\n for ld_data in d[\"dictionaries\"]:\n dtype = ld_data[\"type\"]\n if dtype == \"embedded\":\n dtype = \"embeddedhtml\"\n elif dtype == \"popup\":\n dtype = \"popuphtml\"\n else:\n raise ValueError(f\"Invalid dictionary type {dtype}\")\n\n ld = LanguageDictionary()\n # ld.language = lang -- if you do this, the dict is added twice.\n ld.usefor = ld_data[\"for\"]\n ld.dicttype = dtype\n ld.dicturi = ld_data[\"url\"]\n ld.is_active = ld_data.get(\"active\", True)\n\n ld.sort_order = ld_sort\n ld_sort += 1\n lang.dictionaries.append(ld)\n\n return lang\n\n\n# Source: lute/models/repositories.py\nclass LanguageRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, language_id):\n \"Get by ID.\"\n return self.session.query(Language).filter(Language.id == language_id).first()\n\n def find_by_name(self, name):\n \"Get by name.\"\n return (\n self.session.query(Language)\n .filter(func.lower(Language.name) == func.lower(name))\n .first()\n )\n\n def all_dictionaries(self):\n \"All dictionaries for all languages.\"\n lang_dicts = {}\n for lang in db.session.query(Language).all():\n lang_dicts[lang.id] = {\n \"term\": lang.active_dict_uris(\"terms\"),\n \"sentence\": lang.active_dict_uris(\"sentences\"),\n }\n return lang_dicts\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 7952}, "tests/unit/models/test_Setting.py::139": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["patch"], "enclosing_function": "test_time_since_last_backup_in_past", "extracted_code": "", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/features/test_term_import.py::141": {"resolved_imports": ["lute/db/__init__.py", "lute/models/language.py", "lute/language/service.py", "lute/models/term.py", "lute/models/repositories.py", "lute/termimport/service.py"], "used_names": ["LanguageRepository", "Term", "TermRepository", "db", "parsers", "then"], "enclosing_function": "then_term_tags", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/models/repositories.py\nclass LanguageRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, language_id):\n \"Get by ID.\"\n return self.session.query(Language).filter(Language.id == language_id).first()\n\n def find_by_name(self, name):\n \"Get by name.\"\n return (\n self.session.query(Language)\n .filter(func.lower(Language.name) == func.lower(name))\n .first()\n )\n\n def all_dictionaries(self):\n \"All dictionaries for all languages.\"\n lang_dicts = {}\n for lang in db.session.query(Language).all():\n lang_dicts[lang.id] = {\n \"term\": lang.active_dict_uris(\"terms\"),\n \"sentence\": lang.active_dict_uris(\"sentences\"),\n }\n return lang_dicts\n\nclass TermRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, term_id):\n \"Get by ID.\"\n return self.session.query(Term).filter(Term.id == term_id).first()\n\n def find_by_spec(self, spec):\n \"\"\"\n Find by the given spec term's language ID and text.\n Returns None if not found.\n \"\"\"\n langid = spec.language.id\n text_lc = spec.text_lc\n query = self.session.query(Term).filter(\n and_(Term.language_id == langid, Term.text_lc == text_lc)\n )\n terms = query.all()\n if not terms:\n return None\n return terms[0]\n\n def delete_empty_images(self):\n \"\"\"\n Data clean-up: delete empty images.\n\n The code was leaving empty images in the db, which are obviously no good.\n This is a hack to clean up the data.\n \"\"\"\n sql = \"delete from wordimages where trim(WiSource) = ''\"\n self.session.execute(sqltext(sql))\n self.session.commit()", "n_imports_parsed": 11, "n_files_resolved": 6, "n_chars_extracted": 9377}, "tests/unit/book/test_stats.py::161": {"resolved_imports": ["lute/db/__init__.py", "lute/term/model.py", "lute/book/stats.py"], "used_names": ["assert_record_count_equals"], "enclosing_function": "test_get_stats_calculates_and_caches_stats", "extracted_code": "", "n_imports_parsed": 7, "n_files_resolved": 3, "n_chars_extracted": 0}, "tests/unit/term/test_Repository_sync_status.py::42": {"resolved_imports": ["lute/term/model.py", "lute/db/__init__.py"], "used_names": ["Repository", "assert_sql_result", "db"], "enclosing_function": "assert_statuses", "extracted_code": "# Source: lute/term/model.py\nclass Repository:\n \"\"\"\n Maps Term BO to and from lute.model.Term.\n \"\"\"\n\n def __init__(self, _session):\n self.session = _session\n\n # Identity map for business lookup.\n # Note that the same term is stored\n # a few times: by upper case or lower case text,\n # plus language ID.\n self.identity_map = {}\n\n def _id_map_key(self, langid, text):\n return f\"key-{langid}-{text}\"\n\n def _add_to_identity_map(self, t):\n \"Add found term to identity map.\"\n for txt in t.text, t.text_lc:\n k = self._id_map_key(t.language_id, txt)\n self.identity_map[k] = t\n\n def _search_identity_map(self, langid, txt):\n \"Search the map w/ the given bus. key.\"\n k = self._id_map_key(langid, txt)\n if k in self.identity_map:\n return self.identity_map[k]\n return None\n\n def load(self, term_id):\n \"Loads a Term business object for the DBTerm with the id.\"\n dbt = self.session.get(DBTerm, term_id)\n if dbt is None:\n raise ValueError(f\"No term with id {term_id} found\")\n term = self._build_business_term(dbt)\n self._add_to_identity_map(term)\n return term\n\n def _search_spec_term(self, langid, text):\n \"\"\"\n Make a term to get the correct text_lc to search for.\n This ensures that the spec term is properly parsed\n and downcased.\n \"\"\"\n lang_repo = LanguageRepository(self.session)\n lang = lang_repo.find(langid)\n return DBTerm(lang, text)\n\n def _find_by_spec(self, langid, text):\n \"Do a search using a spec term.\"\n spec = self._search_spec_term(langid, text)\n repo = TermRepository(self.session)\n return repo.find_by_spec(spec)\n\n def find(self, langid, text):\n \"\"\"\n Return a Term business object for the DBTerm with the langid and text.\n If no match, return None.\n \"\"\"\n term = self._search_identity_map(langid, text)\n if term is not None:\n return term\n\n dbt = self._find_by_spec(langid, text)\n if dbt is None:\n return None\n term = self._build_business_term(dbt)\n self._add_to_identity_map(term)\n return term\n\n def find_or_new(self, langid, text):\n \"\"\"\n Return a Term business object for the DBTerm with the langid and text.\n If no match, return a new term with the text and language.\n\n Note that this does a search by the **tokenized version**\n of the text; i.e., first the text argument is converted into\n a \"search specification\" (spec) using the language with the given id.\n The db search is then done using this spec. In most cases, this\n # will suffice.\n\n # In some cases, though, it may cause errors. The parsing here is done\n # without a fuller context, which in some language parsers can result\n # in different results. For example, the Japanese \"集めれ\" string can\n # can be parsed with mecab to return one unit (\"集めれ\") or two (\"集め/れ\"),\n # depending on context.\n\n # So what does this mean? It means that any context-less searches\n # for terms that have ambiguous parsing results will, themselves,\n # also be ambiguous. This impacts csv imports and term form usage.\n\n # For regular (reading screen) usage, it probably doesn't matter.\n # The terms in the reading screen are all created when the page is\n # opened, and so have ids assigned. With that, terms are not\n # searched by text match, they are only searched by id.\n\n ## TODO verify_identity_map_comment:\n If it's new, don't add to the identity map ... it's not saved yet,\n and so if we search for it again we should hit the db again.\n\n # the above statement about the identity map was old code, and I'm not\n # sure it's a valid statement/condition.\n \"\"\"\n t = self.find(langid, text)\n if t is not None:\n return t\n\n spec = self._search_spec_term(langid, text)\n t = Term()\n t.language_id = langid\n t.text = spec.text\n t.text_lc = spec.text_lc\n t.romanization = spec.language.parser.get_reading(text)\n t.original_text = spec.text\n\n # TODO verify_identity_map_comment\n # Adding the term to the map, even though it's new.\n self._add_to_identity_map(t)\n\n return t\n\n def find_matches(self, langid, text, max_results=50):\n \"\"\"\n Return array of Term business objects for the DBTerms\n with the same langid, matching the text.\n If no match, return [].\n \"\"\"\n spec = self._search_spec_term(langid, text)\n text_lc = spec.text_lc\n search = text_lc.strip() if text_lc else \"\"\n if search == \"\":\n return []\n\n sql_query = \"\"\"SELECT\n t.WoID as id,\n t.WoText as text,\n t.WoTextLC as text_lc,\n t.WoTranslation as translation,\n t.WoStatus as status,\n t.WoLgID as language_id,\n CASE WHEN wp.WpParentWoID IS NOT NULL THEN 1 ELSE 0 END AS has_children,\n CASE WHEN t.WoTextLC = :text_lc THEN 2\n WHEN t.WoTextLC LIKE :text_lc_starts_with THEN 1\n ELSE 0\n END as text_starts_with_search_string\n\n FROM words AS t\n LEFT JOIN (\n select WpParentWoID from wordparents group by WpParentWoID\n ) wp on wp.WpParentWoID = t.WoID\n\n WHERE t.WoLgID = :langid AND t.WoTextLC LIKE :text_lc_wildcard\n\n ORDER BY text_starts_with_search_string DESC, has_children DESC, t.WoTextLC\n LIMIT :max_results\n \"\"\"\n # print(sql_query)\n params = {\n \"text_lc\": text_lc,\n \"text_lc_wildcard\": f\"%{text_lc}%\",\n \"text_lc_starts_with\": f\"{text_lc}%\",\n \"langid\": langid,\n \"max_results\": max_results,\n }\n # print(params)\n\n alchsql = sqlalchemy.text(sql_query)\n return self.session.execute(alchsql, params).fetchall()\n\n def get_term_tags(self):\n \"Get all available term tags, helper method.\"\n tags = self.session.query(TermTag).all()\n return sorted([t.text for t in tags])\n\n def add(self, term):\n \"\"\"\n Add a term to be saved to the db session.\n Returns DB Term for tests and verification only,\n clients should not change it.\n \"\"\"\n dbterm = self._build_db_term(term)\n self.session.add(dbterm)\n return dbterm\n\n def delete(self, term):\n \"\"\"\n Add term to be deleted to session.\n \"\"\"\n dbt = None\n if term.id is not None:\n dbt = self.session.get(DBTerm, term.id)\n else:\n dbt = self._find_by_spec(term.language_id, term.text)\n if dbt is not None:\n self.session.delete(dbt)\n\n def commit(self):\n \"\"\"\n Commit everything, flush the map to force refetches.\n \"\"\"\n self.identity_map = {}\n self.session.commit()\n\n def _build_db_term(self, term):\n \"Convert a term business object to a DBTerm.\"\n # pylint: disable=too-many-branches\n if term.text is None:\n raise ValueError(\"Text not set for term\")\n\n t = None\n if term.id is not None:\n # This is an existing term, so use it directly.\n t = self.session.get(DBTerm, term.id)\n else:\n # New term, or finding by text.\n spec = self._search_spec_term(term.language_id, term.text)\n term_repo = TermRepository(self.session)\n t = term_repo.find_by_spec(spec) or DBTerm()\n t.language = spec.language\n\n t.text = term.text\n t.original_text = term.text\n t.status = term.status\n t.translation = term.translation\n t.romanization = term.romanization\n t.sync_status = term.sync_status\n t.set_current_image(term.current_image)\n\n if term.flash_message is not None:\n t.set_flash_message(term.flash_message)\n else:\n t.pop_flash_message()\n\n tt_repo = TermTagRepository(self.session)\n termtags = []\n for s in list(set(term.term_tags)):\n termtags.append(tt_repo.find_or_create_by_text(s))\n t.remove_all_term_tags()\n for tt in termtags:\n t.add_term_tag(tt)\n\n termparents = []\n lang = t.language\n create_parents = [\n p\n for p in term.parents\n if p is not None\n and p != \"\"\n and lang.get_lowercase(term.text) != lang.get_lowercase(p)\n ]\n # print('creating parents: ' + ', '.join(create_parents))\n for p in create_parents:\n termparents.append(self._find_or_create_parent(p, lang, term, termtags))\n t.remove_all_parents()\n for tp in termparents:\n t.add_parent(tp)\n\n if len(termparents) != 1:\n t.sync_status = False\n\n if t.sync_status and len(termparents) == 1:\n p = termparents[0]\n # pylint: disable=protected-access\n if term._status_explicitly_set or p.status == 0:\n p.status = t.status\n else:\n t.status = p.status\n\n return t\n\n def _find_or_create_parent(self, pt, language, term, termtags) -> DBTerm:\n p = self._find_by_spec(language.id, pt)\n new_or_unknown_parent = p is None or p.status == 0\n new_term = term.id is None\n\n if p is None:\n p = DBTerm(language, pt)\n\n if new_or_unknown_parent:\n p.status = term.status\n\n # Copy translation, image if missing, but _not_ if we're just\n # re-saving an existing term.\n if new_or_unknown_parent or new_term:\n if (p.translation or \"\") == \"\":\n p.translation = term.translation\n if (p.get_current_image() or \"\") == \"\":\n p.set_current_image(term.current_image)\n\n # Only copy tags if this is a new parent. New parents should\n # _likely_ inherity the tags of the term.\n if new_or_unknown_parent:\n for tt in termtags:\n p.add_term_tag(tt)\n\n return p\n\n def _build_business_term(self, dbterm):\n \"Create a Term bus. object from a lute.model.term.Term.\"\n term = Term()\n term.id = dbterm.id\n term.language_id = dbterm.language.id\n\n text = dbterm.text\n ## Remove zero-width spaces (zws) from strings for user forms.\n #\n # NOTE: disabling this as it creates challenges for editing\n # terms. In some cases, the same term may have a zws\n # character as part of it; in other cases, it won't, e.g. \"\n # 集めれ\" sometimes is parsed as one token, and sometimes\n # two (\"集め/れ\"). If we strip the zws from the string, then\n # when it's posted back, Lute will think that it has changed.\n # ... it gets messy.\n # zws = \"\\u200B\" # zero-width space\n # text = text.replace(zws, \"\")\n term.text_lc = dbterm.text_lc\n term.original_text = text\n term.text = text\n\n term.translation = dbterm.translation\n term.romanization = dbterm.romanization\n term.current_image = dbterm.get_current_image()\n term.flash_message = dbterm.get_flash_message()\n term.parents = [p.text for p in dbterm.parents]\n term.romanization = dbterm.romanization\n term.term_tags = [tt.text for tt in dbterm.term_tags]\n\n # pylint: disable=protected-access\n term._status = dbterm.status\n term._sync_status = dbterm.sync_status\n\n return term\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 11776}, "tests/orm/test_Term.py::169": {"resolved_imports": ["lute/models/term.py", "lute/db/__init__.py"], "used_names": ["Term", "assert_sql_result", "db"], "enclosing_function": "test_save_replace_remove_image", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7471}, "tests/unit/models/test_Setting.py::48": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_save_and_retrieve_user_setting", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/unit/db/setup/test_SqliteMigrator.py::117": {"resolved_imports": ["lute/db/setup/migrator.py"], "used_names": ["SqliteMigrator"], "enclosing_function": "test_repeatable_migs_are_always_applied", "extracted_code": "# Source: lute/db/setup/migrator.py\nclass SqliteMigrator:\n \"\"\"\n Sqlite migrator class.\n\n Follows the principles documented in\n https://github.com/jzohrab/DbMigrator/blob/master/docs/managing_database_changes.md\n \"\"\"\n\n def __init__(self, location, repeatable):\n self.location = location\n self.repeatable = repeatable\n\n def has_migrations(self, conn):\n \"\"\"\n Return True if have non-applied migrations.\n \"\"\"\n outstanding = self._get_pending(conn)\n return len(outstanding) > 0\n\n def _get_pending(self, conn):\n \"\"\"\n Get all non-applied (one-time) migrations.\n \"\"\"\n allfiles = []\n with _change_directory(self.location):\n allfiles = [\n os.path.join(self.location, s)\n for s in os.listdir()\n if s.endswith(\".sql\")\n ]\n allfiles.sort()\n outstanding = [f for f in allfiles if self._should_apply(conn, f)]\n return outstanding\n\n def do_migration(self, conn):\n \"\"\"\n Run all migrations, then all repeatable migrations.\n \"\"\"\n self._process_folder(conn)\n self._process_repeatable(conn)\n\n def _process_folder(self, conn):\n \"\"\"\n Run all pending migrations. Write executed script to\n _migrations table.\n \"\"\"\n outstanding = self._get_pending(conn)\n for f in outstanding:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n self._add_migration_to_database(conn, f)\n\n def _process_repeatable(self, conn):\n \"\"\"\n Run all repeatable migrations.\n \"\"\"\n with _change_directory(self.repeatable):\n files = [\n os.path.join(self.repeatable, f)\n for f in os.listdir()\n if f.endswith(\".sql\")\n ]\n for f in files:\n try:\n self._process_file(conn, f)\n except Exception as e:\n msg = str(e)\n print(f\"\\nFile {f} exception:\\n{msg}\\n\")\n raise e\n\n def _should_apply(self, conn, filename):\n \"\"\"\n True if a migration hasn't been run yet.\n\n The file basename (no directory) is stored in the migration table.\n \"\"\"\n f = os.path.basename(filename)\n sql = f\"select count(filename) from _migrations where filename = '{f}'\"\n res = conn.execute(sql).fetchone()\n return res[0] == 0\n\n def _add_migration_to_database(self, conn, filename):\n \"\"\"\n Track the executed migration in _migrations.\n \"\"\"\n f = os.path.basename(filename)\n conn.execute(\"begin transaction\")\n conn.execute(f\"INSERT INTO _migrations values ('{f}')\")\n conn.execute(\"commit transaction\")\n\n def _process_file(self, conn, f):\n \"\"\"\n Run the given file.\n \"\"\"\n with open(f, \"r\", encoding=\"utf8\") as sql_file:\n commands = sql_file.read()\n self._exec_commands(conn, commands)\n\n def _exec_commands(self, conn, sql):\n \"\"\"\n Execute all commands in the given file.\n \"\"\"\n conn.executescript(sql)", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3329}, "tests/unit/models/test_TermTag.py::56": {"resolved_imports": ["lute/models/term.py", "lute/models/repositories.py", "lute/db/__init__.py"], "used_names": ["TermTagRepository", "db"], "enclosing_function": "test_find_or_create_by_text_returns_new_if_no_match", "extracted_code": "# Source: lute/models/repositories.py\nclass TermTagRepository:\n \"Repository.\"\n\n def __init__(self, session):\n self.session = session\n\n def find(self, termtag_id):\n \"Get by ID.\"\n return self.session.query(TermTag).filter(TermTag.id == termtag_id).first()\n\n def find_by_text(self, text):\n \"Find a tag by text, or None if not found.\"\n return self.session.query(TermTag).filter(TermTag.text == text).first()\n\n def find_or_create_by_text(self, text):\n \"Return tag or create one.\"\n ret = self.find_by_text(text)\n if ret is not None:\n return ret\n return TermTag(text)\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 3, "n_chars_extracted": 699}, "tests/unit/language/test_service.py::63": {"resolved_imports": ["lute/language/service.py", "lute/db/__init__.py", "lute/utils/debug_helpers.py"], "used_names": ["DebugTimer", "Service", "assert_sql_result", "db"], "enclosing_function": "test_load_def_loads_lang_and_stories", "extracted_code": "# Source: lute/language/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n self.lang_defs_cache = self._get_langdefs_cache()\n\n def _get_langdefs_cache(self):\n \"Load cache.\"\n # dt = DebugTimer(\"_get_langdefs_cache\", False)\n # dt.step(\"start\")\n thisdir = os.path.dirname(__file__)\n langdefs_dir = os.path.join(thisdir, \"..\", \"db\", \"language_defs\")\n langdefs_dir = os.path.abspath(langdefs_dir)\n # dt.step(\"got base directory\")\n cache = []\n def_glob = os.path.join(langdefs_dir, \"**\", \"definition.yaml\")\n def_list = glob(def_glob)\n # dt.step(\"globbed\")\n def_list.sort()\n for f in def_list:\n lang_dir, _ = os.path.split(f)\n ld = LangDef(lang_dir)\n # dt.step(f\"build ld {ld.language_name}\".ljust(30))\n cache.append(ld)\n # dt.summary()\n return cache\n\n def get_supported_defs(self):\n \"Return supported language definitions.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language.is_supported]\n ret.sort(key=lambda x: x.language_name)\n return ret\n\n def supported_predefined_languages(self):\n \"Supported Languages defined in yaml files.\"\n return [d.language for d in self.get_supported_defs()]\n\n def get_language_def(self, lang_name):\n \"Get a lang def and its stories.\"\n ret = [ld for ld in self.lang_defs_cache if ld.language_name == lang_name]\n if len(ret) == 0:\n raise RuntimeError(f\"Missing language def name {lang_name}\")\n return ret[0]\n\n def load_language_def(self, lang_name):\n \"Load a language def and its stories, save to database.\"\n load_def = self.get_language_def(lang_name)\n lang = load_def.language\n if not lang.is_supported:\n raise RuntimeError(f\"{lang_name} not supported, can't be loaded.\")\n\n self.session.add(lang)\n self.session.commit()\n\n r = Repository(self.session)\n for b in load_def.books:\n r.add(b)\n r.commit()\n\n return lang.id\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()\n\n\n# Source: lute/utils/debug_helpers.py\nclass DebugTimer:\n \"\"\"\n Helper to log time.\n \"\"\"\n\n global_step_map = {}\n\n def __init__(self, name, display=True):\n self.start = time.process_time()\n self.curr_start = self.start\n self.name = name\n self.step_map = {}\n self.display = display\n if display:\n print(f\"{name} timer started\")\n\n def step(self, s):\n \"Dump time spent in step, total time since start.\"\n n = time.process_time()\n step_elapsed = n - self.curr_start\n total_step_elapsed = self.step_map.get(s, 0)\n total_step_elapsed += step_elapsed\n self.step_map[s] = total_step_elapsed\n\n if s != \"\":\n full_step_map_string = f\"{self.name} {s}\"\n global_step_elapsed = DebugTimer.global_step_map.get(\n full_step_map_string, 0\n )\n global_step_elapsed += step_elapsed\n DebugTimer.global_step_map[full_step_map_string] = global_step_elapsed\n\n total_elapsed = n - self.start\n self.curr_start = n\n\n if not self.display:\n return\n\n msg = \" \".join(\n [\n f\"{self.name} {s}:\",\n f\"step_elapsed: {step_elapsed:.6f},\",\n f\"total step_elapsed: {total_step_elapsed:.6f},\",\n f\"total_elapsed: {total_elapsed:.6f}\",\n ]\n )\n print(msg, flush=True)\n\n def summary(self):\n \"Print final step summary.\"\n print(f\"{self.name} summary ------------------\", flush=True)\n for k, v in self.step_map.items():\n print(f\" {k}: {v:.6f}\", flush=True)\n print(f\"end {self.name} summary --------------\", flush=True)\n\n @classmethod\n def clear_total_summary(cls):\n cls.global_step_map = {}\n\n @classmethod\n def total_summary(cls):\n \"Print final step summary.\"\n print(\"global summary ------------------\", flush=True)\n for k, v in cls.global_step_map.items():\n print(f\" {k}: {v:.6f}\", flush=True)\n print(\"end global summary --------------\", flush=True)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4318}, "tests/unit/backup/test_backup.py::254": {"resolved_imports": ["lute/backup/service.py", "lute/models/repositories.py", "lute/db/__init__.py", "lute/language/service.py"], "used_names": ["DatabaseBackupFile", "patch"], "enclosing_function": "test_database_backup_file_size_formatting", "extracted_code": "# Source: lute/backup/service.py\nclass DatabaseBackupFile:\n \"\"\"\n A representation of a lute backup file to hold metadata attributes.\n \"\"\"\n\n def __init__(self, filepath: Union[str, os.PathLike]):\n if not os.path.exists(filepath):\n raise BackupException(f\"No backup file at {filepath}.\")\n\n name = os.path.basename(filepath)\n if not re.match(r\"(manual_)?lute_backup_\", name):\n raise BackupException(f\"Not a valid lute database backup at {filepath}.\")\n\n self.filepath = filepath\n self.name = name\n self.is_manual = self.name.startswith(\"manual_\")\n\n def __lt__(self, other):\n return self.last_modified < other.last_modified\n\n @property\n def last_modified(self) -> datetime:\n return datetime.fromtimestamp(os.path.getmtime(self.filepath)).astimezone()\n\n @property\n def size_bytes(self) -> int:\n return os.path.getsize(self.filepath)\n\n @property\n def size(self) -> str:\n \"\"\"\n A human-readable string representation of the size of the file.\n\n Eg.\n 1746 bytes\n 4 kB\n 27 MB\n \"\"\"\n s = self.size_bytes\n if s >= 1e9:\n return f\"{round(s * 1e-9)} GB\"\n if s >= 1e6:\n return f\"{round(s * 1e-6)} MB\"\n if s >= 1e3:\n return f\"{round(s * 1e-3)} KB\"\n return f\"{s} bytes\"", "n_imports_parsed": 9, "n_files_resolved": 4, "n_chars_extracted": 1383}, "tests/orm/test_Language.py::131": {"resolved_imports": ["lute/models/language.py", "lute/models/repositories.py", "lute/read/service.py", "lute/db/__init__.py"], "used_names": ["LanguageDictionary", "add_terms", "assert_record_count_equals", "assert_sql_result", "db", "make_text"], "enclosing_function": "test_delete_language_removes_book_and_terms", "extracted_code": "# Source: lute/models/language.py\nclass LanguageDictionary(db.Model):\n \"\"\"\n Language dictionary.\n \"\"\"\n\n __tablename__ = \"languagedicts\"\n\n id = db.Column(\"LdID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\n \"LdLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"), nullable=False\n )\n language = db.relationship(\"Language\", back_populates=\"dictionaries\")\n usefor = db.Column(\"LdUseFor\", db.String(20), nullable=False)\n dicttype = db.Column(\"LdType\", db.String(20), nullable=False)\n dicturi = db.Column(\"LdDictURI\", db.String(200), nullable=False)\n is_active = db.Column(\"LdIsActive\", db.Boolean, default=True)\n sort_order = db.Column(\"LdSortOrder\", db.SmallInteger, nullable=False)\n\n # HACK: pre-pend '*' to URLs that need to open a new window.\n # This is a relic of the original code, and should be changed.\n # TODO remove-asterisk-hack: remove * from URL start.\n def make_uri(self):\n \"Hack add asterisk.\"\n prepend = \"*\" if self.dicttype == \"popuphtml\" else \"\"\n return f\"{prepend}{self.dicturi}\"\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 7, "n_files_resolved": 4, "n_chars_extracted": 1137}, "tests/unit/models/test_Setting.py::37": {"resolved_imports": ["lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["assert_sql_result", "db"], "enclosing_function": "test_user_and_system_settings_do_not_intersect", "extracted_code": "# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 5, "n_files_resolved": 2, "n_chars_extracted": 47}, "tests/unit/themes/test_service.py::17": {"resolved_imports": ["lute/themes/service.py", "lute/db/__init__.py", "lute/models/repositories.py"], "used_names": ["Service", "db"], "enclosing_function": "test_list_themes", "extracted_code": "# Source: lute/themes/service.py\nclass Service:\n \"Service.\"\n\n def __init__(self, session):\n self.session = session\n\n def _css_path(self):\n \"\"\"\n Path to css in this folder.\n \"\"\"\n thisdir = os.path.dirname(__file__)\n theme_dir = os.path.join(thisdir, \"css\")\n return os.path.abspath(theme_dir)\n\n def list_themes(self):\n \"\"\"\n List of theme file names and user-readable name.\n \"\"\"\n\n def _make_display_name(s):\n ret = os.path.basename(s)\n ret = ret.replace(\".css\", \"\").replace(\"_\", \" \")\n return ret\n\n g = glob(os.path.join(self._css_path(), \"*.css\"))\n themes = [(os.path.basename(f), _make_display_name(f)) for f in g]\n theme_basenames = [t[0] for t in themes]\n\n g = glob(os.path.join(current_app.env_config.userthemespath, \"*.css\"))\n additional_user_themes = [\n (os.path.basename(f), _make_display_name(f))\n for f in g\n if os.path.basename(f) not in theme_basenames\n ]\n\n themes += additional_user_themes\n sorted_themes = sorted(themes, key=lambda x: x[1])\n return [default_entry] + sorted_themes\n\n def get_current_css(self):\n \"\"\"\n Return the current css pointed at by the current_theme user setting.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n if current_theme == default_entry[0]:\n return \"\"\n\n def _get_theme_css_in_dir(d):\n \"Get css, or '' if no file.\"\n fname = os.path.join(d, current_theme)\n if not os.path.exists(fname):\n return \"\"\n with open(fname, \"r\", encoding=\"utf-8\") as f:\n return f.read()\n\n ret = _get_theme_css_in_dir(self._css_path())\n add = _get_theme_css_in_dir(current_app.env_config.userthemespath)\n if add != \"\":\n ret += f\"\\n\\n/* Additional user css */\\n\\n{add}\"\n return ret\n\n def next_theme(self):\n \"\"\"\n Move to the next theme in the list of themes.\n \"\"\"\n repo = UserSettingRepository(self.session)\n current_theme = repo.get_value(\"current_theme\")\n themes = [t[0] for t in self.list_themes()]\n themes.append(default_entry[0])\n for i in range(0, len(themes)): # pylint: disable=consider-using-enumerate\n if themes[i] == current_theme:\n new_index = i + 1\n break\n repo.set_value(\"current_theme\", themes[new_index])\n self.session.commit()\n\n\n# Source: lute/db/__init__.py\ndb = SQLAlchemy()", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 2663}, "plugins/_template_/tests/test_LangNameParser.py::38": {"resolved_imports": ["lute/models/term.py", "lute/parse/base.py"], "used_names": ["Term"], "enclosing_function": "todo_test_token_count", "extracted_code": "# Source: lute/models/term.py\nclass Term(\n db.Model\n): # pylint: disable=too-few-public-methods, too-many-instance-attributes\n \"\"\"\n Term entity.\n \"\"\"\n\n __tablename__ = \"words\"\n\n id = db.Column(\"WoID\", db.SmallInteger, primary_key=True)\n language_id = db.Column(\"WoLgID\", db.Integer, db.ForeignKey(\"languages.LgID\"))\n\n # Text should only be set through setters.\n _text = db.Column(\"WoText\", db.String(250))\n\n # text_lc shouldn't be touched (it's changed when term.text is\n # set), but it's public here to allow for its access during\n # queries (eg in lute.read.service. This can probably be\n # improved, not sure how at the moment.\n text_lc = db.Column(\"WoTextLC\", db.String(250))\n\n status = db.Column(\"WoStatus\", db.Integer)\n translation = db.Column(\"WoTranslation\", db.String(500))\n romanization = db.Column(\"WoRomanization\", db.String(100))\n token_count = db.Column(\"WoTokenCount\", db.Integer)\n sync_status = db.Column(\"WoSyncStatus\", db.Boolean)\n\n language = db.relationship(\"Language\")\n term_tags = db.relationship(\"TermTag\", secondary=\"wordtags\")\n parents = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n back_populates=\"children\",\n )\n children = db.relationship(\n \"Term\",\n secondary=\"wordparents\",\n primaryjoin=\"Term.id == wordparents.c.WpParentWoID\",\n secondaryjoin=\"Term.id == wordparents.c.WpWoID\",\n back_populates=\"parents\",\n )\n images = db.relationship(\n \"TermImage\",\n back_populates=\"term\",\n lazy=\"subquery\",\n cascade=\"all, delete-orphan\",\n )\n term_flash_message = db.relationship(\n \"TermFlashMessage\",\n uselist=False,\n back_populates=\"term\",\n cascade=\"all, delete-orphan\",\n )\n\n def __init__(self, language=None, text=None):\n self.status = 1\n self.translation = None\n self.romanization = None\n self.sync_status = False\n self.term_tags = []\n self.parents = []\n self.children = []\n self.images = []\n if language is not None:\n self.language = language\n if text is not None:\n self.text = text\n\n @staticmethod\n def create_term_no_parsing(language, text):\n \"\"\"\n Create a term, but do not reparse it during creation.\n\n This method is necessary because some parsers return\n different parsed tokens for a given text string based\n on its context. The general __init__() is used for\n parsing without context, such as creating Terms from\n the UI or during CSV import. This method is used\n when new terms are created from an already-parsed\n and already-tokenized page of text.\n \"\"\"\n t = Term()\n t.language = language\n t._text = text # pylint: disable=protected-access\n t.text_lc = language.get_lowercase(text)\n t.romanization = language.parser.get_reading(text)\n t._calc_token_count() # pylint: disable=protected-access\n return t\n\n def __repr__(self):\n return f\"\"\n\n def __eq__(self, other):\n def eqrep(term):\n return f\"{term.language.name} {term.text}\"\n\n if isinstance(other, Term):\n return eqrep(self) == eqrep(other)\n return False\n\n @property\n def text(self):\n \"Get the text.\"\n return self._text\n\n def _parse_string_add_zws(self, lang, textstring):\n \"Parse the string using the language.\"\n # Clean up encoding cruft.\n t = textstring.strip()\n zws = \"\\u200B\" # zero-width space\n t = t.replace(zws, \"\")\n nbsp = \"\\u00A0\" # non-breaking space\n t = t.replace(nbsp, \" \")\n\n tokens = lang.get_parsed_tokens(t)\n\n # Terms can't contain paragraph markers.\n tokens = [tok for tok in tokens if tok.token != \"¶\"]\n tok_strings = [tok.token for tok in tokens]\n\n t = zws.join(tok_strings)\n return t\n\n @text.setter\n def text(self, textstring):\n \"\"\"\n Set the text, textlc, and token count.\n\n For new terms, just parse, downcase, and get the count.\n\n For existing terms, ensure that the actual text content has\n not changed.\n \"\"\"\n if self.language is None:\n raise RuntimeError(\"Must set term language before setting text\")\n lang = self.language\n\n if self.id is None:\n t = self._parse_string_add_zws(lang, textstring)\n self._text = t\n self.text_lc = lang.get_lowercase(t)\n self.romanization = lang.parser.get_reading(t)\n self._calc_token_count()\n else:\n # new_lc = lang.get_lowercase(textstring)\n # print(f\"new lowercase = '{new_lc}', old = '{self.text_lc}'\", flush=True)\n if lang.get_lowercase(textstring) != self.text_lc:\n msg = f'Cannot change text of saved term \"{self._text}\" (id {self.id}).'\n raise TermTextChangedException(msg)\n self._text = textstring\n\n def _calc_token_count(self):\n \"Tokens are separated by zero-width space.\"\n token_count = 0\n if self._text is not None:\n zws = \"\\u200B\" # zero-width space\n parts = self._text.split(zws)\n token_count = len(parts)\n self.token_count = token_count\n\n def remove_all_term_tags(self):\n self.term_tags = []\n\n def add_term_tag(self, term_tag):\n if term_tag not in self.term_tags:\n self.term_tags.append(term_tag)\n\n def remove_term_tag(self, term_tag):\n if term_tag in self.term_tags:\n self.term_tags.remove(term_tag)\n\n def remove_all_parents(self):\n self.parents = []\n\n def add_parent(self, parent):\n \"\"\"\n Add valid parent, term cannot be its own parent.\n \"\"\"\n if self == parent:\n return\n if parent not in self.parents:\n self.parents.append(parent)\n if len(self.parents) > 1:\n self.sync_status = False\n\n def get_current_image(self):\n \"Get the current (first) image for the term.\"\n if len(self.images) == 0:\n return None\n i = self.images[0]\n return i.source\n\n def set_current_image(self, s):\n \"Set the current image for this term.\"\n while len(self.images) > 0:\n self.images.pop(0)\n if (s or \"\").strip() != \"\":\n ti = TermImage()\n ti.term = self\n ti.source = s.strip()\n self.images.append(ti)\n\n def get_flash_message(self):\n \"Get the flash message.\"\n if not self.term_flash_message:\n return None\n return self.term_flash_message.message\n\n def set_flash_message(self, m):\n \"Set a flash message to be shown at some point in the future.\"\n tfm = self.term_flash_message\n if not tfm:\n tfm = TermFlashMessage()\n self.term_flash_message = tfm\n tfm.message = m\n\n def pop_flash_message(self):\n \"Get the flash message, and remove it from this term.\"\n if not self.term_flash_message:\n return None\n m = self.term_flash_message.message\n self.term_flash_message = None\n return m", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7421}}}