Mariam-anglais / app.py
Docfile's picture
Update app.py
4a3da21 verified
raw
history blame
7.33 kB
import streamlit as st
import PIL.Image
import os
import google.generativeai as genai
safety_settings = [
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
]
# Configuration de la page
st.set_page_config(
page_title="Mariam Anglais",
page_icon="🇬🇧",
layout="wide",
initial_sidebar_state="expanded"
)
# CSS personnalisé pour un design plus esthétique
st.markdown(
"""
<style>
body {
background-color: #f4f4f4;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; /* Police plus moderne */
}
.stButton>button {
background-color: #4CAF50;
color: white;
padding: 0.75rem 1.5rem;
border-radius: 0.5rem;
font-weight: bold;
transition: all 0.2s ease-in-out; /* Animation au survol */
}
.stButton>button:hover {
background-color: #3e8e41; /* Couleur plus foncée au survol */
box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2); /* Ombre au survol */
transform: translateY(-2px); /* Légère élévation au survol */
}
.stFileUploader {
padding: 1rem;
border: 2px dashed #4CAF50;
border-radius: 0.5rem;
}
.stRadio>div>label {
font-weight: bold;
}
.st-bb {
border-bottom: 2px solid #4CAF50;
}
.st-el { /* Pour les messages d'avertissement et de succès */
border-radius: 0.5rem;
padding: 0.75rem;
}
.st-ek { /* Zone de texte */
border-radius: 0.5rem;
}
.st-ef { /* Titres */
font-weight: bold;
color: #267629;
}
.stProgress>div>div>div>div {
background-color: #4CAF50;
}
</style>
""",
unsafe_allow_html=True
)
prompt_text = """
je souhaite faire mon travail d'anglais qui consiste à de l'analyse de texte. j'aimerais que tu le phase en respectant scrupuleusement la méthodologie suivante. j'aimerais que tu fasses ce travail en anglais en donnant également la traduction française:
INTRODUCTION
SUMMARY
COMMENTARY
EVALUATION
I- INTRODUCTION
Title (what is the title of the text?)
Nature (what is it?)
Author (who wrote it?)
Origin (where was it extracted?)
Date of publication (when was it written?)
Genre (descriptive...)
General idea (what is it about?)
Writer' intention (what for?)
II - SUMMARY
The components (the structure / text subdivision)
(The main parts of the text and their ideas)
The summary itself.
III - COMMENTARY
Focus on the main points of interest from the summary
Discuss, explain and develop the main points of the writer's opinion, deal with them in a coherent and logical order.
Tone
Style
IV-EVALUATION
Assess the text value
The interest of the text
The lessons, you've learnt and the impact on your opinion.
V - BRANCHING OUT
Personal opinion (give one's opinion)
Feelings (I had mixed feeling about.........)
"""
prompt_image = " Décris l'image "
# Configuration de l'API Google Generative AI
GOOGLE_API_KEY = st.secrets["GOOGLE_API_KEY"] # Définir le chemin d'accès dans les secrets de l'application
genai.configure(api_key=GOOGLE_API_KEY)
# Titre et introduction avec effet d'animation
st.markdown(
"""
<h1 style='text-align: center; color: #267629; font-size: 3em; font-weight: bold;'>
<span style='opacity: 0; animation: fadeIn 1s ease-in-out forwards;'>✨ Mariam Anglais ✨</span>
</h1>
<style>
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
""",
unsafe_allow_html=True
)
st.markdown("<br>", unsafe_allow_html=True) # Espace
st.write("Bienvenue sur votre plateforme d'analyse d'images intelligente! Téléchargez vos images, choisissez votre type d'analyse, et laissez la magie opérer.")
# Colonnes pour une meilleure disposition
col1, col2 = st.columns(2, gap="large") # Ajout d'un gap plus grand
with col1:
# Section de téléchargement d'images
st.subheader("📷 Téléchargement d'images")
uploaded_files = st.file_uploader("", type=["jpg", "jpeg", "png"], accept_multiple_files=True, label_visibility="collapsed") # Label caché
# Aperçu des images téléchargées avec possibilité de les supprimer individuellement
if uploaded_files:
st.write("Aperçu des images :")
for i, uploaded_file in enumerate(uploaded_files):
col_img, col_del = st.columns([4, 1]) # Colonnes pour l'image et le bouton de suppression
with col_img:
st.image(uploaded_file, width=200, caption=f"Image {i+1}")
with col_del:
if st.button(f"🗑️", key=f"del_{i}"):
del uploaded_files[i]
st.experimental_rerun()
with col2:
# Section de choix du type d'analyse
st.subheader("🎛️ Choix du type d'analyse")
analysis_type = st.radio("",
("🔍 Type 1: Analyse de Texte", "🧠 Type 2: Document iconographique"), label_visibility="collapsed")
# Description des types d'analyse (cachée par défaut, visible en cliquant)
with st.expander("ℹ️ En savoir plus sur les types d'analyse"):
if analysis_type == "🔍 Type 1: Analyse de texte":
st.write("il s'agit ici de l'analyse de texte avec (INTRODUCTION,SUMMARY,COMMENTARY,EVALUATION.")
else:
st.write("il s'agit ici du document iconographique.")
# Bouton de soumission
if st.button("🚀 Soumettre", key="submit"):
if uploaded_files:
st.write("Type d'analyse sélectionné :", analysis_type)
# Préparation des images pour l'API
image_parts = []
for uploaded_file in uploaded_files:
try:
image = PIL.Image.open(uploaded_file)
image_parts.append(image)
except Exception as e:
st.error(f"Erreur lors du chargement de l'image : {e}")
st.stop()
# Définir le prompt en fonction du type d'analyse
if analysis_type == "🔍 Type 1: Analyse de Text":
prompt = prompt_text
else:
prompt = prompt_image
# Appel de l'API Google Generative AI
try:
model = genai.GenerativeModel(model_name="gemini-2.0-flash-exp",safety_settings=safety_settings)
with st.spinner("Analyse en cours..."):
progress_bar = st.progress(0)
response = model.generate_content([prompt] + image_parts, stream=True)
response.resolve()
progress_bar.progress(100)
# Affichage de la réponse
st.subheader("📝 Résultat de l'analyse :")
st.write(response.text)
except Exception as e:
st.error(f"Erreur lors de l'analyse : {e}")
else:
st.warning("⚠️ Veuillez télécharger au moins une image.")
# Pied de page
st.markdown("---")
st.write("© 2024 Mariam AI - Tous droits réservés.")