-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstream.py
More file actions
165 lines (131 loc) · 3.73 KB
/
stream.py
File metadata and controls
165 lines (131 loc) · 3.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Streamlit example using DSPy to summarize JSON from the Senzing SDK.
see copyright/license https://github.com/DerwenAI/dylifo/README.md
"""
import json
import logging
import pathlib
import sys
import tomllib
import typing
from dylifo import Profile, SummaryModule
from sz_semantics import Mask, SzClient
import dspy
import pandas as pd
import streamlit as st
@st.cache_resource
def get_config (
config_path: pathlib.Path,
) -> dict:
"""
Load configuration.
"""
with open(config_path, mode = "rb") as fp:
return tomllib.load(fp)
@st.cache_resource
def run_senzing (
config: dict,
data_sources: dict,
*,
debug: bool = False,
) -> typing.Tuple[ SzClient, dict ]:
"""
Set up Senzing gRPC client and run _entity resolution_.
"""
_sz: SzClient = SzClient(
config,
data_sources,
debug = debug,
)
_ents: dict = _sz.entity_resolution(
data_sources,
debug = debug,
)
return _sz, _ents
@st.cache_resource
def get_dspy_module (
config: dict,
) -> SummaryModule:
"""
Set up DSPy to run a module.
"""
return SummaryModule(
config,
run_local = config["dspy"]["run_local"],
)
@st.fragment
def select_entity (
_sz: SzClient,
_ents: dict,
dspy_module: SummaryModule,
*,
debug: bool = False,
) -> None:
"""
Main UI task as a `Streamlit.fragment`: select an entity,
then summarize.
"""
sz_mask: Mask = Mask()
option: str | None = st.selectbox(
"Which resolved entity?",
list(_ents.keys()),
index = None,
placeholder = "Select an entity to summarize...",
)
if option is not None:
ent: dict = _ents[option]
entity_id: int = ent.get("entity_id")
sz_json: str = _sz.get_entity(entity_id)
st.expander("subgraph:", icon = ":material/info:").json(sz_json)
st.expander("entity:", icon = ":material/info:").json(ent)
dat: dict = json.loads(sz_json)
masked_dat: typing.Any = sz_mask.mask_data(dat, debug = debug)
predict: dspy.Prediction = dspy_module(json.dumps(masked_dat))
## output
st.write(sz_mask.unmask_text(predict.summary))
rows: list = []
for row in predict.entity_rows:
if row.person in sz_mask.tokens:
row.person = sz_mask.tokens[row.person]
if row.data_source in sz_mask.tokens:
row.data_source = sz_mask.tokens[row.data_source]
if row.record_id in sz_mask.tokens:
row.record_id = sz_mask.tokens[row.record_id]
rows.append(row)
st.dataframe(
pd.DataFrame([
row.model_dump()
for row in rows
])
)
usage: dict = predict.get_lm_usage()
expand = st.expander("token usage:", icon = ":material/info:")
if len(usage) < 1:
expand.write("cached")
else:
expand.json(usage)
if __name__ == "__main__":
config: dict = get_config(pathlib.Path("config.toml"))
logger: logging.Logger = logging.getLogger(__name__)
logging.basicConfig(level = logging.WARNING) # DEBUG
data_sources: typing.Dict[ str, str ] = {
"CUSTOMERS": "data/customers.json",
"WATCHLIST": "data/watchlist.json",
"REFERENCE": "data/reference.json",
}
# underscore tells Streamlit this is a singleton resource
_sz, _ents = run_senzing(
config,
data_sources,
debug = False,
)
dspy_module: SummaryModule = get_dspy_module(config)
logger.info("set up, run only once")
## interaction
select_entity(
_sz,
_ents,
dspy_module,
)