Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
3 |
+
|
4 |
+
import streamlit as st
|
5 |
+
from st_aggrid import AgGrid
|
6 |
+
import pandas as pd
|
7 |
+
from transformers import pipeline, T5ForConditionalGeneration, T5Tokenizer
|
8 |
+
|
9 |
+
st.set_page_config(layout="wide")
|
10 |
+
|
11 |
+
style = '''
|
12 |
+
<style>
|
13 |
+
body {background-color: #F5F5F5; color: #000000;}
|
14 |
+
header {visibility: hidden;}
|
15 |
+
div.block-container {padding-top:4rem;}
|
16 |
+
section[data-testid="stSidebar"] div:first-child {
|
17 |
+
padding-top: 0;
|
18 |
+
}
|
19 |
+
.font {
|
20 |
+
text-align:center;
|
21 |
+
font-family:sans-serif;font-size: 1.25rem;}
|
22 |
+
</style>
|
23 |
+
'''
|
24 |
+
st.markdown(style, unsafe_allow_html=True)
|
25 |
+
|
26 |
+
st.markdown('<p style="font-family:sans-serif;font-size: 1.9rem;"> HertogAI Q&A table V1 using TAPAS and Text Generated</p>', unsafe_allow_html=True)
|
27 |
+
st.markdown("<p style='font-family:sans-serif;font-size: 0.9rem;'>Pre-trained TAPAS model runs on max 64 rows and 32 columns data. Make sure the file data doesn't exceed these dimensions.</p>", unsafe_allow_html=True)
|
28 |
+
|
29 |
+
# Initialize TAPAS and Hugging Face Model (T5 for NLP generation)
|
30 |
+
tqa = pipeline(task="table-question-answering",
|
31 |
+
model="google/tapas-large-finetuned-wtq",
|
32 |
+
device="cpu")
|
33 |
+
|
34 |
+
model_name = "t5-small" # You can use a larger model or GPT as needed
|
35 |
+
tokenizer = T5Tokenizer.from_pretrained(model_name)
|
36 |
+
model = T5ForConditionalGeneration.from_pretrained(model_name)
|
37 |
+
|
38 |
+
# Function to generate natural language from TAPAS output
|
39 |
+
def generate_nlp_from_tapas(tapas_output, df):
|
40 |
+
"""
|
41 |
+
Use Hugging Face's T5 model to generate natural language text from TAPAS output.
|
42 |
+
"""
|
43 |
+
try:
|
44 |
+
# Construct prompt using TAPAS output
|
45 |
+
answer = tapas_output['answer']
|
46 |
+
coordinates = tapas_output['coordinates']
|
47 |
+
answer_data = [df.iloc[row, col] for row, col in coordinates]
|
48 |
+
|
49 |
+
# Format the prompt for NLP model
|
50 |
+
prompt = f"Answer: {answer}. Data Location: Rows {coordinates}, Values: {answer_data}. Please summarize this information in a natural language sentence."
|
51 |
+
|
52 |
+
# Tokenize input and generate response
|
53 |
+
inputs = tokenizer.encode(prompt, return_tensors="pt", truncation=True, max_length=512)
|
54 |
+
outputs = model.generate(inputs, max_length=100, num_beams=5, early_stopping=True)
|
55 |
+
|
56 |
+
# Decode and return the generated response
|
57 |
+
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
58 |
+
return response
|
59 |
+
except Exception as e:
|
60 |
+
return f"Error generating response: {str(e)}"
|
61 |
+
|
62 |
+
|
63 |
+
file_name = st.sidebar.file_uploader("Upload file:", type=['csv', 'xlsx'])
|
64 |
+
|
65 |
+
if file_name is None:
|
66 |
+
st.markdown('<p class="font">Please upload an excel or csv file </p>', unsafe_allow_html=True)
|
67 |
+
else:
|
68 |
+
try:
|
69 |
+
# Check file type and handle reading accordingly
|
70 |
+
if file_name.name.endswith('.csv'):
|
71 |
+
df = pd.read_csv(file_name, sep=';', encoding='ISO-8859-1') # Adjust encoding if needed
|
72 |
+
elif file_name.name.endswith('.xlsx'):
|
73 |
+
df = pd.read_excel(file_name, engine='openpyxl') # Use openpyxl to read .xlsx files
|
74 |
+
else:
|
75 |
+
st.error("Unsupported file type")
|
76 |
+
df = None
|
77 |
+
|
78 |
+
# Continue with further processing if df is loaded
|
79 |
+
if df is not None:
|
80 |
+
numeric_columns = df.select_dtypes(include=['object']).columns
|
81 |
+
for col in numeric_columns:
|
82 |
+
df[col] = pd.to_numeric(df[col], errors='ignore')
|
83 |
+
|
84 |
+
st.write("Original Data:")
|
85 |
+
st.write(df)
|
86 |
+
|
87 |
+
# Create a copy for numerical operations
|
88 |
+
df_numeric = df.copy()
|
89 |
+
df = df.astype(str)
|
90 |
+
|
91 |
+
grid_response = AgGrid(
|
92 |
+
df.head(5),
|
93 |
+
columns_auto_size_mode='FIT_CONTENTS',
|
94 |
+
editable=True,
|
95 |
+
height=300,
|
96 |
+
width='100%',
|
97 |
+
)
|
98 |
+
|
99 |
+
except Exception as e:
|
100 |
+
st.error(f"Error reading file: {str(e)}")
|
101 |
+
|
102 |
+
question = st.text_input('Type your question')
|
103 |
+
|
104 |
+
with st.spinner():
|
105 |
+
if(st.button('Answer')):
|
106 |
+
try:
|
107 |
+
# Get the raw answer from TAPAS
|
108 |
+
raw_answer = tqa(table=df, query=question, truncation=True)
|
109 |
+
|
110 |
+
st.markdown("<p style='font-family:sans-serif;font-size: 0.9rem;'> Raw Result: </p>", unsafe_allow_html=True)
|
111 |
+
st.success(raw_answer)
|
112 |
+
|
113 |
+
# Use Hugging Face's T5 model to generate NLP text from TAPAS output
|
114 |
+
final_answer = generate_nlp_from_tapas(raw_answer, df)
|
115 |
+
|
116 |
+
# Display the generated answer in a simple format
|
117 |
+
st.markdown("<p style='font-family:sans-serif;font-size: 0.9rem;'> Generated Answer: </p>", unsafe_allow_html=True)
|
118 |
+
st.success(final_answer)
|
119 |
+
|
120 |
+
except Exception as e:
|
121 |
+
st.warning(f"Error: {str(e)} - Please retype your question and ensure it is correctly formatted.")
|
122 |
+
|