File size: 4,665 Bytes
5363e34
368cb61
 
5363e34
 
 
54165ee
5363e34
 
f60ad9a
368cb61
4e3336f
6a5228f
5363e34
 
e44c6ac
 
 
 
 
 
368cb61
4e3336f
d516eb1
368cb61
36d2689
5363e34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e3336f
5363e34
 
 
4e3336f
368cb61
36d2689
405af3c
36d2689
 
 
5363e34
 
 
 
 
 
36d2689
5363e34
 
36d2689
 
 
3c3c238
36d2689
4e3336f
5363e34
 
368cb61
 
5363e34
368cb61
5363e34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368cb61
5363e34
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import streamlit as st
import google.generativeai as genai
import os
from PIL import Image
import io

# Configuratiovbn de la page Streamlit
st.set_page_config(page_title="Mariam eco", layout="wide")
st.title("Mariam eco")
st.markdown("yup")

# Configuration de l'API Gemini
api_key = os.environ["GEMINI_API_KEY"] 

genai.configure(api_key=api_key)
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"},
]

# Définition du modèle
model = genai.GenerativeModel("gemini-2.5-flash-preview-04-17",system_instruction="Tu es Mariam une IA entraîner par Aenir pour répondre aux questions. ", safety_settings=safety_settings)

# Chargement de tous les fichiers PDF du dossier "data"
@st.cache_resource
def load_pdf_files():
    DATA_FOLDER = "data"
    if not os.path.exists(DATA_FOLDER):
        os.makedirs(DATA_FOLDER)
        st.warning(f"Le dossier {DATA_FOLDER} a été créé. Veuillez y placer vos fichiers PDF.")
        return []
    
    pdf_files = [
        os.path.join(DATA_FOLDER, file)
        for file in os.listdir(DATA_FOLDER)
        if file.lower().endswith(".pdf")
    ]
    
    if not pdf_files:
        st.info(f"Aucun fichier PDF trouvé dans le dossier {DATA_FOLDER}.")
        return []
    
    with st.spinner("Chargement des fichiers PDF..."):
        uploaded_files = [genai.upload_file(pdf_file) for pdf_file in pdf_files]
        st.success(f"{len(uploaded_files)} fichiers PDF chargés avec succès.")
    
    return uploaded_files

uploaded_files = load_pdf_files()

def process_input(prompt, image_file):
    """Traite le texte et l'image optionnelle et génère une réponse."""
    try:
        # Préparer le contenu en ajoutant tous les fichiers PDF
        print(prompt)
        content = uploaded_files.copy()

        # Si une image est fournie, l'ajouter au contenu
        if image_file is not None:
            # Streamlit fournit un fichier en mémoire, nous devons le sauvegarder temporairement
            temp_image_path = "temp_image.jpg"
            img = Image.open(image_file)
            img.save(temp_image_path)
            img_file = genai.upload_file(temp_image_path)
            content.append(img_file)
            # Supprimer le fichier temporaire
            os.remove(temp_image_path)

        # Ajout du prompt avec l'instruction de répondre en français
        content.append("\n\n")
        content.append(prompt + " répond en français.")

        # Génération du contenu
        with st.spinner("Génération de la réponse..."):
            result = model.generate_content(content)
        return result.text
    except Exception as e:
        return f"Une erreur s'est produite : "

# Interface principale
tab1, tab2 = st.tabs(["Interface principale", "Exemples"])

with tab1:
    st.subheader("Posez une question")
    
    # Zone de texte pour la question
    prompt = st.text_area("Question", placeholder="Posez une question sur le roman...", height=100)
    
    # Upload d'image (facultatif)
    image_file = st.file_uploader("Image (facultative)", type=["jpg", "jpeg", "png"])
    
    # Affichage de l'image téléchargée
    if image_file is not None:
        st.image(image_file, caption="Image téléchargée", use_column_width=True)
    
    # Bouton pour soumettre la question
    if st.button("Obtenir une réponse"):
        if prompt:
            response = process_input(prompt, image_file)
            st.markdown("### Réponse")
            st.markdown(response)
        else:
            st.warning("Veuillez entrer une question.")

with tab2:
    st.subheader("Exemples de questions")
    
    example1 = st.button("C'est quoi un mass media?")
    example2 = st.button("C'est quoi l'entrepreneuriat?")
    
    if example1:
        response = process_input("C'est quoi un mass media", None)
        st.markdown("### Réponse")
        st.markdown(response)
    
    if example2:
        response = process_input("C'est quoi l'entrepreneuriat", None)
        st.markdown("### Réponse")
        st.markdown(response)

# Affichage des informations sur les fichiers chargés
with st.sidebar:
    st.subheader("Informations")
    st.write(f"Nombre de fichiers PDF chargés: {len(uploaded_files)}")
    if uploaded_files:
        st.write("Fichiers PDF dans le dossier 'data':")
        for file in os.listdir("data"):
            if file.lower().endswith(".pdf"):
                st.write(f"- {file}")