diff scobot/service/query.py @ 17:0d72635fc501

reloadIndexIfChanged
author drewp@bigasterisk.com
date Fri, 19 Jul 2024 00:59:45 -0700
parents 7a87ba2f00d9
children
line wrap: on
line diff
--- a/scobot/service/query.py	Fri Jul 19 00:49:38 2024 -0700
+++ b/scobot/service/query.py	Fri Jul 19 00:59:45 2024 -0700
@@ -45,24 +45,37 @@
 # rebuild(client, embedding_fn, dim=embedding_fn.dim)
 # search(q, embedding_fn, client)
 
+indexPath = Path('data/build/index0')
+
 
 @asynccontextmanager
 async def lifespan(app: FastAPI):
-    app.state.index = SearchIndexRO(Path('data/build/index0'))
+    reloadIndexIfChanged(app)
     yield
 
+
 app = FastAPI(lifespan=lifespan)
 
+
+def reloadIndexIfChanged(app: FastAPI):
+    if ((not hasattr(app.state, 'indexMtime'))
+            or (app.state.indexMtime != indexPath.stat().st_mtime)):
+        print('reloading index')
+        app.state.indexMtime = indexPath.stat().st_mtime
+        app.state.index = SearchIndexRO(indexPath)
+
+
 @app.get("/sco/query")
 def read_query1(q: str):
+    reloadIndexIfChanged(app)
     index = app.state.index
 
     query = QueryParser("phrase", index.ix.schema).parse(q)
     pprint(query)
     results = index.searcher.search(query)
-    docs=[]
+    docs = []
     for res in results:
-        doc=dict(res)
+        doc = dict(res)
         doc['snippetHtml'] = html.escape(doc['phrase'])
         docs.append(doc)
     return {"results": docs}