#!/usr/bin/env python3 """Read-only offline exact/prefix/substring queries of an admitted SQLite snapshot. Advanced and transliterated queries scan local edition rows; no network or model. Greek transliteration is deliberately lossy spelling access, not translation. """ import argparse,csv,json,sqlite3,sys,unicodedata,re from pathlib import Path BOUNDARY='zzmagaliaboundaryzz' def normalize_quotes(value): """Canonicalize explicit query quote pairs, without changing source text/apostrophes.""" pairs={'"':'"','“':'”','"':'"','「':'」','『':'』'};closers={'”','」','』'};unsupported={'„','‟','〝','〞','〟','«','»'};active=None;out=[] for ch in str(value): if ch in unsupported:raise ValueError('Use matching straight, curly, fullwidth or Chinese corner double quotes around a phrase.') if active: if ch==active:out.append('"');active=None elif ch in pairs or ch in closers:raise ValueError('Use a matching pair of phrase quotes; mixed or nested double quotes are unsupported.') else:out.append(ch) elif ch in pairs:active=pairs[ch];out.append('"') elif ch in closers:raise ValueError('A closing phrase quote needs its matching opening quote.') else:out.append(ch) if active:raise ValueError('Close the quoted phrase before searching.') return ''.join(out) def normalize(s): text=''.join(c for c in unicodedata.normalize('NFD',str(s).replace('\ufffc',' '+BOUNDARY+' ').lower()) if not unicodedata.category(c).startswith('M')).replace('ς','σ') return ' '.join(re.findall(r'[^\W_]+',text)) def beta_code(value): table=dict(zip('abgdezhqiklmncoprstufxywv','αβγδεζηθικλμνξοπρστυφχψωϝ'));out='';capital=False;letter=False;i=0 while i300 or BOUNDARY in q.lower() or '\ufffc' in q:raise ValueError('Use at most300 characters and no reserved boundary marker.') q=normalize_quotes(q) if q.count('"')%2:raise ValueError('Close the quoted phrase before searching.') unquoted=re.sub(r'"[^"]*"',' ',q) if re.search(r'[?~]',q) or (input_mode!='betacode' and '*' in q) or re.search(r'\b(?:AND|OR|NOT|NEAR)\b',unquoted) or re.search(r'(?:^|\s)[A-Za-z][A-Za-z-]*:',unquoted):raise ValueError('Choose exact/prefix/substring. Boolean, proximity, field and wildcard syntax is unsupported; use quoted phrases and -exclude.') if input_mode=='transliteration' and any(c.isalpha() and not unicodedata.name(c,'').startswith('LATIN') for c in q):raise ValueError('Use Latin-script letters in Greek transliteration mode.') interpreted=beta_code(q) if input_mode=='betacode' else q;terms=[] for m in re.finditer(r'(-?)(?:"([^"]+)"|([^\s"]+))',interpreted): value=latin_fold(m[2] or m[3]) if input_mode=='transliteration' else normalize(m[2] or m[3]) if not value:continue words=value.split();minimum=2 if mode=='prefix' else 3 if mode=='substring' else 1 if any(len(w)16:raise ValueError('Use at most16 terms.') return terms,interpreted def word_matches(token,word,t): if token==BOUNDARY:return False value=greek_fold(token) if t['input']=='transliteration' else token if value is None:return False return value.startswith(word) if t['mode']=='prefix' else word in value if t['mode']=='substring' else value==word def contains(tokens,t):return any(all(word_matches(tokens[i+j],word,t) for j,word in enumerate(t['words'])) for i in range(len(tokens)-len(t['words'])+1)) def matches(record,layer,terms): tokens=normalize(record[layer]).split() return all(not contains(tokens,t) if t['exclude'] else contains(tokens,t) for t in terms) def main(): p=argparse.ArgumentParser(description=__doc__);p.add_argument('database',type=Path);p.add_argument('query');p.add_argument('--layer',choices=['reading','conservative'],default='reading');p.add_argument('--format',choices=['jsonl','csv'],default='jsonl');p.add_argument('--limit',type=int,default=1000);p.add_argument('--match',choices=['exact','prefix','substring'],default='exact');p.add_argument('--input',choices=['unicode','betacode','transliteration'],default='unicode');a=p.parse_args() try:terms,interpreted=parse(a.query,a.match,a.input) except ValueError as e:p.error(str(e)) if not a.database.is_file() or not 1<=a.limit<=100000:p.error('Use an existing database and a limit between1 and100000.') con=sqlite3.connect(a.database.resolve().as_uri()+'?mode=ro',uri=True) if a.match=='exact' and a.input!='transliteration': clauses=[(t['exclude'],'"'+t['value'].replace('"','""')+'"') for t in terms];expression=' AND '.join(v for neg,v in clauses if not neg) for neg,v in clauses: if neg:expression+=' NOT '+v expression=a.layer+' : ('+expression+')' rows=con.execute('SELECT r.record_json FROM text_fts f JOIN records r ON r.record_id=f.record_id WHERE text_fts MATCH ? ORDER BY r.record_id',(expression,)) else:rows=con.execute('SELECT record_json FROM records ORDER BY record_id') records=[] for row in rows: rec=json.loads(row[0]) if matches(rec,a.layer,terms):records.append({**rec,'search_query':a.query,'match_mode':a.match,'input_mode':a.input,'interpreted_query':interpreted}) if len(records)>a.limit:break con.close() if len(records)>a.limit:print('Result truncated at requested limit; more matches exist.',file=sys.stderr) records=records[:a.limit] if a.format=='jsonl': for rec in records:print(json.dumps(rec,ensure_ascii=False)) else: fields=['search_query','match_mode','input_mode','interpreted_query','record_id','corpus','source_id','edition','title','language','date','source_sha256','source_url','license',a.layer];w=csv.DictWriter(sys.stdout,fieldnames=fields,extrasaction='ignore');w.writeheader() for rec in records: row={k:rec.get(k) for k in fields} for k,v in row.items(): if isinstance(v,str) and v.startswith(('=','+','-','@','\t','\r')):row[k]="'"+v w.writerow(row) return 0 if __name__=='__main__':raise SystemExit(main())