Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,30 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from typing import Dict, List, Union
|
| 2 |
from google.cloud import aiplatform
|
| 3 |
from google.protobuf import json_format
|
| 4 |
from google.protobuf.struct_pb2 import Value
|
| 5 |
import os
|
| 6 |
import re
|
| 7 |
-
import pandas as pd
|
| 8 |
-
import plotly.express as px
|
| 9 |
-
import plotly.graph_objects as go
|
| 10 |
-
import streamlit as st
|
| 11 |
-
import nltk
|
| 12 |
import tempfile
|
| 13 |
|
| 14 |
-
#
|
| 15 |
def get_credentials():
|
| 16 |
-
creds_json_str = os.getenv("JSONSTR") # Get
|
| 17 |
if creds_json_str is None:
|
| 18 |
raise ValueError("GOOGLE_APPLICATION_CREDENTIALS_JSON not found in environment")
|
| 19 |
|
| 20 |
# Create a temporary file
|
| 21 |
with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as temp:
|
| 22 |
-
temp.write(creds_json_str) # Write in
|
| 23 |
-
temp_filename = temp.name
|
| 24 |
|
| 25 |
return temp_filename
|
| 26 |
|
| 27 |
-
# Set
|
| 28 |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_credentials()
|
| 29 |
|
| 30 |
max_seq_length = 2048
|
|
@@ -39,6 +40,7 @@ except LookupError:
|
|
| 39 |
|
| 40 |
text_split_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 41 |
|
|
|
|
| 42 |
def predict_custom_trained_model_sample(
|
| 43 |
project: str,
|
| 44 |
endpoint_id: str,
|
|
@@ -68,7 +70,7 @@ def predict_custom_trained_model_sample(
|
|
| 68 |
split_predictions = clean_prediction.split()
|
| 69 |
predictions_list.extend(split_predictions)
|
| 70 |
else:
|
| 71 |
-
print("prediction (unknown type, skipping):", prediction)
|
| 72 |
return [emotion for emotion in predictions_list if emotion in d_emotion.values()]
|
| 73 |
|
| 74 |
d_emotion = {0: 'admiration', 1: 'amusement', 2: 'anger', 3: 'annoyance', 4: 'approval', 5: 'caring', 6: 'confusion',
|
|
@@ -77,28 +79,30 @@ d_emotion = {0: 'admiration', 1: 'amusement', 2: 'anger', 3: 'annoyance', 4: 'ap
|
|
| 77 |
20: 'optimism', 21: 'pride', 22: 'realization', 23: 'relief', 24: 'remorse', 25: 'sadness', 26: 'surprise',
|
| 78 |
27: 'neutral'}
|
| 79 |
|
| 80 |
-
st.write("Write or paste any number of document texts to
|
| 81 |
|
| 82 |
-
# Define
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
# Add button to fill in sample text
|
| 86 |
if st.button("Use Sample Text"):
|
| 87 |
-
user_input =
|
| 88 |
else:
|
| 89 |
user_input = st.text_area('Enter Text to Analyze')
|
| 90 |
|
| 91 |
button = st.button("Analyze")
|
| 92 |
|
| 93 |
-
if
|
| 94 |
-
alpaca_prompt = """Below is a conversation between a human and an AI agent.
|
| 95 |
### Instruction:
|
| 96 |
predict the emotion word or words
|
| 97 |
### Input:
|
| 98 |
{}
|
| 99 |
### Response:
|
| 100 |
"""
|
| 101 |
-
|
| 102 |
instances = []
|
| 103 |
input_array = text_split_tokenizer.tokenize(user_input)
|
| 104 |
for sentence in input_array:
|
|
@@ -144,8 +148,6 @@ if user_input and button:
|
|
| 144 |
|
| 145 |
@st.cache_data
|
| 146 |
def get_emotion_heatmap(predictions):
|
| 147 |
-
# Create a matrix for heatmap
|
| 148 |
-
# Count occurrences of each emotion
|
| 149 |
emotion_counts = pd.Series(predictions).value_counts().reset_index()
|
| 150 |
emotion_counts.columns = ['Emotion', 'Count']
|
| 151 |
|
|
@@ -163,9 +165,9 @@ if user_input and button:
|
|
| 163 |
))
|
| 164 |
fig.update_layout(title='Emotion Heatmap', xaxis_title='Predicted Emotion', yaxis_title='Predicted Emotion')
|
| 165 |
return fig
|
| 166 |
-
|
| 167 |
fig_heatmap = get_emotion_heatmap(predictions)
|
| 168 |
-
|
| 169 |
tab1, tab2, tab3 = st.tabs(["Emotion Analysis", "Emotion Counts Distribution", "Heatmap"])
|
| 170 |
with tab1:
|
| 171 |
st.plotly_chart(fig_pie)
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import numpy as np
|
| 3 |
+
import nltk
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
import pandas as pd
|
| 7 |
from typing import Dict, List, Union
|
| 8 |
from google.cloud import aiplatform
|
| 9 |
from google.protobuf import json_format
|
| 10 |
from google.protobuf.struct_pb2 import Value
|
| 11 |
import os
|
| 12 |
import re
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
import tempfile
|
| 14 |
|
| 15 |
+
# Function to get credentials from environment variable and create a temporary file
|
| 16 |
def get_credentials():
|
| 17 |
+
creds_json_str = os.getenv("JSONSTR") # Get JSON credentials stored as a string
|
| 18 |
if creds_json_str is None:
|
| 19 |
raise ValueError("GOOGLE_APPLICATION_CREDENTIALS_JSON not found in environment")
|
| 20 |
|
| 21 |
# Create a temporary file
|
| 22 |
with tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as temp:
|
| 23 |
+
temp.write(creds_json_str) # Write in JSON format
|
| 24 |
+
temp_filename = temp.name
|
| 25 |
|
| 26 |
return temp_filename
|
| 27 |
|
| 28 |
+
# Set environment variable for Google application credentials
|
| 29 |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_credentials()
|
| 30 |
|
| 31 |
max_seq_length = 2048
|
|
|
|
| 40 |
|
| 41 |
text_split_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
|
| 42 |
|
| 43 |
+
# Function to predict emotions using the custom trained model
|
| 44 |
def predict_custom_trained_model_sample(
|
| 45 |
project: str,
|
| 46 |
endpoint_id: str,
|
|
|
|
| 70 |
split_predictions = clean_prediction.split()
|
| 71 |
predictions_list.extend(split_predictions)
|
| 72 |
else:
|
| 73 |
+
print(" prediction (unknown type, skipping):", prediction)
|
| 74 |
return [emotion for emotion in predictions_list if emotion in d_emotion.values()]
|
| 75 |
|
| 76 |
d_emotion = {0: 'admiration', 1: 'amusement', 2: 'anger', 3: 'annoyance', 4: 'approval', 5: 'caring', 6: 'confusion',
|
|
|
|
| 79 |
20: 'optimism', 21: 'pride', 22: 'realization', 23: 'relief', 24: 'remorse', 25: 'sadness', 26: 'surprise',
|
| 80 |
27: 'neutral'}
|
| 81 |
|
| 82 |
+
st.write("Write or paste any number of document texts to analyse the emotion percentage with your document")
|
| 83 |
|
| 84 |
+
# Define the sample text
|
| 85 |
+
sample_text = ("Once, in a small village nestled in the rolling hills of Tuscany, lived an elderly woman named Isabella. "
|
| 86 |
+
"She had spent her entire life in this village, raising her children and caring for her garden, which was the most "
|
| 87 |
+
"beautiful in the region. Her husband, Marco, had passed away many years ago, leaving her with a heart full of memories "
|
| 88 |
+
"and a small, quaint house that overlooked the lush vineyards.")
|
| 89 |
|
| 90 |
# Add button to fill in sample text
|
| 91 |
if st.button("Use Sample Text"):
|
| 92 |
+
user_input = sample_text
|
| 93 |
else:
|
| 94 |
user_input = st.text_area('Enter Text to Analyze')
|
| 95 |
|
| 96 |
button = st.button("Analyze")
|
| 97 |
|
| 98 |
+
if button and user_input:
|
| 99 |
+
alpaca_prompt = """Below is a conversation between a human and an AI agent. write a response based on the input.
|
| 100 |
### Instruction:
|
| 101 |
predict the emotion word or words
|
| 102 |
### Input:
|
| 103 |
{}
|
| 104 |
### Response:
|
| 105 |
"""
|
|
|
|
| 106 |
instances = []
|
| 107 |
input_array = text_split_tokenizer.tokenize(user_input)
|
| 108 |
for sentence in input_array:
|
|
|
|
| 148 |
|
| 149 |
@st.cache_data
|
| 150 |
def get_emotion_heatmap(predictions):
|
|
|
|
|
|
|
| 151 |
emotion_counts = pd.Series(predictions).value_counts().reset_index()
|
| 152 |
emotion_counts.columns = ['Emotion', 'Count']
|
| 153 |
|
|
|
|
| 165 |
))
|
| 166 |
fig.update_layout(title='Emotion Heatmap', xaxis_title='Predicted Emotion', yaxis_title='Predicted Emotion')
|
| 167 |
return fig
|
| 168 |
+
|
| 169 |
fig_heatmap = get_emotion_heatmap(predictions)
|
| 170 |
+
|
| 171 |
tab1, tab2, tab3 = st.tabs(["Emotion Analysis", "Emotion Counts Distribution", "Heatmap"])
|
| 172 |
with tab1:
|
| 173 |
st.plotly_chart(fig_pie)
|