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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, render_template, request, jsonify, send_file
|
| 2 |
+
import threading
|
| 3 |
+
import time
|
| 4 |
+
import os
|
| 5 |
+
from datetime import datetime
|
| 6 |
+
from google import genai
|
| 7 |
+
import uuid
|
| 8 |
+
|
| 9 |
+
app = Flask(__name__)
|
| 10 |
+
|
| 11 |
+
# Configuration
|
| 12 |
+
GOOGLE_API_KEY = "AIzaSyCVCvvAJbf1oLJV81fNhl56-N2s2f0ZeBc" # Remplacez par votre clé API
|
| 13 |
+
MODEL_ID = "gemini-2.5-flash-preview-05-20" # Ou le modèle que vous utilisez
|
| 14 |
+
UPLOAD_FOLDER = 'uploads'
|
| 15 |
+
RESULTS_FOLDER = 'results'
|
| 16 |
+
|
| 17 |
+
# Créer les dossiers s'ils n'existent pas
|
| 18 |
+
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
| 19 |
+
os.makedirs(RESULTS_FOLDER, exist_ok=True)
|
| 20 |
+
|
| 21 |
+
# Stockage des tâches en cours
|
| 22 |
+
tasks = {}
|
| 23 |
+
|
| 24 |
+
class TaskManager:
|
| 25 |
+
def __init__(self):
|
| 26 |
+
self.tasks = {}
|
| 27 |
+
|
| 28 |
+
def create_task(self, task_id):
|
| 29 |
+
self.tasks[task_id] = {
|
| 30 |
+
'status': 'running',
|
| 31 |
+
'progress': 0,
|
| 32 |
+
'total': 470,
|
| 33 |
+
'results_file': f'results_{task_id}.txt',
|
| 34 |
+
'start_time': datetime.now(),
|
| 35 |
+
'errors': []
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
def update_progress(self, task_id, progress):
|
| 39 |
+
if task_id in self.tasks:
|
| 40 |
+
self.tasks[task_id]['progress'] = progress
|
| 41 |
+
|
| 42 |
+
def add_error(self, task_id, error):
|
| 43 |
+
if task_id in self.tasks:
|
| 44 |
+
self.tasks[task_id]['errors'].append(error)
|
| 45 |
+
|
| 46 |
+
def complete_task(self, task_id):
|
| 47 |
+
if task_id in self.tasks:
|
| 48 |
+
self.tasks[task_id]['status'] = 'completed'
|
| 49 |
+
|
| 50 |
+
def get_task(self, task_id):
|
| 51 |
+
return self.tasks.get(task_id)
|
| 52 |
+
|
| 53 |
+
task_manager = TaskManager()
|
| 54 |
+
|
| 55 |
+
def generate_synthetic_data(file_path, task_id):
|
| 56 |
+
"""Fonction qui exécute les 470 requêtes en arrière-plan"""
|
| 57 |
+
try:
|
| 58 |
+
# Initialiser le client Google AI
|
| 59 |
+
client = genai.Client(api_key=GOOGLE_API_KEY)
|
| 60 |
+
|
| 61 |
+
# Uploader le fichier
|
| 62 |
+
file_ref = client.files.upload(file=file_path)
|
| 63 |
+
|
| 64 |
+
# Prompt pour chaque requête
|
| 65 |
+
prompt = ("J'aimerais générer des nouvelles données synthétiques à partir de ça. "
|
| 66 |
+
"Une fang, une français. Je veux 400 phrases longues.\n\n"
|
| 67 |
+
"Selon le format : fang :.... / Français :...")
|
| 68 |
+
|
| 69 |
+
# Fichier de résultats
|
| 70 |
+
results_file = os.path.join(RESULTS_FOLDER, f'results_{task_id}.txt')
|
| 71 |
+
|
| 72 |
+
with open(results_file, 'w', encoding='utf-8') as f:
|
| 73 |
+
f.write(f"Génération de données synthétiques - Démarré le {datetime.now()}\n")
|
| 74 |
+
f.write("="*60 + "\n\n")
|
| 75 |
+
|
| 76 |
+
for i in range(470):
|
| 77 |
+
try:
|
| 78 |
+
# Faire la requête
|
| 79 |
+
response = client.models.generate_content(
|
| 80 |
+
model=MODEL_ID,
|
| 81 |
+
contents=[file_ref, prompt]
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
# Écrire la réponse dans le fichier
|
| 85 |
+
f.write(f"--- Requête {i+1}/470 ---\n")
|
| 86 |
+
f.write(response.text)
|
| 87 |
+
f.write("\n" + "="*60 + "\n\n")
|
| 88 |
+
f.flush() # Forcer l'écriture
|
| 89 |
+
|
| 90 |
+
# Mettre à jour le progrès
|
| 91 |
+
task_manager.update_progress(task_id, i + 1)
|
| 92 |
+
|
| 93 |
+
print(f"Requête {i+1}/470 complétée")
|
| 94 |
+
|
| 95 |
+
# Pause pour éviter de surcharger l'API
|
| 96 |
+
time.sleep(1)
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
error_msg = f"Erreur requête {i+1}: {str(e)}"
|
| 100 |
+
task_manager.add_error(task_id, error_msg)
|
| 101 |
+
f.write(f"ERREUR - Requête {i+1}: {str(e)}\n")
|
| 102 |
+
f.write("="*60 + "\n\n")
|
| 103 |
+
print(error_msg)
|
| 104 |
+
|
| 105 |
+
task_manager.complete_task(task_id)
|
| 106 |
+
print(f"Tâche {task_id} terminée avec succès")
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
error_msg = f"Erreur générale: {str(e)}"
|
| 110 |
+
task_manager.add_error(task_id, error_msg)
|
| 111 |
+
print(error_msg)
|
| 112 |
+
|
| 113 |
+
@app.route('/')
|
| 114 |
+
def index():
|
| 115 |
+
return render_template('index.html')
|
| 116 |
+
|
| 117 |
+
@app.route('/upload', methods=['POST'])
|
| 118 |
+
def upload_file():
|
| 119 |
+
if 'file' not in request.files:
|
| 120 |
+
return jsonify({'error': 'Aucun fichier sélectionné'}), 400
|
| 121 |
+
|
| 122 |
+
file = request.files['file']
|
| 123 |
+
if file.filename == '':
|
| 124 |
+
return jsonify({'error': 'Aucun fichier sélectionné'}), 400
|
| 125 |
+
|
| 126 |
+
if file:
|
| 127 |
+
# Générer un ID unique pour cette tâche
|
| 128 |
+
task_id = str(uuid.uuid4())
|
| 129 |
+
|
| 130 |
+
# Sauvegarder le fichier
|
| 131 |
+
filename = f"input_{task_id}.txt"
|
| 132 |
+
file_path = os.path.join(UPLOAD_FOLDER, filename)
|
| 133 |
+
file.save(file_path)
|
| 134 |
+
|
| 135 |
+
# Créer la tâche
|
| 136 |
+
task_manager.create_task(task_id)
|
| 137 |
+
|
| 138 |
+
# Démarrer le traitement en arrière-plan
|
| 139 |
+
thread = threading.Thread(
|
| 140 |
+
target=generate_synthetic_data,
|
| 141 |
+
args=(file_path, task_id)
|
| 142 |
+
)
|
| 143 |
+
thread.daemon = True
|
| 144 |
+
thread.start()
|
| 145 |
+
|
| 146 |
+
return jsonify({
|
| 147 |
+
'task_id': task_id,
|
| 148 |
+
'message': 'Traitement démarré en arrière-plan'
|
| 149 |
+
})
|
| 150 |
+
|
| 151 |
+
@app.route('/status/<task_id>')
|
| 152 |
+
def get_status(task_id):
|
| 153 |
+
task = task_manager.get_task(task_id)
|
| 154 |
+
if not task:
|
| 155 |
+
return jsonify({'error': 'Tâche non trouvée'}), 404
|
| 156 |
+
|
| 157 |
+
return jsonify({
|
| 158 |
+
'status': task['status'],
|
| 159 |
+
'progress': task['progress'],
|
| 160 |
+
'total': task['total'],
|
| 161 |
+
'percentage': round((task['progress'] / task['total']) * 100, 2),
|
| 162 |
+
'errors_count': len(task['errors']),
|
| 163 |
+
'start_time': task['start_time'].strftime('%Y-%m-%d %H:%M:%S')
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
@app.route('/download/<task_id>')
|
| 167 |
+
def download_results(task_id):
|
| 168 |
+
task = task_manager.get_task(task_id)
|
| 169 |
+
if not task:
|
| 170 |
+
return jsonify({'error': 'Tâche non trouvée'}), 404
|
| 171 |
+
|
| 172 |
+
results_file = os.path.join(RESULTS_FOLDER, f'results_{task_id}.txt')
|
| 173 |
+
|
| 174 |
+
if not os.path.exists(results_file):
|
| 175 |
+
return jsonify({'error': 'Fichier de résultats non trouvé'}), 404
|
| 176 |
+
|
| 177 |
+
return send_file(
|
| 178 |
+
results_file,
|
| 179 |
+
as_attachment=True,
|
| 180 |
+
download_name=f'donnees_synthetiques_{task_id}.txt'
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
@app.route('/tasks')
|
| 184 |
+
def list_tasks():
|
| 185 |
+
"""Liste toutes les tâches"""
|
| 186 |
+
task_list = []
|
| 187 |
+
for task_id, task_info in task_manager.tasks.items():
|
| 188 |
+
task_list.append({
|
| 189 |
+
'id': task_id,
|
| 190 |
+
'status': task_info['status'],
|
| 191 |
+
'progress': task_info['progress'],
|
| 192 |
+
'total': task_info['total'],
|
| 193 |
+
'percentage': round((task_info['progress'] / task_info['total']) * 100, 2),
|
| 194 |
+
'start_time': task_info['start_time'].strftime('%Y-%m-%d %H:%M:%S'),
|
| 195 |
+
'errors_count': len(task_info['errors'])
|
| 196 |
+
})
|
| 197 |
+
|
| 198 |
+
return jsonify(task_list)
|
| 199 |
+
|
| 200 |
+
if __name__ == '__main__':
|
| 201 |
+
app.run(debug=True, threaded=True)
|