Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import pandas as pd
|
| 4 |
+
from pyspark.sql import SparkSession
|
| 5 |
+
|
| 6 |
+
# ββ Initialize Spark βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 7 |
+
spark = (
|
| 8 |
+
SparkSession
|
| 9 |
+
.builder
|
| 10 |
+
.master("local[*]")
|
| 11 |
+
.appName("HF Spark Demo")
|
| 12 |
+
.getOrCreate()
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
# ββ Demo 1: Word Count ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
def count_words(text: str) -> str:
|
| 17 |
+
df = spark.createDataFrame([(text,)], ["sentence"])
|
| 18 |
+
result = df.selectExpr("size(split(sentence, ' ')) as word_count").collect()[0]
|
| 19 |
+
return f"Your input has {result['word_count']} words."
|
| 20 |
+
|
| 21 |
+
# ββ Demo 2: JSON Data Explorer βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
def load_example_json() -> pd.DataFrame:
|
| 23 |
+
# Read the example JSON file into a Spark DataFrame
|
| 24 |
+
df = spark.read.json("example_data.json")
|
| 25 |
+
# Convert to pandas for Gradio display
|
| 26 |
+
return df.toPandas()
|
| 27 |
+
|
| 28 |
+
# ββ Build Gradio Interface ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
+
with gr.Blocks() as demo:
|
| 30 |
+
gr.Markdown("## π₯ Spark + Gradio Demo on 0.0.0.0")
|
| 31 |
+
|
| 32 |
+
with gr.Tab("Word Count"):
|
| 33 |
+
txt = gr.Textbox(lines=3, placeholder="Type something here...", label="Input Text")
|
| 34 |
+
out = gr.Textbox(label="Word Count Result")
|
| 35 |
+
txt.submit(count_words, txt, out)
|
| 36 |
+
gr.Button("Count Words").click(count_words, txt, out)
|
| 37 |
+
|
| 38 |
+
with gr.Tab("JSON Data Explorer"):
|
| 39 |
+
df_table = gr.Dataframe(
|
| 40 |
+
value=load_example_json(),
|
| 41 |
+
label="Example Data",
|
| 42 |
+
interactive=False
|
| 43 |
+
)
|
| 44 |
+
gr.Button("Reload Data").click(load_example_json, None, df_table)
|
| 45 |
+
|
| 46 |
+
# ββ Launch βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
demo.launch(
|
| 49 |
+
server_name="0.0.0.0",
|
| 50 |
+
server_port=7860,
|
| 51 |
+
enable_queue=True
|
| 52 |
+
)
|