import streamlit as st import pandas as pd # Custom CSS for better styling st.markdown(""" """, unsafe_allow_html=True) # Main Title st.markdown('
Question Answering Over Tables with TAPAS and Spark NLP
', unsafe_allow_html=True) # Overview Section st.markdown("""

As data becomes increasingly complex, extracting meaningful insights from tabular data is more important than ever. TAPAS, a transformer-based model developed by Google, is designed specifically to handle question-answering over tables. By combining TAPAS with Spark NLP, we can leverage the power of distributed computing to process large datasets efficiently.

This guide will walk you through the process of setting up TAPAS in Spark NLP, implementing two specific models (table_qa_tapas_base_finetuned_wtq and table_qa_tapas_base_finetuned_sqa), and understanding their best use cases.

""", unsafe_allow_html=True) # Introduction to TAPAS and Spark NLP st.markdown('
Introduction to TAPAS and Spark NLP
', unsafe_allow_html=True) # What is TAPAS? st.markdown("""

What is TAPAS?

TAPAS (Table Parsing Supervised via Pre-trained Language Models) is a model that extends the BERT architecture to handle tabular data. Unlike traditional models that require flattening tables into text, TAPAS can directly interpret tables, making it a powerful tool for answering questions that involve tabular data.

""", unsafe_allow_html=True) # Why Use TAPAS with Spark NLP? st.markdown("""

Why Use TAPAS with Spark NLP?

Spark NLP, developed by John Snow Labs, is an open-source library that provides state-of-the-art natural language processing capabilities within a distributed computing framework. Integrating TAPAS with Spark NLP allows you to scale your question-answering tasks across large datasets, making it ideal for big data environments.

""", unsafe_allow_html=True) # Pipeline and Results st.markdown('
Pipeline and Results
', unsafe_allow_html=True) st.markdown("""

In this section, we’ll build a pipeline using Spark NLP to process a table and answer questions about the data it contains. We will utilize two different TAPAS models, each suited for different types of queries.

""", unsafe_allow_html=True) # Step 1: Creating the Data st.markdown("""

Step 1: Creating the Data

We'll start by creating a Spark DataFrame that includes a table in JSON format and a set of questions.

""", unsafe_allow_html=True) st.code(""" json_data = ''' { "header": ["name", "money", "age"], "rows": [ ["Donald Trump", "$100,000,000", "75"], ["Elon Musk", "$20,000,000,000,000", "55"] ] } ''' queries = [ "Who earns less than 200,000,000?", "Who earns 100,000,000?", "How much money has Donald Trump?", "How old are they?", "How much money have they total?", "Who earns more than Donald Trump?" ] data = spark.createDataFrame([[json_data, " ".join(queries)]])\\ .toDF("table_json", "questions") """, language="python") # Step 2: Assembling the Pipeline st.markdown("""

Step 2: Assembling the Pipeline

We will now set up a Spark NLP pipeline that includes the necessary annotators for processing the table and questions.

""", unsafe_allow_html=True) st.code(""" from sparknlp.annotator import TapasForQuestionAnswering, SentenceDetector from sparknlp.base import MultiDocumentAssembler, TableAssembler from pyspark.ml import Pipeline from pyspark.sql import functions as F # Step 1: Transforms raw texts to `document` annotation document_assembler = MultiDocumentAssembler() \\ .setInputCols("table_json", "questions") \\ .setOutputCols("document_table", "document_questions") # Step 2: Getting the sentences sentence_detector = SentenceDetector() \\ .setInputCols(["document_questions"]) \\ .setOutputCol("questions") # Step 3: Get the tables table_assembler = TableAssembler()\\ .setInputCols(["document_table"])\\ .setOutputCol("table") # WTQ TAPAS model tapas_wtq = TapasForQuestionAnswering\\ .pretrained("table_qa_tapas_base_finetuned_wtq", "en")\\ .setInputCols(["questions", "table"])\\ .setOutputCol("answers_wtq") # SQA TAPAS model tapas_sqa = TapasForQuestionAnswering\\ .pretrained("table_qa_tapas_base_finetuned_sqa", "en")\\ .setInputCols(["questions", "table"])\\ .setOutputCol("answers_sqa") # Define pipeline pipeline = Pipeline(stages=[ document_assembler, sentence_detector, table_assembler, tapas_wtq, tapas_sqa ]) # Fit and transform data model = pipeline.fit(data) result = model.transform(data) """, language="python") # Step 3: Viewing the Results st.markdown("""

Step 3: Viewing the Results

After processing, we can explore the results generated by each model:

