Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,209 +1,215 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
import
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
logging.
|
15 |
-
|
16 |
-
|
17 |
-
)
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
)
|
33 |
-
|
34 |
-
model
|
35 |
-
model
|
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 |
-
query_lower
|
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 |
-
st.
|
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 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
st.
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
"
|
195 |
-
"
|
196 |
-
"
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import streamlit as st
|
3 |
+
import pandas as pd
|
4 |
+
import torch
|
5 |
+
from transformers import TapexTokenizer, BartForConditionalGeneration
|
6 |
+
import xml.etree.ElementTree as ET
|
7 |
+
from io import StringIO
|
8 |
+
import logging
|
9 |
+
from datetime import datetime
|
10 |
+
import time
|
11 |
+
|
12 |
+
# Configure logging
|
13 |
+
logging.basicConfig(
|
14 |
+
level=logging.INFO,
|
15 |
+
format='%(asctime)s - %(levelname)s - %(message)s'
|
16 |
+
)
|
17 |
+
logger = logging.getLogger(__name__)
|
18 |
+
|
19 |
+
@st.cache_resource
|
20 |
+
def load_model():
|
21 |
+
"""
|
22 |
+
Load and cache the TAPEX model and tokenizer using Streamlit's caching
|
23 |
+
"""
|
24 |
+
try:
|
25 |
+
tokenizer = TapexTokenizer.from_pretrained(
|
26 |
+
"microsoft/tapex-large-finetuned-wtq",
|
27 |
+
model_max_length=1024
|
28 |
+
)
|
29 |
+
model = BartForConditionalGeneration.from_pretrained(
|
30 |
+
"microsoft/tapex-large-finetuned-wtq"
|
31 |
+
)
|
32 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
33 |
+
model = model.to(device)
|
34 |
+
model.eval()
|
35 |
+
return tokenizer, model
|
36 |
+
except Exception as e:
|
37 |
+
st.error(f"Error loading model: {str(e)}")
|
38 |
+
return None, None
|
39 |
+
|
40 |
+
def parse_xml_to_dataframe(xml_string: str):
|
41 |
+
"""
|
42 |
+
Parse XML string to DataFrame with error handling
|
43 |
+
"""
|
44 |
+
try:
|
45 |
+
tree = ET.parse(StringIO(xml_string))
|
46 |
+
root = tree.getroot()
|
47 |
+
|
48 |
+
data = []
|
49 |
+
columns = set()
|
50 |
+
|
51 |
+
# First pass: collect all possible columns
|
52 |
+
for record in root.findall('.//record'):
|
53 |
+
columns.update(elem.tag for elem in record)
|
54 |
+
|
55 |
+
# Second pass: create data rows
|
56 |
+
for record in root.findall('.//record'):
|
57 |
+
row_data = {col: None for col in columns}
|
58 |
+
for elem in record:
|
59 |
+
row_data[elem.tag] = elem.text
|
60 |
+
data.append(row_data)
|
61 |
+
|
62 |
+
df = pd.DataFrame(data)
|
63 |
+
|
64 |
+
# Convert numeric columns (automatically detect)
|
65 |
+
for col in df.columns:
|
66 |
+
try:
|
67 |
+
df[col] = pd.to_numeric(df[col])
|
68 |
+
except:
|
69 |
+
continue
|
70 |
+
|
71 |
+
return df, None
|
72 |
+
except Exception as e:
|
73 |
+
return None, f"Error parsing XML: {str(e)}"
|
74 |
+
|
75 |
+
def process_query(tokenizer, model, df, query: str):
|
76 |
+
"""
|
77 |
+
Process a single query using the TAPEX model
|
78 |
+
"""
|
79 |
+
try:
|
80 |
+
start_time = time.time()
|
81 |
+
|
82 |
+
# Handle direct DataFrame operations for common queries
|
83 |
+
query_lower = query.lower()
|
84 |
+
if "highest" in query_lower or "maximum" in query_lower:
|
85 |
+
for col in df.select_dtypes(include=['number']).columns:
|
86 |
+
if col.lower() in query_lower:
|
87 |
+
return df.loc[df[col].idxmax()].to_dict()
|
88 |
+
elif "average" in query_lower or "mean" in query_lower:
|
89 |
+
for col in df.select_dtypes(include=['number']).columns:
|
90 |
+
if col.lower() in query_lower:
|
91 |
+
return f"Average {col}: {df[col].mean():.2f}"
|
92 |
+
elif "total" in query_lower or "sum" in query_lower:
|
93 |
+
for col in df.select_dtypes(include=['number']).columns:
|
94 |
+
if col.lower() in query_lower:
|
95 |
+
return f"Total {col}: {df[col].sum():.2f}"
|
96 |
+
|
97 |
+
# Use TAPEX for more complex queries
|
98 |
+
with torch.no_grad():
|
99 |
+
encoding = tokenizer(
|
100 |
+
table=df.astype(str),
|
101 |
+
query=query,
|
102 |
+
return_tensors="pt",
|
103 |
+
padding=True,
|
104 |
+
truncation=True
|
105 |
+
)
|
106 |
+
outputs = model.generate(**encoding)
|
107 |
+
answer = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
|
108 |
+
|
109 |
+
processing_time = time.time() - start_time
|
110 |
+
return f"Answer: {answer} (Processing time: {processing_time:.2f}s)"
|
111 |
+
|
112 |
+
except Exception as e:
|
113 |
+
return f"Error processing query: {str(e)}"
|
114 |
+
|
115 |
+
def main():
|
116 |
+
st.title("XML Data Query System")
|
117 |
+
st.write("Upload your XML data and ask questions about it!")
|
118 |
+
|
119 |
+
# Initialize session state for XML input and query if not exists
|
120 |
+
if 'xml_input' not in st.session_state:
|
121 |
+
st.session_state.xml_input = ""
|
122 |
+
if 'current_query' not in st.session_state:
|
123 |
+
st.session_state.current_query = ""
|
124 |
+
|
125 |
+
# Load model
|
126 |
+
with st.spinner("Loading TAPEX model... (this may take a few moments)"):
|
127 |
+
tokenizer, model = load_model()
|
128 |
+
if tokenizer is None or model is None:
|
129 |
+
st.error("Failed to load the model. Please refresh the page.")
|
130 |
+
return
|
131 |
+
|
132 |
+
# XML Input
|
133 |
+
xml_input = st.text_area(
|
134 |
+
"Enter your XML data here:",
|
135 |
+
value=st.session_state.xml_input,
|
136 |
+
height=200,
|
137 |
+
help="Paste your XML data here. Make sure it's properly formatted."
|
138 |
+
)
|
139 |
+
|
140 |
+
# Sample XML button
|
141 |
+
if st.button("Load Sample XML"):
|
142 |
+
st.session_state.xml_input = """<?xml version="1.0" encoding="UTF-8"?>
|
143 |
+
<data>
|
144 |
+
<records>
|
145 |
+
<record>
|
146 |
+
<company>Apple</company>
|
147 |
+
<revenue>365.7</revenue>
|
148 |
+
<employees>147000</employees>
|
149 |
+
<year>2021</year>
|
150 |
+
</record>
|
151 |
+
<record>
|
152 |
+
<company>Microsoft</company>
|
153 |
+
<revenue>168.1</revenue>
|
154 |
+
<employees>181000</employees>
|
155 |
+
<year>2021</year>
|
156 |
+
</record>
|
157 |
+
<record>
|
158 |
+
<company>Amazon</company>
|
159 |
+
<revenue>386.1</revenue>
|
160 |
+
<employees>1608000</employees>
|
161 |
+
<year>2021</year>
|
162 |
+
</record>
|
163 |
+
</records>
|
164 |
+
</data>"""
|
165 |
+
st.rerun()
|
166 |
+
|
167 |
+
if xml_input:
|
168 |
+
df, error = parse_xml_to_dataframe(xml_input)
|
169 |
+
if error:
|
170 |
+
st.error(error)
|
171 |
+
else:
|
172 |
+
st.success("XML parsed successfully!")
|
173 |
+
|
174 |
+
# Display DataFrame
|
175 |
+
st.subheader("Parsed Data:")
|
176 |
+
st.dataframe(df)
|
177 |
+
|
178 |
+
# Query input
|
179 |
+
query = st.text_input(
|
180 |
+
"Enter your question about the data:",
|
181 |
+
value=st.session_state.current_query,
|
182 |
+
help="Example: 'Which company has the highest revenue?'"
|
183 |
+
)
|
184 |
+
|
185 |
+
# Process query
|
186 |
+
if query:
|
187 |
+
with st.spinner("Processing query..."):
|
188 |
+
result = process_query(tokenizer, model, df, query)
|
189 |
+
st.write(result)
|
190 |
+
|
191 |
+
# Sample queries
|
192 |
+
st.subheader("Sample Questions (Click to use):")
|
193 |
+
sample_queries = [
|
194 |
+
"Which company has the highest revenue?",
|
195 |
+
"What is the average revenue of all companies?",
|
196 |
+
"How many employees does Microsoft have?",
|
197 |
+
"Which company has the most employees?",
|
198 |
+
"What is the total revenue of all companies?"
|
199 |
+
]
|
200 |
+
|
201 |
+
# Create columns for sample query buttons
|
202 |
+
cols = st.columns(len(sample_queries))
|
203 |
+
for idx, (col, sample_query) in enumerate(zip(cols, sample_queries)):
|
204 |
+
with col:
|
205 |
+
if st.button(f"Query {idx + 1}", help=sample_query, key=f"query_btn_{idx}"):
|
206 |
+
st.session_state.current_query = sample_query
|
207 |
+
st.rerun()
|
208 |
+
|
209 |
+
# Display the sample queries as text for reference
|
210 |
+
with st.expander("View all sample questions"):
|
211 |
+
for idx, query in enumerate(sample_queries, 1):
|
212 |
+
st.write(f"{idx}. {query}")
|
213 |
+
|
214 |
+
if __name__ == "__main__":
|
215 |
+
main()
|