Docfile commited on
Commit
da7ef42
·
verified ·
1 Parent(s): b985ced

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +186 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template_string, request, session, redirect, url_for
2
+ import os
3
+ import google.generativeai as genai
4
+ import http.client
5
+ import json
6
+ from dotenv import load_dotenv
7
+
8
+ load_dotenv()
9
+
10
+ app = Flask(__name__)
11
+ app.secret_key = os.getenv("FLASK_SECRET_KEY", "supersecretkey") # Configurez la clé secrète pour la session
12
+
13
+ # Configurez l'API pour Generative AI
14
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
15
+
16
+ # Paramètres de sécurité et instruction système
17
+ safety_settings = [
18
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
19
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
20
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
21
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
22
+ ]
23
+
24
+ ss = """
25
+ # Prompt System pour Mariam, IA conçu par youssouf
26
+
27
+ ## Personnalité Fondamentale
28
+
29
+ Mariam est une IA chaleureuse, bienveillante et authentique, conçue pour être une présence réconfortante et utile. Elle combine professionnalisme et chaleur humaine dans ses interactions.
30
+
31
+ [...]
32
+
33
+ ## Amélioration Continue
34
+
35
+ - Collecter les retours des utilisateurs
36
+ - Analyser les interactions pour identifier les points d'amélioration
37
+ - Ajuster les réponses en fonction des retours
38
+ - Maintenir à jour les connaissances et références
39
+ """
40
+
41
+ # Initialisation du modèle de chat
42
+ model = genai.GenerativeModel('gemini-2.0-flash-exp', tools='code_execution',
43
+ safety_settings=safety_settings,
44
+ system_instruction=ss)
45
+
46
+ # Fonction d'initialisation du chat dans la session
47
+ def init_chat():
48
+ session['chat_history'] = []
49
+
50
+ # Fonction pour réaliser une recherche web
51
+ def perform_web_search(query):
52
+ conn = http.client.HTTPSConnection("google.serper.dev")
53
+ payload = json.dumps({"q": query})
54
+ headers = {
55
+ 'X-API-KEY': '9b90a274d9e704ff5b21c0367f9ae1161779b573',
56
+ 'Content-Type': 'application/json'
57
+ }
58
+ try:
59
+ conn.request("POST", "/search", payload, headers)
60
+ res = conn.getresponse()
61
+ data = json.loads(res.read().decode("utf-8"))
62
+ return data
63
+ except Exception as e:
64
+ print(f"Erreur lors de la recherche web : {e}")
65
+ return None
66
+ finally:
67
+ conn.close()
68
+
69
+ # Mise en forme des résultats de recherche
70
+ def format_search_results(data):
71
+ if not data:
72
+ return "Aucun résultat trouvé"
73
+
74
+ result = ""
75
+ if 'knowledgeGraph' in data:
76
+ kg = data['knowledgeGraph']
77
+ result += f"### {kg.get('title', '')}\n"
78
+ result += f"*{kg.get('type', '')}*\n\n"
79
+ result += f"{kg.get('description', '')}\n\n"
80
+ if 'organic' in data:
81
+ result += "### Résultats principaux:\n"
82
+ for item in data['organic'][:3]:
83
+ result += f"- **{item['title']}**\n"
84
+ result += f" {item['snippet']}\n"
85
+ result += f" [Lien]({item['link']})\n\n"
86
+ if 'peopleAlsoAsk' in data:
87
+ result += "### Questions fréquentes:\n"
88
+ for item in data['peopleAlsoAsk'][:2]:
89
+ result += f"- **{item['question']}**\n"
90
+ result += f" {item['snippet']}\n\n"
91
+ return result
92
+
93
+ # Traitement du fichier uploadé
94
+ def process_uploaded_file(file):
95
+ if file:
96
+ temp_dir = "temp"
97
+ os.makedirs(temp_dir, exist_ok=True)
98
+ temp_path = os.path.join(temp_dir, file.filename)
99
+ file.save(temp_path)
100
+ try:
101
+ gemini_file = genai.upload_file(temp_path)
102
+ return gemini_file
103
+ except Exception as e:
104
+ print(f"Erreur lors du téléchargement du fichier : {e}")
105
+ return None
106
+ return None
107
+
108
+ # Template HTML (vous pouvez le déplacer dans un fichier template si besoin)
109
+ template = """
110
+ <!doctype html>
111
+ <html>
112
+ <head>
113
+ <meta charset="utf-8">
114
+ <title>Mariam AI</title>
115
+ </head>
116
+ <body>
117
+ <h1>Mariam AI!</h1>
118
+ <form method="POST" enctype="multipart/form-data">
119
+ <div>
120
+ <label for="prompt">Votre message :</label>
121
+ <input type="text" id="prompt" name="prompt" required>
122
+ </div>
123
+ <div>
124
+ <label for="file">Télécharger un fichier (image/document) :</label>
125
+ <input type="file" id="file" name="file" accept=".jpg,.jpeg,.png,.mp4,.mp3,.pdf,.txt">
126
+ </div>
127
+ <div>
128
+ <label for="web_search">Activer la recherche web :</label>
129
+ <input type="checkbox" id="web_search" name="web_search">
130
+ </div>
131
+ <button type="submit">Envoyer</button>
132
+ </form>
133
+
134
+ <h2>Conversation</h2>
135
+ <div>
136
+ {% for message in chat_history %}
137
+ <p><strong>{{ message.role|capitalize }} :</strong> {{ message.text }}</p>
138
+ {% endfor %}
139
+ </div>
140
+ </body>
141
+ </html>
142
+ """
143
+
144
+ @app.route("/", methods=["GET", "POST"])
145
+ def index():
146
+ # Initialisation de l'historique de chat en session s'il n'existe pas
147
+ if "chat_history" not in session:
148
+ init_chat()
149
+
150
+ if request.method == "POST":
151
+ prompt = request.form.get("prompt")
152
+ web_search_enabled = request.form.get("web_search") == "on"
153
+ file = request.files.get("file")
154
+
155
+ # Ajout du message utilisateur à l'historique de la session
156
+ session['chat_history'].append({"role": "user", "text": prompt})
157
+
158
+ uploaded_gemini_file = process_uploaded_file(file)
159
+
160
+ # Si la recherche web est activée, effectuez-la et enrichissez la question
161
+ if web_search_enabled:
162
+ web_results = perform_web_search(prompt)
163
+ if web_results:
164
+ formatted_results = format_search_results(web_results)
165
+ prompt = f"Question: {prompt}\n\nRésultats de recherche web:\n{formatted_results}\n\nPourrais-tu analyser ces informations et me donner une réponse complète?"
166
+
167
+ try:
168
+ # Recrée le chat avec l'historique stocké en session
169
+ chat = model.start_chat(history=session.get("chat_history", []))
170
+ if uploaded_gemini_file:
171
+ response = chat.send_message([uploaded_gemini_file, "\n\n", prompt])
172
+ else:
173
+ response = chat.send_message(prompt)
174
+ answer = response.text
175
+ session['chat_history'].append({"role": "assistant", "text": answer})
176
+ except Exception as e:
177
+ error_message = f"Erreur lors de l'envoi du message : {e}"
178
+ session['chat_history'].append({"role": "assistant", "text": error_message})
179
+
180
+ session.modified = True
181
+ return redirect(url_for("index"))
182
+
183
+ return render_template_string(template, chat_history=session.get("chat_history", []))
184
+
185
+ if __name__ == "__main__":
186
+ app.run(debug=True)