Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, jsonify, Response, stream_with_context
|
| 2 |
+
from google import genai
|
| 3 |
+
import logging
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
import sys
|
| 6 |
+
from typing import Generator
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
api_key = os.environ.get("GEMINI_API_KEY")
|
| 12 |
+
|
| 13 |
+
#pi_key = "YOUR_API_KEY_HERE"
|
| 14 |
+
|
| 15 |
+
# Configuration du logging
|
| 16 |
+
logging.basicConfig(
|
| 17 |
+
level=logging.DEBUG,
|
| 18 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 19 |
+
handlers=[
|
| 20 |
+
logging.StreamHandler(sys.stdout),
|
| 21 |
+
logging.FileHandler(Path('app.log'))
|
| 22 |
+
]
|
| 23 |
+
)
|
| 24 |
+
logger = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
app = Flask(__name__)
|
| 27 |
+
|
| 28 |
+
class GeminiClient:
|
| 29 |
+
def __init__(self, api_key: str):
|
| 30 |
+
self.client = None
|
| 31 |
+
self.init_client(api_key)
|
| 32 |
+
|
| 33 |
+
def init_client(self, api_key: str) -> None:
|
| 34 |
+
try:
|
| 35 |
+
self.client = genai.Client(
|
| 36 |
+
api_key=api_key,
|
| 37 |
+
http_options={'api_version': 'v1alpha'}
|
| 38 |
+
)
|
| 39 |
+
except Exception as e:
|
| 40 |
+
logger.error(f"Erreur d'initialisation du client Gemini: {e}")
|
| 41 |
+
raise RuntimeError(f"Impossible d'initialiser le client Gemini: {e}")
|
| 42 |
+
|
| 43 |
+
def get_response(self, question: str, model_name: str) -> Generator:
|
| 44 |
+
if not self.client:
|
| 45 |
+
raise RuntimeError("Client Gemini non initialisé")
|
| 46 |
+
|
| 47 |
+
try:
|
| 48 |
+
response = self.client.models.generate_content_stream(
|
| 49 |
+
model=model_name,
|
| 50 |
+
config={'thinking_config': {'include_thoughts': True}},
|
| 51 |
+
contents=[question]
|
| 52 |
+
)
|
| 53 |
+
return response
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"Erreur lors de la génération de la réponse: {e}")
|
| 56 |
+
raise
|
| 57 |
+
|
| 58 |
+
def stream_response(response: Generator):
|
| 59 |
+
thinking_text = ""
|
| 60 |
+
answer_text = ""
|
| 61 |
+
mode = 'starting'
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
for chunk in response:
|
| 65 |
+
if hasattr(chunk, 'candidates') and chunk.candidates:
|
| 66 |
+
content = chunk.candidates[0].content
|
| 67 |
+
|
| 68 |
+
if hasattr(content, 'parts'):
|
| 69 |
+
for part in content.parts:
|
| 70 |
+
has_thought = hasattr(part, 'thought') and part.thought
|
| 71 |
+
text = getattr(part, 'text', '')
|
| 72 |
+
|
| 73 |
+
if not text:
|
| 74 |
+
continue
|
| 75 |
+
|
| 76 |
+
if has_thought:
|
| 77 |
+
thinking_text += text
|
| 78 |
+
yield json.dumps({
|
| 79 |
+
'type': 'thinking',
|
| 80 |
+
'content': thinking_text
|
| 81 |
+
}) + '\n'
|
| 82 |
+
else:
|
| 83 |
+
answer_text += text
|
| 84 |
+
yield json.dumps({
|
| 85 |
+
'type': 'answer',
|
| 86 |
+
'content': answer_text
|
| 87 |
+
}) + '\n'
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
logger.error(f"Erreur dans le streaming de la réponse: {e}")
|
| 91 |
+
yield json.dumps({
|
| 92 |
+
'type': 'error',
|
| 93 |
+
'content': "Une erreur est survenue lors de l'analyse."
|
| 94 |
+
}) + '\n'
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
gemini_client = GeminiClient(api_key)
|
| 98 |
+
|
| 99 |
+
@app.route('/')
|
| 100 |
+
def home():
|
| 101 |
+
return render_template('index.html')
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@app.route('/ask', methods=['POST'])
|
| 106 |
+
def ask():
|
| 107 |
+
# À remplacer par votre clé API
|
| 108 |
+
question = request.json.get('question')
|
| 109 |
+
model_name = "gemini-2.0-flash-thinking-exp-01-21"
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
response = gemini_client.get_response(question, model_name)
|
| 113 |
+
return Response(
|
| 114 |
+
stream_with_context(stream_response(response)),
|
| 115 |
+
mimetype='text/event-stream'
|
| 116 |
+
)
|
| 117 |
+
except Exception as e:
|
| 118 |
+
logger.error(f"Erreur lors de la génération: {e}", exc_info=True)
|
| 119 |
+
return jsonify({'error': "Une erreur est survenue. Veuillez réessayer."}), 500
|
| 120 |
+
|
| 121 |
+
if __name__ == '__main__':
|
| 122 |
+
app.run(debug=True)
|