Docfile commited on
Commit
ca8d526
·
verified ·
1 Parent(s): 424facd

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -0
app.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ import google.generativeai as genai
3
+ import os
4
+ from dotenv import load_dotenv
5
+ import http.client
6
+ import json
7
+ from werkzeug.utils import secure_filename
8
+
9
+ app = Flask(__name__)
10
+ app.config['UPLOAD_FOLDER'] = 'temp'
11
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
12
+
13
+ load_dotenv()
14
+
15
+ # Configure the API key
16
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
17
+
18
+ safety_settings = [
19
+ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
20
+ {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
21
+ {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
22
+ {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
23
+ ]
24
+
25
+ model = genai.GenerativeModel('gemini-2.0-flash-exp',
26
+ tools='code_execution',
27
+ safety_settings=safety_settings,
28
+ system_instruction="Tu es un assistant intelligent. ton but est d'assister au mieux que tu peux. tu as été créé par Aenir et tu t'appelles Mariam")
29
+
30
+ def perform_web_search(query):
31
+ conn = http.client.HTTPSConnection("google.serper.dev")
32
+ payload = json.dumps({"q": query})
33
+ headers = {
34
+ 'X-API-KEY': '9b90a274d9e704ff5b21c0367f9ae1161779b573',
35
+ 'Content-Type': 'application/json'
36
+ }
37
+ try:
38
+ conn.request("POST", "/search", payload, headers)
39
+ res = conn.getresponse()
40
+ data = json.loads(res.read().decode("utf-8"))
41
+ return data
42
+ except Exception as e:
43
+ return {"error": str(e)}
44
+ finally:
45
+ conn.close()
46
+
47
+ def format_search_results(data):
48
+ if not data:
49
+ return "Aucun résultat trouvé"
50
+
51
+ result = ""
52
+
53
+ if 'knowledgeGraph' in data:
54
+ kg = data['knowledgeGraph']
55
+ result += f"### {kg.get('title', '')}\n"
56
+ result += f"*{kg.get('type', '')}*\n\n"
57
+ result += f"{kg.get('description', '')}\n\n"
58
+
59
+ if 'organic' in data:
60
+ result += "### Résultats principaux:\n"
61
+ for item in data['organic'][:3]:
62
+ result += f"- **{item['title']}**\n"
63
+ result += f" {item['snippet']}\n"
64
+ result += f" [Lien]({item['link']})\n\n"
65
+
66
+ return result
67
+
68
+ @app.route('/')
69
+ def home():
70
+ return render_template('index.html')
71
+
72
+ @app.route('/chat', methods=['POST'])
73
+ def chat():
74
+ data = request.json
75
+ prompt = data.get('message')
76
+ web_search_enabled = data.get('web_search', False)
77
+
78
+ try:
79
+ web_results = None
80
+ if web_search_enabled:
81
+ web_results = perform_web_search(prompt)
82
+ if web_results and 'error' not in web_results:
83
+ formatted_results = format_search_results(web_results)
84
+ 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?"""
85
+
86
+ response = model.generate_content(prompt)
87
+ return jsonify({"response": response.text})
88
+
89
+ except Exception as e:
90
+ return jsonify({"error": str(e)}), 500
91
+
92
+ @app.route('/upload', methods=['POST'])
93
+ def upload_file():
94
+ if 'file' not in request.files:
95
+ return jsonify({"error": "No file part"}), 400
96
+
97
+ file = request.files['file']
98
+ if file.filename == '':
99
+ return jsonify({"error": "No selected file"}), 400
100
+
101
+ if file:
102
+ filename = secure_filename(file.filename)
103
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
104
+ file.save(filepath)
105
+
106
+ try:
107
+ gemini_file = genai.upload_file(filepath)
108
+ return jsonify({"success": True, "filename": filename})
109
+ except Exception as e:
110
+ return jsonify({"error": str(e)}), 500
111
+
112
+ if __name__ == '__main__':
113
+ os.makedirs("temp", exist_ok=True)
114
+ app.run(debug=True)