Spaces:
Sleeping
Sleeping
Update app.py
Browse files8 unmodified lines9101112131415161718192021222324252627282930313233347 unmodified lines424344454647481 unmodified line5051525354555657585916 unmodified lines76777879808182838485868788899091929394959697989910010110210310410510610710810911011144 unmodified lines15615715815916016116216316416516612 unmodified lines1791801811821831841851861871881891901911921938 unmodified linesimport plotly.graph_objects as goimport streamlit as stimport nltkimport jsonimport 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# passos.environ["GOOGLE_APPLICATION_CREDENTIALS"]= get_credentials()max_seq_length = 2048dtype = None7 unmodified linestext_split_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')def predict_custom_trained_model_sample(project: str,endpoint_id: str,1 unmodified linelocation: str = "us-east4",api_endpoint: str = "us-east4-aiplatform.googleapis.com",) -> List[str]:"""`instances` can be either single instance of type dict or a listof instances."""client_options = {"api_endpoint": api_endpoint}client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)instances = instances if isinstance(instances, list) else [instances]16 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',7: 'curiosity', 8: 'desire', 9: 'disappointment', 10: 'disapproval', 11: 'disgust', 12: 'embarrassment',13: 'excitement', 14: 'fear', 15: 'gratitude', 16: 'grief', 17: 'joy', 18: 'love', 19: 'nervousness',20: 'optimism', 21: 'pride', 22: 'realization', 23: 'relief', 24: 'remorse', 25: 'sadness', 26: 'surprise',27: 'neutral'}st.write(" ")st.write(" ")st.write("Write or paste any number of document texts to analyse the emotion percentage with your document")# Add button to fill in sample textif st.button("Use Sample Text"):user_input = st.text_area(label="Sample", value="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.", disabled=True)else:user_input = st.text_area('Enter Text to Analyze')# user_input = st.text_input(label, value=ur_input, height=None, max_chars=None, key=None, help=None, on_change=None, args=None, kwargs=None, *, placeholder=None, disabled=False, label_visibility="visible")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:44 unmodified linesfig_bar = get_emotion_chart(predictions)@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']12 unmodified lines))fig.update_layout(title='Emotion Heatmap', xaxis_title='Predicted Emotion', yaxis_title='Predicted Emotion')return figfig_dist = get_emotion_heatmap(predictions)tab1, tab2, tab3 = st.tabs(["Emotion Analysis", "Emotion Counts Distribution", "Heatmap"])with tab1:st.plotly_chart(fig_pie)with tab2:st.plotly_chart(fig_bar)with tab3:st.plotly_chart(fig_dist)8 unmodified lines9101112131415161718192021222324252627282930317 unmodified lines3940414243441 unmodified line46474849505116 unmodified lines68697071727374757677787980818283848586878889909192939495969744 unmodified lines14214314414514614714814915012 unmodified lines1631641651661671681691701711721731741758 unmodified linesimport 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 = 2048dtype = None7 unmodified linestext_split_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')def predict_custom_trained_model_sample(project: str,endpoint_id: str,1 unmodified linelocation: str = "us-east4",api_endpoint: str = "us-east4-aiplatform.googleapis.com",) -> List[str]:client_options = {"api_endpoint": api_endpoint}client = aiplatform.gapic.PredictionServiceClient(client_options=client_options)instances = instances if isinstance(instances, list) else [instances]16 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',7: 'curiosity', 8: 'desire', 9: 'disappointment', 10: 'disapproval', 11: 'disgust', 12: 'embarrassment',13: 'excitement', 14: 'fear', 15: 'gratitude', 16: 'grief', 17: 'joy', 18: 'love', 19: 'nervousness',20: '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:44 unmodified linesfig_bar = get_emotion_chart(predictions)@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']12 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)with tab2:st.plotly_chart(fig_bar)with tab3:st.plotly_chart(fig_heatmap)
app.py+19-37