""", unsafe_allow_html=True) st.code(""" # WTQ Model Results: result.select(F.explode(result.answers_wtq)).show(truncate=False) """, language="python") st.text(""" +--------------------------------------+ |col | +--------------------------------------+ |Donald Trump | |Donald Trump | |SUM($100,000,000) | |AVERAGE(75, 55) | |SUM($100,000,000, $20,000,000,000,000)| |Elon Musk | +--------------------------------------+ """) st.code(""" # SQA Model Results: result.select(F.explode(result.answers_sqa)).show(truncate=False) """, language="python") st.text(""" +---------------------------------+ |col | +---------------------------------+ |Donald Trump | |Donald Trump | |$100,000,000 | |75, 55 | |$100,000,000, $20,000,000,000,000| |Elon Musk | +---------------------------------+ """) # Comparing Results st.markdown("""

Comparing Results

To better understand the differences, we can compare the results from both models side by side:

""", unsafe_allow_html=True) st.code(""" result.select(F.explode(F.arrays_zip(result.questions.result, result.answers_sqa.result, result.answers_wtq.result)).alias("cols"))\\ .select(F.expr("cols['0']").alias("question"), F.expr("cols['1']").alias("answer_sqa"), F.expr("cols['2']").alias("answer_wtq")).show(truncate=False) """, language="python") st.text(""" +---------------------------------+---------------------------------+--------------------------------------+ |question |answer_sqa |answer_wtq | +---------------------------------+---------------------------------+--------------------------------------+ |Who earns less than 200,000,000? |Donald Trump |Donald Trump | |Who earns 100,000,000? |Donald Trump |Donald Trump | |How much money has Donald Trump? |$100,000,000 |SUM($100,000,000) | |How old are they? |75, 55 |AVERAGE(75, 55) | |How much money have they total? |$100,000,000, $20,000,000,000,000|SUM($100,000,000, $20,000,000,000,000)| |Who earns more than Donald Trump?|Elon Musk |Elon Musk | +---------------------------------+---------------------------------+--------------------------------------+ """) # One-Liner Alternative st.markdown("""

One-Liner Alternative

For those who prefer a simpler approach, John Snow Labs offers a one-liner API to quickly get answers using TAPAS models.

""", unsafe_allow_html=True) st.code(""" #Downliad the johnsnowlabs library pip install johnsnowlabs """, language="bash") st.code(""" import pandas as pd from johnsnowlabs import nlp # Create the context DataFrame context_df = pd.DataFrame({ 'name': ['Donald Trump', 'Elon Musk'], 'money': ['$100,000,000', '$20,000,000,000,000'], 'age': ['75', '55'] }) # Define the questions questions = [ "Who earns less than 200,000,000?", "Who earns 100,000,000?", "How much money has Donald Trump?", "How old are they?", "How much money have they total?", "Who earns more than Donald Trump?" ] # Combine context and questions into a tuple tapas_data = (context_df, questions) # Use the one-liner API with the WTQ model answers_wtq = nlp.load('en.answer_question.tapas.wtq.large_finetuned').predict(tapas_data) answers_wtq[['sentence', 'tapas_qa_UNIQUE_answer']] """, language="python") # Define the data as a list of dictionaries data = { "sentence": [ "Who earns less than 200,000,000?", "Who earns 100,000,000?", "How much money has Donald Trump?", "How old are they?", "How much money have they total? Who earns more..." ], "tapas_qa_UNIQUE_answer": [ "Donald Trump", "Donald Trump", "SUM($100,000,000)", "SUM(55)", "SUM($20,000,000,000,000)" ] } st.dataframe(pd.DataFrame(data)) # Model Information and Use Cases st.markdown("""

Model Information and Use Cases

Understanding the strengths of each TAPAS model can help you choose the right tool for your task.

  • table_qa_tapas_base_finetuned_wtq
    • Best for: answering questions involving table-wide aggregation (e.g., sums, averages).
  • table_qa_tapas_base_finetuned_sqa
    • Best for: answering questions in a sequential question-answering context, where the current question depends on previous answers.
""", unsafe_allow_html=True) # Conclusion st.markdown("""

Conclusion

TAPAS, integrated with Spark NLP, provides a powerful solution for question-answering over tables, capable of handling both complex aggregation queries and straightforward Q&A tasks. Whether you're working with large datasets or simple tables, TAPAS offers flexibility and scalability. The table_qa_tapas_base_finetuned_wtq model excels in aggregation tasks, while table_qa_tapas_base_finetuned_sqa is best for direct, sequential question-answering.

By following this guide, you can efficiently implement TAPAS in your own projects, leveraging Spark NLP's powerful processing capabilities to extract insights from your data.

""", unsafe_allow_html=True) # References st.markdown(""" """, unsafe_allow_html=True) # Community & Support st.markdown('
Community & Support
', unsafe_allow_html=True) st.markdown("""
  • Official Website: Documentation and examples
  • Slack: Live discussion with the community and team
  • GitHub: Bug reports, feature requests, and contributions
  • Medium: Spark NLP articles
  • YouTube: Video tutorials
""", unsafe_allow_html=True)