Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829308 unmodified lines39404142434423 unmodified lines686970717273742 unmodified lines777879808182838485868788899091929394959697989910010110210310439 unmodified lines14414514614714814915015111 unmodified lines163164165166167168169170171from typing import Dict, List, Unionfrom google.cloud import aiplatformfrom google.protobuf import json_formatfrom google.protobuf.struct_pb2 import Valueimport osimport reimport pandas as pdimport plotly.express as pximport plotly.graph_objects as goimport streamlit as stimport nltkimport tempfile# Process of getting credentialsdef get_credentials():creds_json_str = os.getenv("JSONSTR") # Get json credentials stored as a stringif creds_json_str is None:raise ValueError("GOOGLE_APPLICATION_CREDENTIALS_JSON not found in environment")# Create a temporary filewith tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as temp:temp.write(creds_json_str) # Write in json formattemp_filename = temp.namereturn temp_filename# Set the credentialsos.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_credentials()max_seq_length = 20488 unmodified linestext_split_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')def predict_custom_trained_model_sample(project: str,endpoint_id: str,23 unmodified linessplit_predictions = clean_prediction.split()predictions_list.extend(split_predictions)else:print("prediction (unknown type, skipping):", prediction)return [emotion for emotion in predictions_list if emotion in d_emotion.values()]d_emotion = {0: 'admiration', 1: 'amusement', 2: 'anger', 3: 'annoyance', 4: 'approval', 5: 'caring', 6: 'confusion',2 unmodified lines20: 'optimism', 21: 'pride', 22: 'realization', 23: 'relief', 24: 'remorse', 25: 'sadness', 26: 'surprise',27: 'neutral'}st.write("Write or paste any number of document texts to analyze the emotion percentage within your document")# Define user_input outside the conditional blockuser_input = ""# Add button to fill in sample textif st.button("Use Sample Text"):user_input = "Once, in a small village nestled in the rolling hills of Tuscany, lived an elderly woman named Isabella. She had spent her entire life in this village, raising her children and caring for her garden, which was the most beautiful in the region. Her husband, Marco, had passed away many years ago, leaving her with a heart full of memories and a small, quaint house that overlooked the lush vineyards."else:user_input = st.text_area('Enter Text to Analyze')button = st.button("Analyze")if user_input and button:alpaca_prompt = """Below is a conversation between a human and an AI agent. Write a response based on the input.### Instruction:predict the emotion word or words### Input:{}### Response:"""instances = []input_array = text_split_tokenizer.tokenize(user_input)for sentence in input_array:39 unmodified lines@st.cache_datadef get_emotion_heatmap(predictions):# Create a matrix for heatmap# Count occurrences of each emotionemotion_counts = pd.Series(predictions).value_counts().reset_index()emotion_counts.columns = ['Emotion', 'Count']11 unmodified lines))fig.update_layout(title='Emotion Heatmap', xaxis_title='Predicted Emotion', yaxis_title='Predicted Emotion')return figfig_heatmap = get_emotion_heatmap(predictions)tab1, tab2, tab3 = st.tabs(["Emotion Analysis", "Emotion Counts Distribution", "Heatmap"])with tab1:st.plotly_chart(fig_pie)123456789101112131415161718192021222324252627282930318 unmodified lines4041424344454623 unmodified lines707172737475762 unmodified lines79808182838485868788899091929394959697989910010110210310410510610710839 unmodified lines14814915015115215311 unmodified lines165166167168169170171172173import streamlit as stimport numpy as npimport nltkimport plotly.express as pximport plotly.graph_objects as goimport pandas as pdfrom typing import Dict, List, Unionfrom google.cloud import aiplatformfrom google.protobuf import json_formatfrom google.protobuf.struct_pb2 import Valueimport osimport reimport tempfile# Function to get credentials from environment variable and create a temporary filedef get_credentials():creds_json_str = os.getenv("JSONSTR") # Get JSON credentials stored as a stringif creds_json_str is None:raise ValueError("GOOGLE_APPLICATION_CREDENTIALS_JSON not found in environment")# Create a temporary filewith tempfile.NamedTemporaryFile(mode="w+", delete=False, suffix=".json") as temp:temp.write(creds_json_str) # Write in JSON formattemp_filename = temp.namereturn temp_filename# Set environment variable for Google application credentialsos.environ["GOOGLE_APPLICATION_CREDENTIALS"] = get_credentials()max_seq_length = 20488 unmodified linestext_split_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')# Function to predict emotions using the custom trained modeldef predict_custom_trained_model_sample(project: str,endpoint_id: str,23 unmodified linessplit_predictions = clean_prediction.split()predictions_list.extend(split_predictions)else:print(" prediction (unknown type, skipping):", prediction)return [emotion for emotion in predictions_list if emotion in d_emotion.values()]d_emotion = {0: 'admiration', 1: 'amusement', 2: 'anger', 3: 'annoyance', 4: 'approval', 5: 'caring', 6: 'confusion',2 unmodified lines20: 'optimism', 21: 'pride', 22: 'realization', 23: 'relief', 24: 'remorse', 25: 'sadness', 26: 'surprise',27: 'neutral'}st.write("Write or paste any number of document texts to analyse the emotion percentage with your document")# Define the sample textsample_text = ("Once, in a small village nestled in the rolling hills of Tuscany, lived an elderly woman named Isabella. ""She had spent her entire life in this village, raising her children and caring for her garden, which was the most ""beautiful in the region. Her husband, Marco, had passed away many years ago, leaving her with a heart full of memories ""and a small, quaint house that overlooked the lush vineyards.")# Add button to fill in sample textif st.button("Use Sample Text"):user_input = sample_textelse:user_input = st.text_area('Enter Text to Analyze')button = st.button("Analyze")if button and user_input:alpaca_prompt = """Below is a conversation between a human and an AI agent. write a response based on the input.### Instruction:predict the emotion word or words### Input:{}### Response:"""instances = []input_array = text_split_tokenizer.tokenize(user_input)for sentence in input_array:39 unmodified lines@st.cache_datadef get_emotion_heatmap(predictions):emotion_counts = pd.Series(predictions).value_counts().reset_index()emotion_counts.columns = ['Emotion', 'Count']11 unmodified lines))fig.update_layout(title='Emotion Heatmap', xaxis_title='Predicted Emotion', yaxis_title='Predicted Emotion')return figfig_heatmap = get_emotion_heatmap(predictions)tab1, tab2, tab3 = st.tabs(["Emotion Analysis", "Emotion Counts Distribution", "Heatmap"])with tab1:st.plotly_chart(fig_pie)
app.py+24-22