Update app.py
Browse files
app.py
CHANGED
|
@@ -3,7 +3,6 @@ import json
|
|
| 3 |
import difflib
|
| 4 |
import re
|
| 5 |
|
| 6 |
-
# --- Fuzzy search utilities ---
|
| 7 |
def normalize(s):
|
| 8 |
return ' '.join(str(s).lower().replace("_", " ").replace("-", " ").replace(".", " ").split())
|
| 9 |
|
|
@@ -11,7 +10,6 @@ def is_fuzzy_match(a, b, threshold=0.7):
|
|
| 11 |
ratio = difflib.SequenceMatcher(None, a, b).ratio()
|
| 12 |
return ratio >= threshold or a in b or b in a
|
| 13 |
|
| 14 |
-
# --- Fuzzy, global string value search (all keys/fields) ---
|
| 15 |
def recursive_fuzzy_value_search(target_value):
|
| 16 |
matches = []
|
| 17 |
norm_target = normalize(target_value)
|
|
@@ -19,8 +17,8 @@ def recursive_fuzzy_value_search(target_value):
|
|
| 19 |
def _search(obj, path):
|
| 20 |
if isinstance(obj, dict):
|
| 21 |
for k, v in obj.items():
|
| 22 |
-
# Match ANY
|
| 23 |
-
if isinstance(v, str) and is_fuzzy_match(norm_target, normalize(v)):
|
| 24 |
matches.append({
|
| 25 |
"match_path": path + [k],
|
| 26 |
"matched_value": v,
|
|
@@ -31,7 +29,7 @@ def recursive_fuzzy_value_search(target_value):
|
|
| 31 |
# Check inside nested dicts
|
| 32 |
if isinstance(v, dict):
|
| 33 |
for nk, nv in v.items():
|
| 34 |
-
if isinstance(nv, str) and is_fuzzy_match(norm_target, normalize(nv)):
|
| 35 |
matches.append({
|
| 36 |
"match_path": path + [k, nk],
|
| 37 |
"matched_value": nv,
|
|
@@ -46,18 +44,17 @@ def recursive_fuzzy_value_search(target_value):
|
|
| 46 |
_search(data, [])
|
| 47 |
return matches
|
| 48 |
|
| 49 |
-
# --- Show all string values (for debug) ---
|
| 50 |
def show_all_strings():
|
| 51 |
found = []
|
| 52 |
for file_name, data in st.session_state.json_data.items():
|
| 53 |
def recursive(obj, path):
|
| 54 |
if isinstance(obj, dict):
|
| 55 |
for k, v in obj.items():
|
| 56 |
-
if isinstance(v, str):
|
| 57 |
found.append(f"{file_name} | {'.'.join(path + [k])} = {v}")
|
| 58 |
elif isinstance(v, dict):
|
| 59 |
for nk, nv in v.items():
|
| 60 |
-
if isinstance(nv, str):
|
| 61 |
found.append(f"{file_name} | {'.'.join(path + [k, nk])} = {nv}")
|
| 62 |
recursive(v, path + [k])
|
| 63 |
elif isinstance(obj, list):
|
|
@@ -66,9 +63,7 @@ def show_all_strings():
|
|
| 66 |
recursive(data, [])
|
| 67 |
return found
|
| 68 |
|
| 69 |
-
# --- Query handler (searches for any string value) ---
|
| 70 |
def handle_user_query(query):
|
| 71 |
-
# Extract likely search string (more flexible, still supports old user-centric queries)
|
| 72 |
patterns = [
|
| 73 |
r"(?:last\s*login.*?for|when\s+did)\s+([a-zA-Z0-9 _\-\.@]+)",
|
| 74 |
r"when\s+was\s+([a-zA-Z0-9 _\-\.@]+)\s+last\s+(?:login|logged\s*in)",
|
|
@@ -82,8 +77,8 @@ def handle_user_query(query):
|
|
| 82 |
found_value = m.group(1).strip()
|
| 83 |
break
|
| 84 |
if not found_value:
|
| 85 |
-
# Fallback: any word/phrase of
|
| 86 |
-
m = re.search(r"([A-Za-z0-9][A-Za-z0-9 _\-\.@]
|
| 87 |
if m:
|
| 88 |
found_value = m.group(1).strip()
|
| 89 |
if found_value:
|
|
@@ -97,7 +92,7 @@ def handle_user_query(query):
|
|
| 97 |
)
|
| 98 |
return "\n\n".join(answers)
|
| 99 |
else:
|
| 100 |
-
return "No valid search value detected. Try a person's name, product, device, etc."
|
| 101 |
|
| 102 |
# --- Streamlit UI setup ---
|
| 103 |
if "json_data" not in st.session_state:
|
|
@@ -110,7 +105,7 @@ if "files_loaded" not in st.session_state:
|
|
| 110 |
st.session_state.files_loaded = False
|
| 111 |
|
| 112 |
st.set_page_config(page_title="Flexible JSON Fuzzy Search", layout="wide")
|
| 113 |
-
st.title("Instant JSON-Backed Q&A (Flexible Fuzzy Search — All Keys!)")
|
| 114 |
|
| 115 |
uploaded_files = st.sidebar.file_uploader(
|
| 116 |
"Choose one or more JSON files", type="json", accept_multiple_files=True
|
|
@@ -130,7 +125,7 @@ elif not uploaded_files:
|
|
| 130 |
st.session_state.json_data.clear()
|
| 131 |
st.session_state.files_loaded = False
|
| 132 |
|
| 133 |
-
st.markdown("### Ask about ANY value (name, product, device, etc) — partials/typos/substring OK!")
|
| 134 |
for msg in st.session_state.messages:
|
| 135 |
if msg["role"] == "user":
|
| 136 |
st.markdown(f"<div style='color: #4F8BF9;'><b>User:</b> {msg['content']}</div>", unsafe_allow_html=True)
|
|
@@ -147,7 +142,7 @@ def send_message():
|
|
| 147 |
|
| 148 |
if st.session_state.json_data:
|
| 149 |
st.text_input("Your message:", key="temp_input", on_change=send_message)
|
| 150 |
-
if st.button("Show all
|
| 151 |
st.write(show_all_strings())
|
| 152 |
else:
|
| 153 |
st.info("Please upload at least one JSON file to start chatting.")
|
|
|
|
| 3 |
import difflib
|
| 4 |
import re
|
| 5 |
|
|
|
|
| 6 |
def normalize(s):
|
| 7 |
return ' '.join(str(s).lower().replace("_", " ").replace("-", " ").replace(".", " ").split())
|
| 8 |
|
|
|
|
| 10 |
ratio = difflib.SequenceMatcher(None, a, b).ratio()
|
| 11 |
return ratio >= threshold or a in b or b in a
|
| 12 |
|
|
|
|
| 13 |
def recursive_fuzzy_value_search(target_value):
|
| 14 |
matches = []
|
| 15 |
norm_target = normalize(target_value)
|
|
|
|
| 17 |
def _search(obj, path):
|
| 18 |
if isinstance(obj, dict):
|
| 19 |
for k, v in obj.items():
|
| 20 |
+
# Match ANY primitive value (str, int, float, bool)
|
| 21 |
+
if isinstance(v, (str, int, float, bool)) and is_fuzzy_match(norm_target, normalize(v)):
|
| 22 |
matches.append({
|
| 23 |
"match_path": path + [k],
|
| 24 |
"matched_value": v,
|
|
|
|
| 29 |
# Check inside nested dicts
|
| 30 |
if isinstance(v, dict):
|
| 31 |
for nk, nv in v.items():
|
| 32 |
+
if isinstance(nv, (str, int, float, bool)) and is_fuzzy_match(norm_target, normalize(nv)):
|
| 33 |
matches.append({
|
| 34 |
"match_path": path + [k, nk],
|
| 35 |
"matched_value": nv,
|
|
|
|
| 44 |
_search(data, [])
|
| 45 |
return matches
|
| 46 |
|
|
|
|
| 47 |
def show_all_strings():
|
| 48 |
found = []
|
| 49 |
for file_name, data in st.session_state.json_data.items():
|
| 50 |
def recursive(obj, path):
|
| 51 |
if isinstance(obj, dict):
|
| 52 |
for k, v in obj.items():
|
| 53 |
+
if isinstance(v, (str, int, float, bool)):
|
| 54 |
found.append(f"{file_name} | {'.'.join(path + [k])} = {v}")
|
| 55 |
elif isinstance(v, dict):
|
| 56 |
for nk, nv in v.items():
|
| 57 |
+
if isinstance(nv, (str, int, float, bool)):
|
| 58 |
found.append(f"{file_name} | {'.'.join(path + [k, nk])} = {nv}")
|
| 59 |
recursive(v, path + [k])
|
| 60 |
elif isinstance(obj, list):
|
|
|
|
| 63 |
recursive(data, [])
|
| 64 |
return found
|
| 65 |
|
|
|
|
| 66 |
def handle_user_query(query):
|
|
|
|
| 67 |
patterns = [
|
| 68 |
r"(?:last\s*login.*?for|when\s+did)\s+([a-zA-Z0-9 _\-\.@]+)",
|
| 69 |
r"when\s+was\s+([a-zA-Z0-9 _\-\.@]+)\s+last\s+(?:login|logged\s*in)",
|
|
|
|
| 77 |
found_value = m.group(1).strip()
|
| 78 |
break
|
| 79 |
if not found_value:
|
| 80 |
+
# Fallback: any word/phrase of 1+ char (letters, digits, spaces, dashes, underscores, dots)
|
| 81 |
+
m = re.search(r"([A-Za-z0-9][A-Za-z0-9 _\-\.@]*)", query)
|
| 82 |
if m:
|
| 83 |
found_value = m.group(1).strip()
|
| 84 |
if found_value:
|
|
|
|
| 92 |
)
|
| 93 |
return "\n\n".join(answers)
|
| 94 |
else:
|
| 95 |
+
return "No valid search value detected. Try a person's name, number, product, device, etc."
|
| 96 |
|
| 97 |
# --- Streamlit UI setup ---
|
| 98 |
if "json_data" not in st.session_state:
|
|
|
|
| 105 |
st.session_state.files_loaded = False
|
| 106 |
|
| 107 |
st.set_page_config(page_title="Flexible JSON Fuzzy Search", layout="wide")
|
| 108 |
+
st.title("Instant JSON-Backed Q&A (Flexible Fuzzy Search — All Keys & Types!)")
|
| 109 |
|
| 110 |
uploaded_files = st.sidebar.file_uploader(
|
| 111 |
"Choose one or more JSON files", type="json", accept_multiple_files=True
|
|
|
|
| 125 |
st.session_state.json_data.clear()
|
| 126 |
st.session_state.files_loaded = False
|
| 127 |
|
| 128 |
+
st.markdown("### Ask about ANY value (name, product, number, device, etc) — partials/typos/substring OK!")
|
| 129 |
for msg in st.session_state.messages:
|
| 130 |
if msg["role"] == "user":
|
| 131 |
st.markdown(f"<div style='color: #4F8BF9;'><b>User:</b> {msg['content']}</div>", unsafe_allow_html=True)
|
|
|
|
| 142 |
|
| 143 |
if st.session_state.json_data:
|
| 144 |
st.text_input("Your message:", key="temp_input", on_change=send_message)
|
| 145 |
+
if st.button("Show all values in uploaded JSONs"):
|
| 146 |
st.write(show_all_strings())
|
| 147 |
else:
|
| 148 |
st.info("Please upload at least one JSON file to start chatting.")
|