├── __about__.py ├── .gitignore ├── LICENSE ├── helper.py ├── pyproject.toml ├── README.md └── src └── search_transcripts ├── utils.py └── __init__.py /__about__.py: -------------------------------------------------------------------------------- 1 | VERSION = "0.1" 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.json 2 | *.pickle 3 | *.db 4 | *.ipynb 5 | __pycache__/ 6 | *.mp3 7 | atp/ 8 | recdiff_transcripts/ 9 | SCOTUS/ 10 | *.db.wal 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Marcos Huerta 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /helper.py: -------------------------------------------------------------------------------- 1 | import json 2 | from os import path 3 | 4 | import whisper 5 | import datetime 6 | import pycurl 7 | 8 | 9 | def download_url(x): 10 | c = pycurl.Curl() 11 | c.setopt(c.URL, x) 12 | c.setopt(c.FOLLOWLOCATION, True) 13 | with open(x.split("/")[-1], 'wb') as f: 14 | c.setopt(c.WRITEFUNCTION, f.write) 15 | c.perform() 16 | 17 | 18 | def write_json(out, filename): 19 | 20 | with open(filename, 'w') as f: 21 | json.dump([{ 22 | 'start': x['start'], 23 | 'end': x['end'], 24 | 'text': x['text'] 25 | } for x in out['segments']], 26 | f, 27 | indent=4) 28 | 29 | 30 | def transcribe_to_json(filename, model='base.en'): 31 | out_name = f'{filename}_transcript_{model}.json' 32 | if path.exists(out_name): 33 | print(f"File {out_name} exists") 34 | return 35 | 36 | start_time = datetime.datetime.now() 37 | model = whisper.load_model(model) 38 | 39 | out = model.transcribe(filename, language='en', verbose=False) 40 | end_time = datetime.datetime.now() 41 | print(f"This took {(end_time-start_time).total_seconds() / 60} minutes") 42 | write_json(out, out_name) 43 | 44 | 45 | if __name__ == "__main__": 46 | 47 | import argparse 48 | parser = argparse.ArgumentParser() 49 | 50 | parser.add_argument('filename') 51 | parser.add_argument("--model", default='medium.en') 52 | 53 | args = parser.parse_args() 54 | 55 | transcribe_to_json(args.filename, model=args.model) 56 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | #none of this probably is right yet 2 | 3 | [build-system] 4 | requires = ["hatchling"] 5 | build-backend = "hatchling.build" 6 | 7 | [project] 8 | name = "search-transcripts" 9 | version = "0.11" 10 | description = 'Convert a folder of transcripts to a searchable database' 11 | readme = "README.md" 12 | requires-python = ">=3.7" 13 | license = "MIT" 14 | keywords = [] 15 | authors = [{ name = "Marcos Huerta", email = "marcos@marcoshuerta.com" }] 16 | classifiers = [ 17 | "Development Status :: 4 - Beta", 18 | "Programming Language :: Python", 19 | "Programming Language :: Python :: 3.7", 20 | "Programming Language :: Python :: 3.8", 21 | "Programming Language :: Python :: 3.9", 22 | "Programming Language :: Python :: 3.10", 23 | "Programming Language :: Python :: 3.11", 24 | "Programming Language :: Python :: Implementation :: CPython", 25 | "Programming Language :: Python :: Implementation :: PyPy", 26 | ] 27 | dependencies = ["pandas", "numpy"] 28 | 29 | [project.urls] 30 | Documentation = "https://github.com/astrowonk/search_transcripts/#readme" 31 | Issues = "https://github.com/astrowonk/search_transcripts/issues" 32 | Source = "https://github.com/astrowonk/search_transcripts" 33 | 34 | 35 | [tool.hatch.envs.default] 36 | dependencies = ["pytest", "pytest-cov"] 37 | [tool.hatch.envs.default.scripts] 38 | cov = "pytest --cov-report=term-missing --cov-config=pyproject.toml --cov=search_transcripts --cov=tests" 39 | no-cov = "cov --no-cov" 40 | 41 | [[tool.hatch.envs.test.matrix]] 42 | python = ["37", "38", "39", "310", "311"] 43 | 44 | [tool.hatch.build.targets.sdist] 45 | exclude = ["/.github"] 46 | 47 | [tool.hatch.build.targets.wheel] 48 | packages = ["src/search_transcripts"] 49 | 50 | [tool.coverage.report] 51 | exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"] 52 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Transcript Search 2 | 3 | This code was designed to make a large number of OpenAI's whisper transcripts easily searchable. So one can find a particular passage or term occurs and at what time in the transcript. However, it should work with any folder of .VTT files: non just OpenAI transcripts of podcasts. 4 | 5 | I used Whisper OpenAI to transcribe [the Accidental Tech Podcast](https://atp.fm), and [I deployed a live search engine web site front end here](https://marcoshuerta.com/dash/atp_search/), powered by this module (specifically `SearchTranscripts`). 6 | 7 | This module has two classes: 8 | 9 | * `LoadTranscripts`: This creates a sqlite database and [FTS5 virtual table](https://www.sqlite.org/fts5.html) from a folder of transcript files (`.vtt` or `.json` files). It creates longer chunks of text (about 300 words each) from the short transcript segments in the original file in order to make the text blocks searchable. It preserves the individual transcript segments in a separate database. 10 | 11 | * `SearchTranscripts`: This is a python class that uses the Sqlite database to return a pandas dataframe of the top results for the search query. 12 | 13 | Once the sqlite database is created with `LoadTranscripts`, you can access that database via any sqlite interface you like such as [datasette](https://datasette.io), [dbeaver](https://dbeaver.io), the [command line](https://www.sqlite.org/cli.html), [SQL alchemy](https://www.sqlalchemy.org), etc. The `SearchTranscripts` class is meant to be a simple and convenient way to access the data from python, using the built-in sqlite3 module and pandas, but it is somewhat limited. 14 | 15 | # Installation: 16 | 17 | Clone and cd into the repo's main directory, then run: 18 | 19 | ``` 20 | pip install . 21 | ``` 22 | 23 | 24 | # Usage: 25 | 26 | ```{python} 27 | 28 | from search_transcripts import LoadTranscripts, SearchTranscripts 29 | 30 | l = LoadTranscripts('transcripts') ## will create main.db and bm25.pickle 31 | 32 | 33 | s = SearchTranscripts() 34 | 35 | ## Returns a pandas dataframe of the top scoring transcript sections, across all transcripts. 36 | 37 | s.search('starship enterprise') 38 | 39 | ##find the exact phrase 40 | 41 | s.search('"starship enterprise"') 42 | 43 | 44 | ``` 45 | 46 | ## JSON transcripts? 47 | 48 | So, before I realized Whisper would create a standard .VTT file, I was using the python API directly. It generates a list of python dictionaries. Saving that as JSON seemed logical at the time. I find the JSON much more easily machine readable than .VTT, and can easily be converted to VTT, so I still support this somewhat quirky format. It looks like so: 49 | 50 | ```{json} 51 | [ 52 | { 53 | "start": 606.1800000000001, 54 | "end": 610.74, 55 | "text": " It's important to have a goal to work toward and accomplish rather than just randomly learning and half building things" 56 | }, 57 | { 58 | "start": 610.74, 59 | "end": 613.0600000000001, 60 | "text": " Having a specific thing you want to build is a good substitute" 61 | }, 62 | { 63 | "start": 613.38, 64 | "end": 619.78, 65 | "text": " Keep making things until you've made something you're proud enough a proud of enough to show off in an interview by the time you've built a few" 66 | }, 67 | { 68 | "start": 619.78, 69 | "end": 624.26, 70 | "text": " Things you'll start developing the taste you need to make that determination of what's quote unquote good enough" 71 | }, 72 | 73 | 74 | ] 75 | 76 | ``` 77 | -------------------------------------------------------------------------------- /src/search_transcripts/utils.py: -------------------------------------------------------------------------------- 1 | """These functions used via the Apache 2.0 license from the Datasette project: 2 | 3 | https://github.com/simonw/datasette/blob/main/datasette/utils/__init__.py 4 | 5 | 6 | 7 | Apache License 8 | Version 2.0, January 2004 9 | http://www.apache.org/licenses/ 10 | 11 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 12 | 13 | 1. Definitions. 14 | 15 | "License" shall mean the terms and conditions for use, reproduction, 16 | and distribution as defined by Sections 1 through 9 of this document. 17 | 18 | "Licensor" shall mean the copyright owner or entity authorized by 19 | the copyright owner that is granting the License. 20 | 21 | "Legal Entity" shall mean the union of the acting entity and all 22 | other entities that control, are controlled by, or are under common 23 | control with that entity. For the purposes of this definition, 24 | "control" means (i) the power, direct or indirect, to cause the 25 | direction or management of such entity, whether by contract or 26 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 27 | outstanding shares, or (iii) beneficial ownership of such entity. 28 | 29 | "You" (or "Your") shall mean an individual or Legal Entity 30 | exercising permissions granted by this License. 31 | 32 | "Source" form shall mean the preferred form for making modifications, 33 | including but not limited to software source code, documentation 34 | source, and configuration files. 35 | 36 | "Object" form shall mean any form resulting from mechanical 37 | transformation or translation of a Source form, including but 38 | not limited to compiled object code, generated documentation, 39 | and conversions to other media types. 40 | 41 | "Work" shall mean the work of authorship, whether in Source or 42 | Object form, made available under the License, as indicated by a 43 | copyright notice that is included in or attached to the work 44 | (an example is provided in the Appendix below). 45 | 46 | "Derivative Works" shall mean any work, whether in Source or Object 47 | form, that is based on (or derived from) the Work and for which the 48 | editorial revisions, annotations, elaborations, or other modifications 49 | represent, as a whole, an original work of authorship. For the purposes 50 | of this License, Derivative Works shall not include works that remain 51 | separable from, or merely link (or bind by name) to the interfaces of, 52 | the Work and Derivative Works thereof. 53 | 54 | "Contribution" shall mean any work of authorship, including 55 | the original version of the Work and any modifications or additions 56 | to that Work or Derivative Works thereof, that is intentionally 57 | submitted to Licensor for inclusion in the Work by the copyright owner 58 | or by an individual or Legal Entity authorized to submit on behalf of 59 | the copyright owner. For the purposes of this definition, "submitted" 60 | means any form of electronic, verbal, or written communication sent 61 | to the Licensor or its representatives, including but not limited to 62 | communication on electronic mailing lists, source code control systems, 63 | and issue tracking systems that are managed by, or on behalf of, the 64 | Licensor for the purpose of discussing and improving the Work, but 65 | excluding communication that is conspicuously marked or otherwise 66 | designated in writing by the copyright owner as "Not a Contribution." 67 | 68 | "Contributor" shall mean Licensor and any individual or Legal Entity 69 | on behalf of whom a Contribution has been received by Licensor and 70 | subsequently incorporated within the Work. 71 | 72 | 2. Grant of Copyright License. Subject to the terms and conditions of 73 | this License, each Contributor hereby grants to You a perpetual, 74 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 75 | copyright license to reproduce, prepare Derivative Works of, 76 | publicly display, publicly perform, sublicense, and distribute the 77 | Work and such Derivative Works in Source or Object form. 78 | 79 | 3. Grant of Patent License. Subject to the terms and conditions of 80 | this License, each Contributor hereby grants to You a perpetual, 81 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 82 | (except as stated in this section) patent license to make, have made, 83 | use, offer to sell, sell, import, and otherwise transfer the Work, 84 | where such license applies only to those patent claims licensable 85 | by such Contributor that are necessarily infringed by their 86 | Contribution(s) alone or by combination of their Contribution(s) 87 | with the Work to which such Contribution(s) was submitted. If You 88 | institute patent litigation against any entity (including a 89 | cross-claim or counterclaim in a lawsuit) alleging that the Work 90 | or a Contribution incorporated within the Work constitutes direct 91 | or contributory patent infringement, then any patent licenses 92 | granted to You under this License for that Work shall terminate 93 | as of the date such litigation is filed. 94 | 95 | 4. Redistribution. You may reproduce and distribute copies of the 96 | Work or Derivative Works thereof in any medium, with or without 97 | modifications, and in Source or Object form, provided that You 98 | meet the following conditions: 99 | 100 | (a) You must give any other recipients of the Work or 101 | Derivative Works a copy of this License; and 102 | 103 | (b) You must cause any modified files to carry prominent notices 104 | stating that You changed the files; and 105 | 106 | (c) You must retain, in the Source form of any Derivative Works 107 | that You distribute, all copyright, patent, trademark, and 108 | attribution notices from the Source form of the Work, 109 | excluding those notices that do not pertain to any part of 110 | the Derivative Works; and 111 | 112 | (d) If the Work includes a "NOTICE" text file as part of its 113 | distribution, then any Derivative Works that You distribute must 114 | include a readable copy of the attribution notices contained 115 | within such NOTICE file, excluding those notices that do not 116 | pertain to any part of the Derivative Works, in at least one 117 | of the following places: within a NOTICE text file distributed 118 | as part of the Derivative Works; within the Source form or 119 | documentation, if provided along with the Derivative Works; or, 120 | within a display generated by the Derivative Works, if and 121 | wherever such third-party notices normally appear. The contents 122 | of the NOTICE file are for informational purposes only and 123 | do not modify the License. You may add Your own attribution 124 | notices within Derivative Works that You distribute, alongside 125 | or as an addendum to the NOTICE text from the Work, provided 126 | that such additional attribution notices cannot be construed 127 | as modifying the License. 128 | 129 | You may add Your own copyright statement to Your modifications and 130 | may provide additional or different license terms and conditions 131 | for use, reproduction, or distribution of Your modifications, or 132 | for any such Derivative Works as a whole, provided Your use, 133 | reproduction, and distribution of the Work otherwise complies with 134 | the conditions stated in this License. 135 | 136 | 5. Submission of Contributions. Unless You explicitly state otherwise, 137 | any Contribution intentionally submitted for inclusion in the Work 138 | by You to the Licensor shall be under the terms and conditions of 139 | this License, without any additional terms or conditions. 140 | Notwithstanding the above, nothing herein shall supersede or modify 141 | the terms of any separate license agreement you may have executed 142 | with Licensor regarding such Contributions. 143 | 144 | 6. Trademarks. This License does not grant permission to use the trade 145 | names, trademarks, service marks, or product names of the Licensor, 146 | except as required for reasonable and customary use in describing the 147 | origin of the Work and reproducing the content of the NOTICE file. 148 | 149 | 7. Disclaimer of Warranty. Unless required by applicable law or 150 | agreed to in writing, Licensor provides the Work (and each 151 | Contributor provides its Contributions) on an "AS IS" BASIS, 152 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 153 | implied, including, without limitation, any warranties or conditions 154 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 155 | PARTICULAR PURPOSE. You are solely responsible for determining the 156 | appropriateness of using or redistributing the Work and assume any 157 | risks associated with Your exercise of permissions under this License. 158 | 159 | 8. Limitation of Liability. In no event and under no legal theory, 160 | whether in tort (including negligence), contract, or otherwise, 161 | unless required by applicable law (such as deliberate and grossly 162 | negligent acts) or agreed to in writing, shall any Contributor be 163 | liable to You for damages, including any direct, indirect, special, 164 | incidental, or consequential damages of any character arising as a 165 | result of this License or out of the use or inability to use the 166 | Work (including but not limited to damages for loss of goodwill, 167 | work stoppage, computer failure or malfunction, or any and all 168 | other commercial damages or losses), even if such Contributor 169 | has been advised of the possibility of such damages. 170 | 171 | 9. Accepting Warranty or Additional Liability. While redistributing 172 | the Work or Derivative Works thereof, You may choose to offer, 173 | and charge a fee for, acceptance of support, warranty, indemnity, 174 | or other liability obligations and/or rights consistent with this 175 | License. However, in accepting such obligations, You may act only 176 | on Your own behalf and on Your sole responsibility, not on behalf 177 | of any other Contributor, and only if You agree to indemnify, 178 | defend, and hold each Contributor harmless for any liability 179 | incurred by, or claims asserted against, such Contributor by reason 180 | of your accepting any such warranty or additional liability. 181 | 182 | END OF TERMS AND CONDITIONS 183 | 184 | APPENDIX: How to apply the Apache License to your work. 185 | 186 | To apply the Apache License to your work, attach the following 187 | boilerplate notice, with the fields enclosed by brackets "{}" 188 | replaced with your own identifying information. (Don't include 189 | the brackets!) The text should be enclosed in the appropriate 190 | comment syntax for the file format. We also recommend that a 191 | file or class name and description of purpose be included on the 192 | same "printed page" as the copyright notice for easier 193 | identification within third-party archives. 194 | 195 | Copyright {yyyy} {name of copyright owner} 196 | 197 | Licensed under the Apache License, Version 2.0 (the "License"); 198 | you may not use this file except in compliance with the License. 199 | You may obtain a copy of the License at 200 | 201 | http://www.apache.org/licenses/LICENSE-2.0 202 | 203 | Unless required by applicable law or agreed to in writing, software 204 | distributed under the License is distributed on an "AS IS" BASIS, 205 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 206 | See the License for the specific language governing permissions and 207 | limitations under the License. 208 | 209 | 210 | 211 | 212 | 213 | """ 214 | 215 | import re 216 | 217 | _escape_fts_re = re.compile(r'\s+|(".*?")') 218 | 219 | 220 | def escape_fts(query): 221 | # If query has unbalanced ", add one at end 222 | # Taken from the Datasette project utils Licensed under the Apache 2.0 license 223 | 224 | if query.count('"') % 2: 225 | query += '"' 226 | bits = _escape_fts_re.split(query) 227 | bits = [b for b in bits if b and b != '""'] 228 | return " ".join('"{}"'.format(bit) if not bit.startswith('"') else bit 229 | for bit in bits) -------------------------------------------------------------------------------- /src/search_transcripts/__init__.py: -------------------------------------------------------------------------------- 1 | import re 2 | import pandas as pd 3 | import glob 4 | import json 5 | from tqdm.notebook import tqdm 6 | import sqlite3 7 | from .utils import escape_fts 8 | from collections import deque 9 | 10 | from concurrent.futures import ProcessPoolExecutor 11 | from multiprocessing import cpu_count 12 | 13 | 14 | def flatten_list(list_of_lists): 15 | return [y for x in list_of_lists for y in x] 16 | 17 | 18 | def my_escape_fts(search): 19 | search = search.replace("‘", "'").replace("’", "'") 20 | search = search.replace('“', '"').replace('”', '"') 21 | if '"' in search or "'" in search: 22 | return escape_fts(search) 23 | else: 24 | return search 25 | 26 | 27 | class LoadTranscripts(): 28 | """Load a directory of VTT or .json transcripts (from Whisper) into a sqlite database. It also creates an BM25 index. 29 | 30 | This creates the data for SearchTranscripts() 31 | 32 | rebuild defaults to False but the key_regex must be consistent between builds or duplicates may be inserted. key_regex processes the file/path name to 33 | whatever string will be used in episode_key in the database. 34 | 35 | """ 36 | search_docs = None 37 | word_limit = 300 38 | conn = None 39 | 40 | def __init__(self, 41 | path: str, 42 | key_regex: str = None, 43 | output_prefix: str = '', 44 | rebuild=False, 45 | sub_dict=None, 46 | make_key_integer=False) -> None: 47 | """Initalize the class. path will be globbed for .vtt and .json files. 48 | 49 | the episode_key will come from the filename unless key_regex is specified to extract an episode number or other identifier. 50 | 51 | """ 52 | if sub_dict: 53 | self.sub_dict = sub_dict 54 | else: 55 | self.sub_dict = {} 56 | self.rebuild = rebuild 57 | if output_prefix: 58 | output_prefix = output_prefix + '_' 59 | self.output_prefix = output_prefix 60 | self.key_regex = key_regex 61 | self.make_key_integer = make_key_integer 62 | self.load_all_files(path) 63 | self.stop_words = [] 64 | 65 | def process_all(self): 66 | """build search documents and save the database""" 67 | 68 | if self.rebuild: 69 | print("Rebuild is True, dropping tables for full rebuild.") 70 | self.drop_tables() 71 | else: 72 | print("cleaning data") 73 | self.clean_data() 74 | self.process_substitutions() 75 | 76 | self.build_search_documents() 77 | self.save_data() 78 | 79 | def load_all_files(self, path): 80 | """Load all files into self.data, a list of dictionaries.""" 81 | json_files = glob.glob(f"{path}/*.json") 82 | vtt_files = glob.glob(f"{path}/*.vtt") 83 | print('loading data') 84 | if not self.key_regex: 85 | self.data = {x: json.load(open(x)) for x in tqdm(json_files)} 86 | self.data.update({x: read_vtt(x) for x in tqdm(vtt_files)}) 87 | else: 88 | self.data = { 89 | self.process_regex(x): json.load(open(x)) 90 | for x in tqdm(json_files) 91 | } 92 | self.data.update( 93 | {self.process_regex(x): read_vtt(x) 94 | for x in tqdm(vtt_files)}) 95 | 96 | def process_regex(self, x): 97 | """turn the file names into whatever the regex finds. Regex should have a () group.""" 98 | print(x) 99 | m = re.search(self.key_regex, x) 100 | if self.make_key_integer: 101 | return int(m.group(1)) 102 | return m.group(1) 103 | 104 | def drop_tables(self): 105 | with sqlite3.connect(f'{self.output_prefix}main.db') as conn: 106 | conn.execute("drop table if exists all_segments;") 107 | conn.execute("drop table if exists search_data;") 108 | 109 | def clean_data(self): 110 | """Check for existing keys and skip insertion and processing of them""" 111 | try: 112 | existing_records = [ 113 | x[0] for x in sqlite3.connect(f'{self.output_prefix}main.db'). 114 | execute("select distinct(episode_key) from search_data;") 115 | ] 116 | except sqlite3.OperationalError: 117 | existing_records = [] 118 | self.data = { 119 | key: val 120 | for key, val in self.data.items() if key not in existing_records 121 | } 122 | print( 123 | f"{len(existing_records)} found in existing search_records database using regex for keys {self.key_regex}. Pruned new records to {len(self.data)}" 124 | ) 125 | 126 | def save_data(self): 127 | """take the list of dictionaries and create the sqlite table and indices.""" 128 | self.conn = sqlite3.connect(f'{self.output_prefix}main.db') 129 | 130 | if not self.data: 131 | print("No records to write") 132 | return 133 | 134 | print(f"Writing SQL with {self.conn}") 135 | print("Making table all_segments") 136 | ## segment data 137 | for key in self.data.keys(): 138 | df = pd.json_normalize( 139 | self.data[key]).reset_index().rename(columns={ 140 | 'index': 'segment' 141 | }).drop(columns='end') 142 | df['start'] = df['start'].apply(self.make_timestamp) 143 | df['episode_key'] = key 144 | df.to_sql('all_segments', 145 | con=self.conn, 146 | if_exists='append', 147 | index=False) 148 | 149 | self.conn.execute( 150 | "CREATE INDEX IF NOT EXISTS idx_segments on all_segments(segment,episode_key);" 151 | ) 152 | 153 | ## search chunk data 154 | print("Making table search_data") 155 | 156 | df = pd.DataFrame(self.search_docs).drop(columns=['end_ts'], 157 | errors='ignore') 158 | print(df.columns) 159 | 160 | self.conn.execute( 161 | "CREATE VIRTUAL TABLE IF NOT EXISTS search_data USING fts5(episode_key, text,start,end,start_ts, start_segment, end_segment, tokenize = 'porter ascii');" 162 | ) 163 | df.to_sql('search_data', 164 | con=self.conn, 165 | if_exists='append', 166 | index=False) 167 | 168 | print("Optimizing...") 169 | self.conn.execute( 170 | "insert into search_data(search_data) values ('optimize');") 171 | self.conn.close() 172 | 173 | def build_search_documents(self): 174 | """tokenize and segment each transcript.""" 175 | self.tokenized_docs = [] 176 | self.search_docs = [] 177 | 178 | if not self.data: 179 | self.search_docs = [] 180 | return 181 | 182 | workers = cpu_count() 183 | print(f'build search documents with {workers} workers') 184 | 185 | with ProcessPoolExecutor(max_workers=workers) as executor: 186 | out = list( 187 | tqdm(executor.map(self.create_rolling_docs, self.data.items()), 188 | total=len(self.data))) 189 | 190 | self.search_docs = flatten_list(out) 191 | 192 | def process_substitutions(self): 193 | """Consistently mistranscribed words or regex patterns are replaced segment by segment.""" 194 | if not self.sub_dict: 195 | return 196 | for key, val in tqdm(self.data.items()): 197 | for item in val: 198 | for word, replacement in self.sub_dict.items(): 199 | item['text'] = re.sub(word, replacement, item['text']) 200 | 201 | def create_rolling_docs(self, x): 202 | """For a given transcript, chunk 300 words together to make an indexable document.""" 203 | i = 0 204 | all_chunk = [] 205 | key, data = x 206 | data = deque(data) 207 | while data: 208 | chunk = [] 209 | chunk_word_length = 0 210 | while data and chunk_word_length < self.word_limit: 211 | bit = data.popleft() 212 | bit['i'] = i 213 | i += 1 214 | chunk.append(bit) 215 | chunk_word_length += len(bit['text'].split(' ')) 216 | start_segment = chunk[0]['i'] 217 | end_segment = chunk[-1]['i'] 218 | 219 | start_time = chunk[0]['start'] 220 | 221 | full_text = ' '.join([x['text'] for x in chunk]) 222 | 223 | #url = self.make_url(start_time) 224 | 225 | all_chunk.append({ 226 | 'episode_key': key, 227 | 'text': full_text, 228 | 'start': start_time, 229 | 'end': chunk[-1]['end'], 230 | 'start_ts': self.make_timestamp(start_time), 231 | 'end_ts': self.make_timestamp(chunk[-1]['end']), 232 | 'start_segment': start_segment, 233 | 'end_segment': end_segment 234 | }) 235 | return all_chunk 236 | 237 | @staticmethod 238 | def make_timestamp(x): 239 | """Convert decimal seconds to a string H:M:S.Z timestamp""" 240 | hours = int(x // 3600) 241 | minutes = int((x - hours * 3600) // 60) 242 | seconds = x - hours * 3600 - minutes * 60 243 | return f"{process_hour(hours)}{minutes:02}:{seconds:05.2f}" 244 | 245 | 246 | class SearchTranscripts(LoadTranscripts): 247 | 248 | def __init__(self, input_prefix=''): 249 | """Load the index and connect database""" 250 | 251 | if input_prefix: 252 | input_prefix = input_prefix + '_' 253 | self.input_prefix = input_prefix 254 | print(f"Using SQL Lite with {input_prefix}main.db ") 255 | 256 | @property 257 | def conn(self): 258 | with sqlite3.connect(f'{self.input_prefix}main.db') as conn: 259 | return conn #kind of suprised this works 260 | 261 | def get_num_search_results(self, search, episode_range=None): 262 | if not episode_range: 263 | return next( 264 | self.conn.execute( 265 | "select count(rowid) from search_data where text match ?;", 266 | [my_escape_fts(search)]))[0] 267 | else: 268 | return next( 269 | self.conn.execute( 270 | "select count(rowid) from search_data where text match ? and cast(episode_key as integer) between ? and ?;", 271 | [ 272 | my_escape_fts(search), episode_range[0], 273 | episode_range[1] 274 | ]))[0] 275 | 276 | def search_bm25_chunk(self, 277 | search, 278 | episode_range=None, 279 | limit=50, 280 | offset=0, 281 | sort_by='score'): 282 | """Use the BM25 ordering to retrieve the top results from sql. limit and offset keyword argument provide for pagination.""" 283 | print(my_escape_fts(search)) 284 | if sort_by == 'score': 285 | sort_code = 'bm25(search_data)' 286 | elif sort_by == 'episode_key_asc': 287 | sort_code = 'cast(episode_key as integer) ASC, bm25(search_data)' 288 | elif sort_by == 'episode_key_desc': 289 | sort_code = 'cast(episode_key as integer) DESC, bm25(search_data)' 290 | if not episode_range: 291 | #not thrilled about the use of an fstring but it can only be one of the three optinos above, not user input. 292 | df = pd.read_sql( 293 | f"select bm25(search_data) as score, * from search_data where text MATCH ? order by {sort_code} limit ? offset ?;", 294 | con=self.conn, 295 | params=[my_escape_fts(search), limit, offset]) 296 | else: 297 | print(episode_range[0], episode_range[1]) 298 | df = pd.read_sql( 299 | f"select bm25(search_data) as score, * from search_data where text MATCH ? and cast(episode_key as integer) between ? and ? order by {sort_code} limit ? offset ?;", 300 | con=self.conn, 301 | params=[ 302 | my_escape_fts(search), episode_range[0], episode_range[1], 303 | limit, offset 304 | ]) 305 | return df 306 | 307 | def get_segment_detail(self, key, start, end): 308 | """Get the text of the appropriate segments from sql. a future version may create time stamp specicifc links for each section.""" 309 | return pd.read_sql( 310 | f"SELECT * from all_segments where episode_key = ? and segment BETWEEN ? and ?", 311 | con=self.conn, 312 | params=[key, start, end]) 313 | 314 | def search(self, search, **kwargs): 315 | """Search and return results wrapping exact matches in ** for markdown""" 316 | base_res = self.search_bm25_chunk(search, **kwargs) 317 | search = search.lower().strip('"') 318 | base_res['exact_match'] = base_res['text'].apply( 319 | lambda x: search in x.lower()).astype(int) 320 | base_res['text'] = base_res['text'].apply( 321 | lambda x: process_bold(x, search)) 322 | 323 | return base_res.sort_values(['exact_match', 'score'], 324 | ascending=[False, True]) 325 | 326 | 327 | def process_bold(x, search): 328 | """Wrap exact matches with double asterisks for markdown""" 329 | idx = x.lower().find(search.lower()) 330 | if idx != -1: 331 | return ''.join([ 332 | x[0:idx], '**', x[idx:idx + len(search)], '**', 333 | x[idx + len(search):] 334 | ]) 335 | return x 336 | 337 | 338 | def convert_timestamp(ts): 339 | """Convert a timestamp H:M:S.Z into decimal seconds""" 340 | return sum(float(x) * 60**i for i, x in enumerate(reversed(ts.split(':')))) 341 | 342 | 343 | def read_vtt(filename): 344 | """Load a VTT file into a list of dictionaries, similar to the json structure created by the whsiper.trascribe() python API.""" 345 | 346 | try: 347 | out = [] 348 | with open(filename, 'r') as f: 349 | _ = f.readline() # skip first two lines 350 | _ = f.readline() 351 | for line1 in f: 352 | if not line1.strip(): 353 | continue 354 | while not (line2 := next(f)): 355 | pass 356 | start, end = [x.strip() for x in line1.split("-->")] 357 | out.append({ 358 | 'start': convert_timestamp(start), 359 | 'end': convert_timestamp(end), 360 | 'text': line2.strip('\n'), 361 | }) 362 | except StopIteration: 363 | print("stop") 364 | return out 365 | 366 | 367 | def process_hour(x): 368 | """simple conditional for hour format""" 369 | if x: 370 | return f"{x:02}:" 371 | return '' 372 | --------------------------------------------------------------------------------