user_settings.py (2030B)
1 import csv 2 import os 3 from pathlib import Path 4 from typing import Dict, List, Tuple 5 from talon import resource 6 7 # NOTE: This method requires this module to be one folder below the top-level 8 # knausj folder. 9 SETTINGS_DIR = Path(__file__).parents[1] / "settings" 10 11 if not SETTINGS_DIR.is_dir(): 12 os.mkdir(SETTINGS_DIR) 13 14 15 def get_list_from_csv( 16 filename: str, headers: Tuple[str, str], default: Dict[str, str] = {} 17 ): 18 """Retrieves list from CSV""" 19 path = SETTINGS_DIR / filename 20 assert filename.endswith(".csv") 21 22 if not path.is_file(): 23 with open(path, "w", encoding="utf-8") as file: 24 writer = csv.writer(file) 25 writer.writerow(headers) 26 for key, value in default.items(): 27 writer.writerow([key] if key == value else [value, key]) 28 29 # Now read via resource to take advantage of talon's 30 # ability to reload this script for us when the resource changes 31 with resource.open(str(path), "r") as f: 32 rows = list(csv.reader(f)) 33 34 # print(str(rows)) 35 mapping = {} 36 if len(rows) >= 2: 37 actual_headers = rows[0] 38 if not actual_headers == list(headers): 39 print( 40 f'"{filename}": Malformed headers - {actual_headers}.' 41 + f" Should be {list(headers)}. Ignoring row." 42 ) 43 for row in rows[1:]: 44 if len(row) == 0: 45 # Windows newlines are sometimes read as empty rows. :champagne: 46 continue 47 if len(row) == 1: 48 output = spoken_form = row[0] 49 else: 50 output, spoken_form = row[:2] 51 if len(row) > 2: 52 print( 53 f'"{filename}": More than two values in row: {row}.' 54 + " Ignoring the extras." 55 ) 56 # Leading/trailing whitespace in spoken form can prevent recognition. 57 spoken_form = spoken_form.strip() 58 mapping[spoken_form] = output 59 60 return mapping