Kotieu commited on
Commit
02e0a38
1 Parent(s): eba58d2

Update app.py

Browse files

import 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)

Files changed (1) hide show
  1. app.py +68 -39
app.py CHANGED
@@ -1,49 +1,78 @@
1
  import streamlit as st
2
- import pandas as pd
3
- from sklearn import datasets
4
- from sklearn.ensemble import RandomForestClassifier
 
 
 
5
 
6
- st.write("""
7
- # Simple Iris Flower Prediction App
 
8
 
9
- This app predicts the **Iris flower** type!
10
- """)
 
 
 
 
 
 
 
11
 
12
- st.sidebar.header('User Input Parameters')
 
 
 
 
 
 
 
13
 
14
- def user_input_features():
15
- sepal_length = st.sidebar.slider('Sepal length', 4.3, 7.9, 5.4)
16
- sepal_width = st.sidebar.slider('Sepal width', 2.0, 4.4, 3.4)
17
- petal_length = st.sidebar.slider('Petal length', 1.0, 6.9, 1.3)
18
- petal_width = st.sidebar.slider('Petal width', 0.1, 2.5, 0.2)
19
- data = {'sepal_length': sepal_length,
20
- 'sepal_width': sepal_width,
21
- 'petal_length': petal_length,
22
- 'petal_width': petal_width}
23
- features = pd.DataFrame(data, index=[0])
24
- return features
25
 
26
- df = user_input_features()
 
 
27
 
28
- st.subheader('User Input parameters')
29
- st.write(df)
30
 
31
- iris = datasets.load_iris()
32
- X = iris.data
33
- Y = iris.target
 
 
 
 
 
 
 
 
 
 
34
 
35
- clf = RandomForestClassifier()
36
- clf.fit(X, Y)
 
 
 
 
37
 
38
- prediction = clf.predict(df)
39
- prediction_proba = clf.predict_proba(df)
40
-
41
- st.subheader('Class labels and their corresponding index number')
42
- st.write(iris.target_names)
43
-
44
- st.subheader('Prediction')
45
- st.write(iris.target_names[prediction])
46
- #st.write(prediction)
47
-
48
- st.subheader('Prediction Probability')
49
- st.write(prediction_proba)
 
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)