JaganathC commited on
Commit
26e452e
·
verified ·
1 Parent(s): 946e98d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -46
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import streamlit as st
2
- import json
3
  import pandas as pd
4
  import re
5
  from io import BytesIO
@@ -8,22 +7,22 @@ from io import BytesIO
8
  # Page Setup
9
  # -------------------------------------------------
10
  st.set_page_config(page_title="JSON Text to Excel", layout="wide")
11
- st.title("📘 JSON Text to Excel Converter")
12
 
13
  st.markdown(
14
- "Paste **JSON-like text** below (copied from config files). "
15
- "The app will auto-correct formatting and generate Excel data."
16
  )
17
 
18
  # -------------------------------------------------
19
- # Session-safe text input (HF FIX)
20
  # -------------------------------------------------
21
  if "json_text" not in st.session_state:
22
  st.session_state.json_text = ""
23
 
24
- json_text = st.text_area(
25
  "JSON Data (Text Format)",
26
- height=360,
27
  key="json_text",
28
  placeholder='''"LABELS": {
29
  "ICN": {
@@ -33,37 +32,31 @@ json_text = st.text_area(
33
  )
34
 
35
  # -------------------------------------------------
36
- # Helper: Clean JSON-like text
37
  # -------------------------------------------------
38
- def normalize_json(text: str) -> str:
39
- text = text.strip()
40
 
41
- # Remove trailing commas before } or ]
42
- text = re.sub(r",\s*([}\]])", r"\1", text)
43
 
44
- # Wrap inside {} if missing
45
- if not text.startswith("{"):
46
- text = "{" + text
47
- if not text.endswith("}"):
48
- text = text + "}"
49
 
50
- return text
 
51
 
52
- # -------------------------------------------------
53
- # Flatten JSON Logic
54
- # -------------------------------------------------
55
- def flatten_json(data):
56
- rows = []
57
 
58
- def walk(obj):
59
- for k, v in obj.items():
60
- if isinstance(v, dict):
61
- rows.append([k, None])
62
- walk(v)
63
- else:
64
- rows.append([k, v])
65
-
66
- walk(data)
67
 
68
  return pd.DataFrame(
69
  rows,
@@ -77,28 +70,24 @@ if st.button("Generate Excel Data", type="primary"):
77
  raw_text = st.session_state.json_text
78
 
79
  if raw_text.strip() == "":
80
- st.warning("⚠️ Please paste JSON-like data.")
81
  else:
82
- try:
83
- clean_json = normalize_json(raw_text)
84
- parsed = json.loads(clean_json)
85
-
86
- df = flatten_json(parsed)
87
 
 
 
 
88
  st.subheader("📊 Excel Preview")
89
  st.dataframe(df, use_container_width=True)
90
 
91
- # Excel generation
92
  buffer = BytesIO()
93
  with pd.ExcelWriter(buffer, engine="xlsxwriter") as writer:
94
  df.to_excel(writer, index=False, sheet_name="Labels")
95
 
96
  st.download_button(
97
- label="📥 Download Excel File",
98
- data=buffer.getvalue(),
99
- file_name="JSON_Text_To_Excel.xlsx",
100
- mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
101
  )
102
-
103
- except Exception as e:
104
- st.error(f"❌ Unable to parse input: {e}")
 
1
  import streamlit as st
 
2
  import pandas as pd
3
  import re
4
  from io import BytesIO
 
7
  # Page Setup
8
  # -------------------------------------------------
9
  st.set_page_config(page_title="JSON Text to Excel", layout="wide")
10
+ st.title("📘 JSON Text Excel Converter")
11
 
12
  st.markdown(
13
+ "Paste JSON-like **text data** (not strict JSON). "
14
+ "The app parses it line-by-line and generates Excel output."
15
  )
16
 
17
  # -------------------------------------------------
18
+ # Text Input (HF Safe)
19
  # -------------------------------------------------
20
  if "json_text" not in st.session_state:
21
  st.session_state.json_text = ""
22
 
23
+ text_input = st.text_area(
24
  "JSON Data (Text Format)",
25
+ height=380,
26
  key="json_text",
27
  placeholder='''"LABELS": {
28
  "ICN": {
 
32
  )
33
 
34
  # -------------------------------------------------
35
+ # Line-by-line Parser (ROBUST)
36
  # -------------------------------------------------
37
+ def parse_text_to_rows(text):
38
+ rows = []
39
 
40
+ for line in text.splitlines():
41
+ line = line.strip()
42
 
43
+ if not line:
44
+ continue
 
 
 
45
 
46
+ # Remove trailing commas
47
+ line = line.rstrip(",")
48
 
49
+ # Match "KEY": {
50
+ obj_match = re.match(r'"([^"]+)"\s*:\s*\{', line)
51
+ if obj_match:
52
+ rows.append([obj_match.group(1), None])
53
+ continue
54
 
55
+ # Match "KEY": "VALUE"
56
+ kv_match = re.match(r'"([^"]+)"\s*:\s*"([^"]*)"', line)
57
+ if kv_match:
58
+ rows.append([kv_match.group(1), kv_match.group(2)])
59
+ continue
 
 
 
 
60
 
61
  return pd.DataFrame(
62
  rows,
 
70
  raw_text = st.session_state.json_text
71
 
72
  if raw_text.strip() == "":
73
+ st.warning("⚠️ Please paste JSON-like text data.")
74
  else:
75
+ df = parse_text_to_rows(raw_text)
 
 
 
 
76
 
77
+ if df.empty:
78
+ st.error("❌ No valid key/value data found.")
79
+ else:
80
  st.subheader("📊 Excel Preview")
81
  st.dataframe(df, use_container_width=True)
82
 
83
+ # Excel Export
84
  buffer = BytesIO()
85
  with pd.ExcelWriter(buffer, engine="xlsxwriter") as writer:
86
  df.to_excel(writer, index=False, sheet_name="Labels")
87
 
88
  st.download_button(
89
+ "📥 Download Excel File",
90
+ buffer.getvalue(),
91
+ "JSON_Text_To_Excel.xlsx",
92
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
93
  )