Create sentiment_analyzer.py
Browse filesimport streamlit as st
from transformers import pipeline
import matplotlib.pyplot as plt
from PIL import Image, ImageFilter
import numpy as np
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing.image import img_to_array
# Chargement du modèle d'analyse de sentiments et de reconnaissance d'images
sentiment_pipeline = pipeline("sentiment-analysis")
image_model = MobileNetV2(weights='imagenet')
def plot_sentiment(sentiment):
""" Dessine un graphique en camembert pour l'analyse de sentiments. """
labels = ['Positive', 'Negative']
sizes = [sentiment['score'], 1 - sentiment['score']]
colors = ['#ff9999','#66b3ff']
fig, ax = plt.subplots()
ax.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', startangle=90)
ax.axis('equal')
return fig
def classify_image(image):
""" Classifie l'image et retourne les prédictions. """
image = image.resize((224, 224))
image = img_to_array(image)
image = np.expand_dims(image, axis=0)
image = preprocess_input(image)
preds = image_model.predict(image)
return decode_predictions(preds, top=3)[0]
def apply_filters(image):
""" Applique des filtres à l'image et retourne l'image filtrée. """
filter = st.sidebar.selectbox("Sélectionnez un filtre", ["Original", "Flou", "Contours", "Accentuation"])
if filter == "Flou":
return image.filter(ImageFilter.BLUR)
elif filter == "Contours":
return image.filter(ImageFilter.CONTOUR)
elif filter == "Accentuation":
return image.filter(ImageFilter.EDGE_ENHANCE)
return image
# Configuration de l'application
st.title("Mon Application de Reconnaissance d'Images et d'Analyse de Sentiments")
st.sidebar.title("Options")
# Barre de navigation
options = st.sidebar.radio("Choisissez une fonctionnalité:", ['Reconnaissance d\'Images', 'Analyse de Sentiments'])
# Reconnaissance d'images
if options == 'Reconnaissance d\'Images':
uploaded_file = st.file_uploader("Téléchargez une image...", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
filtered_image = apply_filters(image)
st.image(filtered_image, caption='Image téléchargée', use_column_width=True)
# Classification de l'image
st.write("Classifying...")
labels = classify_image(filtered_image)
for label in labels:
st.write(f"{label[1]} ({label[2]*100:.2f}%)")
# Analyse de sentiments basée sur les étiquettes de l'image
sentiments = [sentiment_pipeline(label[1])[0] for label in labels]
for sentiment in sentiments:
st.write(f"Sentiment pour '{sentiment['label']}' : {sentiment['score']:.2f}")
fig = plot_sentiment(sentiment)
st.pyplot(fig)
# Analyse de sentiments
elif options == 'Analyse de Sentiments':
user_input = st.text_area("Entrez le texte à analyser", "Tapez ici...")
if st.button("Analyser"):
result = sentiment_pipeline(user_input)[0]
st.write(f"Sentiment: {result['label']}, Score: {result['score']:.2f}")
fig = plot_sentiment(result)
st.pyplot(fig)
- sentiment_analyzer.py +78 -0
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from transformers import pipeline
|
3 |
+
import matplotlib.pyplot as plt
|
4 |
+
from PIL import Image, ImageFilter
|
5 |
+
import numpy as np
|
6 |
+
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2, preprocess_input, decode_predictions
|
7 |
+
from tensorflow.keras.preprocessing.image import img_to_array
|
8 |
+
|
9 |
+
# Chargement du modèle d'analyse de sentiments et de reconnaissance d'images
|
10 |
+
sentiment_pipeline = pipeline("sentiment-analysis")
|
11 |
+
image_model = MobileNetV2(weights='imagenet')
|
12 |
+
|
13 |
+
def plot_sentiment(sentiment):
|
14 |
+
""" Dessine un graphique en camembert pour l'analyse de sentiments. """
|
15 |
+
labels = ['Positive', 'Negative']
|
16 |
+
sizes = [sentiment['score'], 1 - sentiment['score']]
|
17 |
+
colors = ['#ff9999','#66b3ff']
|
18 |
+
fig, ax = plt.subplots()
|
19 |
+
ax.pie(sizes, colors=colors, labels=labels, autopct='%1.1f%%', startangle=90)
|
20 |
+
ax.axis('equal')
|
21 |
+
return fig
|
22 |
+
|
23 |
+
def classify_image(image):
|
24 |
+
""" Classifie l'image et retourne les prédictions. """
|
25 |
+
image = image.resize((224, 224))
|
26 |
+
image = img_to_array(image)
|
27 |
+
image = np.expand_dims(image, axis=0)
|
28 |
+
image = preprocess_input(image)
|
29 |
+
preds = image_model.predict(image)
|
30 |
+
return decode_predictions(preds, top=3)[0]
|
31 |
+
|
32 |
+
def apply_filters(image):
|
33 |
+
""" Applique des filtres à l'image et retourne l'image filtrée. """
|
34 |
+
filter = st.sidebar.selectbox("Sélectionnez un filtre", ["Original", "Flou", "Contours", "Accentuation"])
|
35 |
+
if filter == "Flou":
|
36 |
+
return image.filter(ImageFilter.BLUR)
|
37 |
+
elif filter == "Contours":
|
38 |
+
return image.filter(ImageFilter.CONTOUR)
|
39 |
+
elif filter == "Accentuation":
|
40 |
+
return image.filter(ImageFilter.EDGE_ENHANCE)
|
41 |
+
return image
|
42 |
+
|
43 |
+
# Configuration de l'application
|
44 |
+
st.title("Mon Application de Reconnaissance d'Images et d'Analyse de Sentiments")
|
45 |
+
st.sidebar.title("Options")
|
46 |
+
|
47 |
+
# Barre de navigation
|
48 |
+
options = st.sidebar.radio("Choisissez une fonctionnalité:", ['Reconnaissance d\'Images', 'Analyse de Sentiments'])
|
49 |
+
|
50 |
+
# Reconnaissance d'images
|
51 |
+
if options == 'Reconnaissance d\'Images':
|
52 |
+
uploaded_file = st.file_uploader("Téléchargez une image...", type=["jpg", "png", "jpeg"])
|
53 |
+
if uploaded_file is not None:
|
54 |
+
image = Image.open(uploaded_file)
|
55 |
+
filtered_image = apply_filters(image)
|
56 |
+
st.image(filtered_image, caption='Image téléchargée', use_column_width=True)
|
57 |
+
|
58 |
+
# Classification de l'image
|
59 |
+
st.write("Classifying...")
|
60 |
+
labels = classify_image(filtered_image)
|
61 |
+
for label in labels:
|
62 |
+
st.write(f"{label[1]} ({label[2]*100:.2f}%)")
|
63 |
+
|
64 |
+
# Analyse de sentiments basée sur les étiquettes de l'image
|
65 |
+
sentiments = [sentiment_pipeline(label[1])[0] for label in labels]
|
66 |
+
for sentiment in sentiments:
|
67 |
+
st.write(f"Sentiment pour '{sentiment['label']}' : {sentiment['score']:.2f}")
|
68 |
+
fig = plot_sentiment(sentiment)
|
69 |
+
st.pyplot(fig)
|
70 |
+
|
71 |
+
# Analyse de sentiments
|
72 |
+
elif options == 'Analyse de Sentiments':
|
73 |
+
user_input = st.text_area("Entrez le texte à analyser", "Tapez ici...")
|
74 |
+
if st.button("Analyser"):
|
75 |
+
result = sentiment_pipeline(user_input)[0]
|
76 |
+
st.write(f"Sentiment: {result['label']}, Score: {result['score']:.2f}")
|
77 |
+
fig = plot_sentiment(result)
|
78 |
+
st.pyplot(fig)
|