File size: 5,430 Bytes
c253059
da7ef42
c253059
 
da7ef42
 
c253059
 
da7ef42
 
6979c79
c253059
da7ef42
c253059
da7ef42
 
c253059
da7ef42
 
 
 
 
 
 
c253059
 
da7ef42
c253059
da7ef42
 
c253059
 
 
 
 
da7ef42
6979c79
 
 
da7ef42
 
 
 
 
 
 
 
 
 
 
 
 
c253059
da7ef42
 
 
 
 
 
 
 
c253059
 
da7ef42
 
c253059
 
 
 
 
 
 
da7ef42
 
c253059
 
 
 
 
 
 
da7ef42
 
c253059
 
da7ef42
c253059
 
 
 
 
 
 
6979c79
 
 
 
 
c253059
 
 
 
 
 
 
da7ef42
c253059
 
 
6979c79
 
 
c253059
 
da7ef42
c253059
da7ef42
 
c253059
 
 
6979c79
 
 
 
 
c253059
6979c79
c253059
 
 
6979c79
c253059
 
 
 
 
6979c79
c253059
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da7ef42
 
c253059
 
da7ef42
c253059
da7ef42
c253059
 
 
 
6979c79
 
 
 
c253059
da7ef42
c253059
6979c79
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
from flask import Flask, render_template, request, jsonify, session
import google.generativeai as genai
import os
from dotenv import load_dotenv
import http.client
import json
from werkzeug.utils import secure_filename
import tempfile

app = Flask(__name__)
app.secret_key = os.urandom(24)
load_dotenv()

# Configure Google AI
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))

# Safety settings
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"},
]

# System prompt
SYSTEM_PROMPT = """
# Prompt System pour Mariam, IA conçu par youssouf 
[Your existing system prompt content here]
"""

# Initialize Gemini model
model = genai.GenerativeModel('gemini-2.0-flash-exp', 
                            tools='code_execution',
                            safety_settings=safety_settings,
                            system_instruction=SYSTEM_PROMPT)

# Store chat sessions in a dictionary
chat_sessions = {}

def perform_web_search(query):
    conn = http.client.HTTPSConnection("google.serper.dev")
    payload = json.dumps({"q": query})
    headers = {
        'X-API-KEY': '9b90a274d9e704ff5b21c0367f9ae1161779b573',
        'Content-Type': 'application/json'
    }
    try:
        conn.request("POST", "/search", payload, headers)
        res = conn.getresponse()
        data = json.loads(res.read().decode("utf-8"))
        return data
    except Exception as e:
        print(f"Web search error: {e}")
        return None
    finally:
        conn.close()

def format_search_results(data):
    if not data:
        return "Aucun résultat trouvé"
    
    result = []
    
    if 'knowledgeGraph' in data:
        kg = data['knowledgeGraph']
        result.append({
            'type': 'knowledge',
            'title': kg.get('title', ''),
            'description': kg.get('description', ''),
            'category': kg.get('type', '')
        })
    
    if 'organic' in data:
        for item in data['organic'][:3]:
            result.append({
                'type': 'organic',
                'title': item['title'],
                'snippet': item['snippet'],
                'link': item['link']
            })
    
    return result

UPLOAD_FOLDER = 'temp'
ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'pdf', 'txt', 'mp3', 'mp4'}

os.makedirs(UPLOAD_FOLDER, exist_ok=True)

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/')
def home():
    if 'user_id' not in session:
        session['user_id'] = os.urandom(16).hex()
    if 'messages' not in session:
        session['messages'] = []
    return render_template('index.html', messages=session['messages'])

@app.route('/send_message', methods=['POST'])
def send_message():
    try:
        data = request.json
        message = data.get('message')
        web_search_enabled = data.get('web_search', False)
        
        if not message:
            return jsonify({'error': 'No message provided'}), 400

        user_id = session.get('user_id')
        if user_id not in chat_sessions:
            chat_sessions[user_id] = model.start_chat(history=[])

        # Perform web search if enabled
        if web_search_enabled:
            web_results = perform_web_search(message)
            if web_results:
                formatted_results = format_search_results(web_results)
                message = f"""Question: {message}\n\nRésultats de recherche web:\n{formatted_results}\n\nPourrais-tu analyser ces informations et me donner une réponse complète?"""

        # Send message to Gemini
        response = chat_sessions[user_id].send_message(message)
        
        # Update message history in session
        if 'messages' not in session:
            session['messages'] = []
        
        session['messages'].append({
            'role': 'user',
            'content': message
        })
        session['messages'].append({
            'role': 'assistant',
            'content': response.text
        })
        
        return jsonify({
            'response': response.text
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
    
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        filepath = os.path.join(UPLOAD_FOLDER, filename)
        file.save(filepath)
        
        try:
            gemini_file = genai.upload_file(filepath)
            return jsonify({'success': True, 'filename': filename})
        except Exception as e:
            return jsonify({'error': str(e)}), 500
    
    return jsonify({'error': 'Invalid file type'}), 400

@app.route('/clear_chat', methods=['POST'])
def clear_chat():
    user_id = session.get('user_id')
    if user_id in chat_sessions:
        del chat_sessions[user_id]
    session['messages'] = []
    return jsonify({'success': True})

if __name__ == '__main__':
    app.run()