Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import tensorflow as tf
|
| 3 |
+
from sklearn.model_selection import train_test_split
|
| 4 |
+
from transformers import T5Tokenizer, TFT5ForConditionalGeneration
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
# ========== STEP 1: Load and Prepare Dataset ==========
|
| 8 |
+
# NOTE: On Hugging Face Spaces, upload your CSV file in the repo and update path here:
|
| 9 |
+
df = pd.read_csv("/gmustafa413/ABSA_Dataset") # Make sure this CSV is uploaded in your repo root
|
| 10 |
+
|
| 11 |
+
# Convert 'aspectTerms' string to list and create input/output pairs
|
| 12 |
+
def format_example(row):
|
| 13 |
+
input_text = row["raw_text"]
|
| 14 |
+
try:
|
| 15 |
+
aspect_terms = eval(row["aspectTerms"])
|
| 16 |
+
except:
|
| 17 |
+
aspect_terms = []
|
| 18 |
+
|
| 19 |
+
if not aspect_terms or aspect_terms == '[]':
|
| 20 |
+
output_text = "noaspectterm:none"
|
| 21 |
+
else:
|
| 22 |
+
output_text = ", ".join([f"{d['term']}:{d['polarity']}" for d in aspect_terms if d['term']])
|
| 23 |
+
return input_text, output_text
|
| 24 |
+
|
| 25 |
+
df["input_text"], df["target_text"] = zip(*df.apply(format_example, axis=1))
|
| 26 |
+
|
| 27 |
+
# Split data
|
| 28 |
+
train_texts, val_texts, train_labels, val_labels = train_test_split(
|
| 29 |
+
df["input_text"], df["target_text"], test_size=0.1, random_state=42
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# ========== STEP 2: Tokenization ==========
|
| 33 |
+
tokenizer = T5Tokenizer.from_pretrained("t5-base")
|
| 34 |
+
max_input_length = 128
|
| 35 |
+
max_target_length = 64
|
| 36 |
+
|
| 37 |
+
def tokenize_data(inputs, targets):
|
| 38 |
+
inputs_enc = tokenizer(
|
| 39 |
+
list(inputs), padding="max_length", truncation=True,
|
| 40 |
+
max_length=max_input_length, return_tensors="tf"
|
| 41 |
+
)
|
| 42 |
+
targets_enc = tokenizer(
|
| 43 |
+
list(targets), padding="max_length", truncation=True,
|
| 44 |
+
max_length=max_target_length, return_tensors="tf"
|
| 45 |
+
)
|
| 46 |
+
return inputs_enc.input_ids, targets_enc.input_ids
|
| 47 |
+
|
| 48 |
+
train_inputs, train_labels = tokenize_data(train_texts, train_labels)
|
| 49 |
+
val_inputs, val_labels = tokenize_data(val_texts, val_labels)
|
| 50 |
+
|
| 51 |
+
# ========== STEP 3: Create TensorFlow Datasets ==========
|
| 52 |
+
BATCH_SIZE = 8
|
| 53 |
+
|
| 54 |
+
train_dataset = tf.data.Dataset.from_tensor_slices(({"input_ids": train_inputs}, train_labels))
|
| 55 |
+
val_dataset = tf.data.Dataset.from_tensor_slices(({"input_ids": val_inputs}, val_labels))
|
| 56 |
+
|
| 57 |
+
train_dataset = train_dataset.shuffle(1000).batch(BATCH_SIZE)
|
| 58 |
+
val_dataset = val_dataset.batch(BATCH_SIZE)
|
| 59 |
+
|
| 60 |
+
# ========== STEP 4: Model Training ==========
|
| 61 |
+
model = TFT5ForConditionalGeneration.from_pretrained("t5-base")
|
| 62 |
+
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-5)
|
| 63 |
+
model.compile(optimizer=optimizer)
|
| 64 |
+
|
| 65 |
+
print("🔧 Training started...")
|
| 66 |
+
model.fit(train_dataset, validation_data=val_dataset, epochs=3)
|
| 67 |
+
print("✅ Training complete!")
|
| 68 |
+
|
| 69 |
+
# Save model and tokenizer (optional here if you want to save locally)
|
| 70 |
+
# model.save_pretrained("t5_absa_tf_model")
|
| 71 |
+
# tokenizer.save_pretrained("t5_absa_tf_model")
|
| 72 |
+
|
| 73 |
+
# ========== STEP 5: Gradio Interface ==========
|
| 74 |
+
# Using trained model & tokenizer directly from memory
|
| 75 |
+
|
| 76 |
+
def preprocess_input(text):
|
| 77 |
+
instruction = """Definition: The output will be the aspects (both implicit and explicit) and the aspect's sentiment polarity. In cases where there are no aspects the output should be noaspectterm:none.
|
| 78 |
+
Positive example:
|
| 79 |
+
input: With the great variety on the menu , I eat here often and never get bored.
|
| 80 |
+
output: menu:positive
|
| 81 |
+
Now complete the following example-
|
| 82 |
+
input: """
|
| 83 |
+
return instruction + text + "\noutput:"
|
| 84 |
+
|
| 85 |
+
def predict_aspects(text):
|
| 86 |
+
processed = preprocess_input(text)
|
| 87 |
+
inputs = tokenizer(processed, return_tensors="tf", truncation=True, padding=True)
|
| 88 |
+
outputs = model.generate(
|
| 89 |
+
input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"],
|
| 90 |
+
max_length=64
|
| 91 |
+
)
|
| 92 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 93 |
+
|
| 94 |
+
interface = gr.Interface(
|
| 95 |
+
fn=predict_aspects,
|
| 96 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your review here..."),
|
| 97 |
+
outputs=gr.Textbox(label="Extracted aspect:sentiment pairs"),
|
| 98 |
+
title="Aspect-Based Sentiment Analysis (ABSA)",
|
| 99 |
+
description="Fine-tuned T5 model for extracting aspects and their sentiment from review text.",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if __name__ == "__main__":
|
| 103 |
+
interface.launch()
|