Agnist commited on
Commit
f22a32c
·
verified ·
1 Parent(s): 91d6e3e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2 -47
app.py CHANGED
@@ -1,44 +1,3 @@
1
- import tensorflow as tf
2
- from tensorflow import keras
3
- from tensorflow.keras.layers import TextVectorization, Embedding, GlobalAveragePooling1D, Dense
4
- import pandas as pd
5
- from sklearn.model_selection import train_test_split
6
- from datasets import load_dataset
7
- import gradio as gr
8
-
9
- # Load dataset
10
- ds = load_dataset("uhoui/text-tone-classifier")
11
- df = pd.DataFrame(ds['train'])
12
-
13
- # Remove classes with only one sample
14
- class_counts = df['label'].value_counts()
15
- classes_to_keep = class_counts[class_counts > 1].index
16
- df = df[df['label'].isin(classes_to_keep)]
17
-
18
- # Convert labels to categorical
19
- df['label'] = pd.Categorical(df['label'])
20
- df['label'] = df['label'].cat.codes # Convert to numerical codes
21
-
22
- # Split data without stratification
23
- train_texts, test_texts, train_labels, test_labels = train_test_split(
24
- df['text'], df['label'], test_size=0.2, random_state=42
25
- )
26
-
27
- # Convert labels to NumPy arrays for TensorFlow
28
- train_labels = train_labels.to_numpy()
29
- test_labels = test_labels.to_numpy()
30
-
31
- # Convert Pandas Series to TensorFlow datasets
32
- train_ds = tf.data.Dataset.from_tensor_slices((train_texts.values, train_labels))
33
- test_ds = tf.data.Dataset.from_tensor_slices((test_texts.values, test_labels))
34
-
35
- # Text Vectorization
36
- vocab_size = 10000
37
- vectorizer = TextVectorization(max_tokens=vocab_size, output_mode="int", output_sequence_length=50)
38
- vectorizer.adapt(train_texts.to_numpy())
39
-
40
- # Build the model
41
- def build_model():
42
  model = keras.Sequential([
43
  vectorizer,
44
  Embedding(input_dim=vocab_size, output_dim=64),
@@ -49,22 +8,18 @@ def build_model():
49
 
50
  model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
51
  return model
52
-
53
  # Train the model
54
  model = build_model()
55
  model.fit(train_ds.batch(32), epochs=10, validation_data=test_ds.batch(32))
56
-
57
  # Function to make predictions
58
  def predict(text):
59
  # Vectorize the input text
60
  vectorized_text = vectorizer([text]) # Use the vectorizer to transform the input
61
- prediction = model.predict(vectorized_text) # No need to expand dimensions
62
  predicted_label = tf.argmax(prediction, axis=1).numpy()[0]
63
  return df['label'].cat.categories[predicted_label]
64
-
65
  # Gradio interface
66
  iface = gr.Interface(fn=predict, inputs="text", outputs="text", title="Text Tone Sentiment Analysis",
67
  description="Enter a text to analyze its tone (e.g., joy, depression, contentment).")
68
-
69
  if __name__ == "__main__":
70
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  model = keras.Sequential([
2
  vectorizer,
3
  Embedding(input_dim=vocab_size, output_dim=64),
 
8
 
9
  model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
10
  return model
 
11
  # Train the model
12
  model = build_model()
13
  model.fit(train_ds.batch(32), epochs=10, validation_data=test_ds.batch(32))
 
14
  # Function to make predictions
15
  def predict(text):
16
  # Vectorize the input text
17
  vectorized_text = vectorizer([text]) # Use the vectorizer to transform the input
18
+ prediction = model.predict(vectorized_text) # Pass the vectorized input to the model
19
  predicted_label = tf.argmax(prediction, axis=1).numpy()[0]
20
  return df['label'].cat.categories[predicted_label]
 
21
  # Gradio interface
22
  iface = gr.Interface(fn=predict, inputs="text", outputs="text", title="Text Tone Sentiment Analysis",
23
  description="Enter a text to analyze its tone (e.g., joy, depression, contentment).")
 
24
  if __name__ == "__main__":
25
+ iface.launch()