Harshhp24 commited on
Commit
f67ba1b
Β·
verified Β·
1 Parent(s): f2a5122

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +111 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,113 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ import json
4
 
5
+ st.set_page_config(
6
+ page_title="Sentiment Analysis App",
7
+ page_icon="😊",
8
+ layout="centered"
9
+ )
10
+
11
+ st.title("Sentiment Analysis App")
12
+ st.write("Enter text to analyze its sentiment using Hugging Face's API")
13
+
14
+ # API credentials input
15
+ api_key = st.text_input("Enter your Hugging Face API key:", type="password", help="Your Hugging Face API token")
16
+
17
+ # Model selection
18
+ model_options = {
19
+ "DistilBERT (SST-2)": "distilbert/distilbert-base-uncased-finetuned-sst-2-english",
20
+ "Twitter-roBERTa-base": "cardiffnlp/twitter-roberta-base-sentiment",
21
+ "BERT-base-multilingual": "nlptown/bert-base-multilingual-uncased-sentiment"
22
+ }
23
+ selected_model = st.selectbox("Select a sentiment analysis model:", options=list(model_options.keys()))
24
+
25
+ # Text input area
26
+ text_input = st.text_area("Enter text to analyze:", height=150)
27
+
28
+ # Function to call the Hugging Face API
29
+ def analyze_sentiment(text, model, api_key):
30
+ API_URL = f"https://api-inference.huggingface.co/models/{model}"
31
+ headers = {
32
+ "Authorization": f"Bearer {api_key}"
33
+ }
34
+
35
+ payload = {
36
+ "inputs": text,
37
+ }
38
+
39
+ try:
40
+ response = requests.post(API_URL, headers=headers, json=payload)
41
+ return response.json()
42
+ except Exception as e:
43
+ return {"error": str(e)}
44
+
45
+ # Submit button
46
+ if st.button("Analyze Sentiment"):
47
+ if not api_key:
48
+ st.error("Please enter your Hugging Face API key")
49
+ elif not text_input:
50
+ st.error("Please enter some text to analyze")
51
+ else:
52
+ with st.spinner("Analyzing sentiment..."):
53
+ selected_model_path = model_options[selected_model]
54
+ result = analyze_sentiment(text_input, selected_model_path, api_key)
55
+
56
+ # Process and display results
57
+ try:
58
+ if "error" in result:
59
+ st.error(f"Error: {result['error']}")
60
+ elif isinstance(result, list) and len(result) > 0:
61
+ # Process the results
62
+ if isinstance(result[0], list):
63
+ items = result[0]
64
+ else:
65
+ items = result
66
+
67
+ # Find the highest scoring sentiment
68
+ highest_item = max(items, key=lambda x: x['score'])
69
+ score = highest_item['score']
70
+ label = highest_item['label'].lower()
71
+
72
+ # Display emoji based on sentiment and score
73
+ st.subheader("Sentiment:")
74
+ col1, col2 = st.columns([1, 3])
75
+
76
+ # Select emoji based on sentiment label and score
77
+ if 'positive' in label or 'pos' in label or '5' in label or '4' in label:
78
+ if score > 0.9:
79
+ emoji = "😍"
80
+ elif score > 0.7:
81
+ emoji = "😁"
82
+ else:
83
+ emoji = "πŸ™‚"
84
+ sentiment_text = f"Positive ({score:.2f})"
85
+ elif 'negative' in label or 'neg' in label or '1' in label or '2' in label:
86
+ if score > 0.9:
87
+ emoji = "😑"
88
+ elif score > 0.7:
89
+ emoji = "😠"
90
+ else:
91
+ emoji = "☹"
92
+ sentiment_text = f"Negative ({score:.2f})"
93
+ else: # neutral or '3' in label
94
+ emoji = "😐"
95
+ sentiment_text = f"Neutral ({score:.2f})"
96
+
97
+ with col1:
98
+ st.markdown(f"<h1 style='font-size:4rem; text-align:center;'>{emoji}</h1>", unsafe_allow_html=True)
99
+ with col2:
100
+ st.markdown(f"<h2>{sentiment_text}</h2>", unsafe_allow_html=True)
101
+
102
+ # Add confidence meter
103
+ st.progress(score)
104
+ else:
105
+ st.warning("Unexpected response format. Please check your API key and try again.")
106
+ st.json(result)
107
+ except Exception as e:
108
+ st.error(f"Error processing results: {str(e)}")
109
+ st.json(result)
110
+
111
+ # Footer
112
+ st.markdown("---")
113
+ st.markdown("Built with Streamlit and Hugging Face API")