querycraft 2.4.2__tar.gz → 2.6.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {querycraft-2.4.2/querycraft.egg-info → querycraft-2.6.0}/PKG-INFO +1 -1
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/LLM.py +22 -8
- querycraft-2.6.0/querycraft/__init__.py +2 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/cachemanager.py +21 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/config/codemata.json +2 -2
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/configmanager.py +3 -1
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sql/SQLStepByStepService.py +55 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/config.html +2 -1
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/credits.html +24 -3
- querycraft-2.6.0/querycraft/web/__init__.py +6 -0
- querycraft-2.6.0/querycraft/web/admin_routes.py +277 -0
- querycraft-2.6.0/querycraft/web/app.py +28 -0
- querycraft-2.6.0/querycraft/web/context.py +109 -0
- querycraft-2.6.0/querycraft/web/exercices_routes.py +318 -0
- querycraft-2.6.0/querycraft/web/helpers.py +74 -0
- querycraft-2.6.0/querycraft/web/pages.py +93 -0
- querycraft-2.6.0/querycraft/web/sql_routes.py +303 -0
- querycraft-2.6.0/querycraft/web/tenancy.py +236 -0
- querycraft-2.6.0/querycraft/web_sbs.py +48 -0
- {querycraft-2.4.2 → querycraft-2.6.0/querycraft.egg-info}/PKG-INFO +1 -1
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft.egg-info/SOURCES.txt +9 -0
- querycraft-2.4.2/querycraft/__init__.py +0 -2
- querycraft-2.4.2/querycraft/web_sbs.py +0 -1343
- {querycraft-2.4.2 → querycraft-2.6.0}/AUTHORS +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/LICENSE +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/MANIFEST.in +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/README.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/LLM_providers.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/LRS.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/PlantUML.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/SQLException.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/cache/readme.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/config/config-sbs-std.cfg +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/config/config-sbs.cfg +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/cinema.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/cours.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/em.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/entreprise.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/librairie.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/lutins.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/robots.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/data/vols.db +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/database/MYSQL.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/database/PGSQL.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/database/SQLITE.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/database/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/database/base.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exceptions/OperationNotSupportedException.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exceptions/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exercicemanager.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exos/Didapro11.json +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exos/OENU2026.json +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exos/ex1.json +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exos/exos1.json +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/exos/readme.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/logger.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/logs/readme.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/CliOutputFactory.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/CliCodeBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/CliListBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/CliParagraphBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/CliTableBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/CliTextBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/CliTitleBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/cli/outputBuilder/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/OutputBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/OutputCodeFactory.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/OutputFactory.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/OutputListBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/OutputParagraphFactory.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/OutputTableBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/SimpleOutputBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/commons/utils.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/HtmlOutputFactory.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/HTMLCodeBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/HTMLListBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/HTMLParagraphBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/HTMLTableBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/HTMLTextBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/HTMLTitleBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/html/outputBuilder/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/MarkdownOutputFactory.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/MarkdownCodeBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/MarkdownListBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/MarkdownParagraphBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/MarkdownTableBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/MarkdownTextBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/MarkdownTitleBuilder.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/output/markdown/outputBuilder/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/paths.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/security.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sql/SQLContext.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sql/SQLExecutionService.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sql/SQLNormalizationService.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sql/SQLQueryService.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sql/__init__.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/sqlsbs.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-0973b307dafc25e2b7a5f12be0f68d1786cedbf5ad0371c3f3d5f051fc00b626.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-18be2287f8920a2975f21fe98022750b27c222b85ac8d6de95a686835f147e9e.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-3d819e30e542ba328af562eb160d23140f2193d92354b0897289767e1c041e96.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-54c49d1ad35ea5cf736dfd64c3ed9c42ea90d7b82a5f3783f73f46de99bf0987.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-5b552498722250bebfe20f44257243a9f9e08d2f3865955c60f4469ff1c12fea.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-a70191192c2a1640bfec39afd281537d4ede20bb5c9e87ccb32b883e1e58bcab.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-d1881606867eea2d5f0cf600fa342f8e04e8d5cc388946a09cffb855052b22ad.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/static/qc-eb48d0ac9258e52c7715e6313b6da064ed9ab2efab6ba7b3225b9568a3c2545e.puml +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/admin_login.html +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/base.html +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/correction_prompt.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/database_prompt.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/didactique.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/didapro11.html +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/erreur_prompt.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/exercices.html +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/index.html +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/instance_error.html +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/requete_prompt.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/systeme_prompt.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/systeme_prompt_factuel.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/systeme_prompt_valideur.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/templates/valideur_prompt.md +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/tenantadmin.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/tenantlogging.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/tenantregistry.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft/tools.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft.egg-info/dependency_links.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft.egg-info/entry_points.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft.egg-info/requires.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/querycraft.egg-info/top_level.txt +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/setup.cfg +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/setup.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/test/testAnthropic.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/test/testLRS.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/test/testOllama.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/test/testParse.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/test/test_exercicemanager.py +0 -0
- {querycraft-2.4.2 → querycraft-2.6.0}/test/test_litellm_provider.py +0 -0
|
@@ -99,7 +99,8 @@ class LLMService:
|
|
|
99
99
|
self.__logger.error(f"Error building prompt context: {e}")
|
|
100
100
|
return ""
|
|
101
101
|
|
|
102
|
-
def __call_with_cache(self, prompt: str, cache_key: str, kind: str, prompt_systeme: str = None
|
|
102
|
+
def __call_with_cache(self, prompt: str, cache_key: str, kind: str, prompt_systeme: str = None,
|
|
103
|
+
postprocess=None) -> LLMResponse:
|
|
103
104
|
"""Appelle le LLM en utilisant le cache si activé. La clé est basée sur les requêtes SQL.
|
|
104
105
|
|
|
105
106
|
Args:
|
|
@@ -107,6 +108,10 @@ class LLMService:
|
|
|
107
108
|
fonctionnalité dans son propre fichier, plutôt que de tout mélanger dans un
|
|
108
109
|
cache partagé par tenant.
|
|
109
110
|
prompt_systeme: Prompt système à utiliser ; par défaut le prompt système général.
|
|
111
|
+
postprocess: Fonction optionnelle appliquée au texte de la réponse avant sa mise
|
|
112
|
+
en cache (ex. validation par un second LLM). N'est appelée qu'au cache-miss :
|
|
113
|
+
c'est son résultat qui est caché, pas la réponse brute, pour qu'un cache-hit
|
|
114
|
+
renvoie directement un texte déjà post-traité sans refaire l'appel.
|
|
110
115
|
"""
|
|
111
116
|
normalized_key = normalizeCacheKey(cache_key)
|
|
112
117
|
|
|
@@ -127,6 +132,8 @@ class LLMService:
|
|
|
127
132
|
if response is None:
|
|
128
133
|
raw = self.provider.get_response(prompt_systeme or self.prompt_systeme, prompt)
|
|
129
134
|
response = self.__build_response(raw, self.provider)
|
|
135
|
+
if postprocess is not None:
|
|
136
|
+
response = (postprocess(response[0]), response[1])
|
|
130
137
|
if (
|
|
131
138
|
self.cache_enabled
|
|
132
139
|
and cache_file is not None
|
|
@@ -197,9 +204,16 @@ class LLMService:
|
|
|
197
204
|
# deux exercices différents peuvent partager la même requête soumise/attendue tout en
|
|
198
205
|
# ayant une intention ou un commentaire de correction différents, qui font partie du
|
|
199
206
|
# prompt envoyé au LLM.
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
207
|
+
#
|
|
208
|
+
# La validation (second appel LLM, cf. LLMValideur) est passée en postprocess : elle
|
|
209
|
+
# n'a lieu qu'au cache-miss, et c'est son résultat qui est caché — un cache-hit renvoie
|
|
210
|
+
# donc directement un texte déjà validé, sans repasser par le validateur à chaque fois.
|
|
211
|
+
response: LLMResponse = self.__call_with_cache(
|
|
212
|
+
prompt, prompt, "exo",
|
|
213
|
+
postprocess=lambda texte: self.validator.valider_texte(
|
|
214
|
+
sql_attendu, sql_soumis, intention, texte, self.typeOutput
|
|
215
|
+
),
|
|
216
|
+
)
|
|
203
217
|
return self.format_ia(response, "Commentaires sur la requête", self.typeOutput)
|
|
204
218
|
|
|
205
219
|
def analyseDbSchema(self, db_key: str,outputType: TypeOutput = "text") -> OutputFactory:
|
|
@@ -318,7 +332,7 @@ class LLMService:
|
|
|
318
332
|
styleBlockAI = Style(colorama.Fore.GREEN, "class='ia'", '')
|
|
319
333
|
if response:
|
|
320
334
|
if outputType == 'html' and detect_format(response.response) == 'html':
|
|
321
|
-
(output.addTitle(f"{titre} par IA générative", 3, styleTitle)
|
|
335
|
+
(output.addTitle(f"{titre} par l'IA générative", 3, styleTitle)
|
|
322
336
|
.addBlock(getOutputFactory(outputType, 'block')
|
|
323
337
|
.addText(response.response)
|
|
324
338
|
.setStyle(styleBlockAI)
|
|
@@ -326,7 +340,7 @@ class LLMService:
|
|
|
326
340
|
.addText(response.source, Style('', "style='font-size: 10px;'", ''))
|
|
327
341
|
.addText(response.cache, Style('', "style='font-size: 10px;'", ''))))
|
|
328
342
|
else:
|
|
329
|
-
(output.addTitle(f"{titre} par IA générative", 3, styleTitle)
|
|
343
|
+
(output.addTitle(f"{titre} par l'IA générative", 3, styleTitle)
|
|
330
344
|
.addBlock(markdown_to_output(response.response, outputType)
|
|
331
345
|
.setStyle(styleBlockAI)
|
|
332
346
|
.addLineSeparator()
|
|
@@ -334,7 +348,7 @@ class LLMService:
|
|
|
334
348
|
.addText(response.cache, Style('', "style='font-size: 10px;'", ''))))
|
|
335
349
|
else:
|
|
336
350
|
output.addBlock(getOutputFactory(outputType, 'paragraph')
|
|
337
|
-
.addText(f"{titre} par IA générative impossible")
|
|
351
|
+
.addText(f"{titre} par l'IA générative impossible")
|
|
338
352
|
.setStyle(styleBlockAI))
|
|
339
353
|
return output
|
|
340
354
|
|
|
@@ -394,7 +408,7 @@ class LLMValideur:
|
|
|
394
408
|
def valider(self, texte: str):
|
|
395
409
|
if not self.llm:
|
|
396
410
|
return texte, False, "Aucun modèle de validation configuré"
|
|
397
|
-
return self.valider_texte(texte, True, f"Validation par IA générative ({self.llm.display_name})")
|
|
411
|
+
return self.valider_texte(texte, True, f"Validation par l'IA générative ({self.llm.display_name})")
|
|
398
412
|
|
|
399
413
|
def valider_texte(self, sqlcible: str, sqletu: str, intention: str, texte: str, output: TypeOutput):
|
|
400
414
|
prompt = self.__build_prompt(sqlcible, sqletu, intention, texte, output)
|
|
@@ -124,6 +124,27 @@ def saveCache(cacheName: str, cle: str, val, cache_dir=None) -> None:
|
|
|
124
124
|
fcntl.flock(lock, fcntl.LOCK_UN)
|
|
125
125
|
|
|
126
126
|
|
|
127
|
+
def deleteCache(cacheName: str, cache_dir=None) -> bool:
|
|
128
|
+
"""Supprime le fichier de cache et son verrou (``.lock``, cf. ``saveCache``) s'ils existent.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
cacheName: Nom du fichier de cache.
|
|
132
|
+
cache_dir: Répertoire de cache de l'instance (défaut : package).
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
True si le fichier de cache a été supprimé, False s'il n'y en avait pas
|
|
136
|
+
(le verrou, lui, est supprimé sans conditionner ce retour).
|
|
137
|
+
"""
|
|
138
|
+
file = _resolve_cache_file(cacheName, cache_dir)
|
|
139
|
+
lock_file = file.with_name(file.name + ".lock")
|
|
140
|
+
if existFile(lock_file):
|
|
141
|
+
lock_file.unlink()
|
|
142
|
+
if existFile(file):
|
|
143
|
+
file.unlink()
|
|
144
|
+
return True
|
|
145
|
+
return False
|
|
146
|
+
|
|
147
|
+
|
|
127
148
|
def diff_dates_iso(date_iso1: str, date_iso2: str) -> int:
|
|
128
149
|
"""Retourne le nombre de jours de différence entre deux dates au format ISO."""
|
|
129
150
|
d1 = date.fromisoformat(date_iso1)
|
|
@@ -30,12 +30,12 @@
|
|
|
30
30
|
}
|
|
31
31
|
],
|
|
32
32
|
"dateCreated": "2024-07-15",
|
|
33
|
-
"dateModified": "2026-07-
|
|
33
|
+
"dateModified": "2026-07-25",
|
|
34
34
|
"datePublished": "2024-12-04",
|
|
35
35
|
"description": "Ce programme permet de proposer une exécution \"pas à pas\" d'une requête SQL. Il doit être utilisé dans le cadre d'un enseignement de SQL en bases de données. Cette bibliothèque propose des classes Python permettant de manipuler des requêtes SQL. Elle propose aussi des applications pour décomposer l'exécution d'une requête SQL sur une base de données PostgreSQL, MySQL ou SQLite.",
|
|
36
36
|
"downloadUrl": "https://gitlab.univ-nantes.fr/ls2n-didactique/querycraft.git",
|
|
37
37
|
"license": "https://spdx.org/licenses/GPL-3.0",
|
|
38
38
|
"name": "QueryCraft",
|
|
39
39
|
"programmingLanguage": "Python 3",
|
|
40
|
-
"version": "2.
|
|
40
|
+
"version": "2.6.0"
|
|
41
41
|
}
|
|
@@ -316,7 +316,9 @@ class ConfigurationBuilder:
|
|
|
316
316
|
return SQLExecutionService(db, normalizationService, self.ia_demandee, self.debug, self.type_output)
|
|
317
317
|
|
|
318
318
|
def buildSQLStepByStepService(self, db: Database, executionService: SQLExecutionService, normalizationService: SQLNormalizationService) -> SQLStepByStepService:
|
|
319
|
-
return SQLStepByStepService(db, executionService, normalizationService, self.debug, self.ia_demandee
|
|
319
|
+
return SQLStepByStepService(db, executionService, normalizationService, self.debug, self.ia_demandee,
|
|
320
|
+
cache_enabled=self.cache, cache_duration=self.duree_cache,
|
|
321
|
+
cache_dir=self._paths.cache_dir)
|
|
320
322
|
|
|
321
323
|
def buildSQLQueryService(self, db: Database, llm_service: LLMService, normalizer: SQLNormalizationService,
|
|
322
324
|
executionService: SQLExecutionService, stepByStepService: SQLStepByStepService,
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
from __future__ import annotations
|
|
3
3
|
|
|
4
|
+
import json
|
|
4
5
|
import logging
|
|
5
6
|
import re
|
|
7
|
+
from pathlib import Path
|
|
6
8
|
from typing import List, Optional
|
|
7
9
|
|
|
8
10
|
from sqlglot.expressions import (
|
|
@@ -13,6 +15,7 @@ from sqlglot.expressions import (
|
|
|
13
15
|
Table,
|
|
14
16
|
)
|
|
15
17
|
|
|
18
|
+
from querycraft.cachemanager import deleteCache, loadCache, normalizeCacheKey, saveCache
|
|
16
19
|
from querycraft.database import Database
|
|
17
20
|
from querycraft.logger import get_logger
|
|
18
21
|
from querycraft.sql.SQLContext import SQLContext
|
|
@@ -50,6 +53,9 @@ class SQLStepByStepService:
|
|
|
50
53
|
norm: SQLNormalizationService,
|
|
51
54
|
debug: bool = False,
|
|
52
55
|
ia_demandee: bool = False,
|
|
56
|
+
cache_enabled: bool = False,
|
|
57
|
+
cache_duration: int = 60,
|
|
58
|
+
cache_dir=None,
|
|
53
59
|
):
|
|
54
60
|
"""
|
|
55
61
|
Args:
|
|
@@ -58,6 +64,9 @@ class SQLStepByStepService:
|
|
|
58
64
|
norm: Service de normalisation des noms.
|
|
59
65
|
debug: Mode debug.
|
|
60
66
|
ia_demandee: Aide de l'IA demandée par défaut pour cette instance.
|
|
67
|
+
cache_enabled: Active le cache des étapes pas-à-pas.
|
|
68
|
+
cache_duration: Durée de validité du cache en jours.
|
|
69
|
+
cache_dir: Répertoire de cache de l'instance (défaut : package).
|
|
61
70
|
"""
|
|
62
71
|
self.__logger = get_logger(__name__)
|
|
63
72
|
self._db = db
|
|
@@ -65,6 +74,9 @@ class SQLStepByStepService:
|
|
|
65
74
|
self._norm = norm
|
|
66
75
|
self.debug = debug
|
|
67
76
|
self.ia_demandee = ia_demandee
|
|
77
|
+
self._cache_enabled = cache_enabled
|
|
78
|
+
self._cache_duration = cache_duration
|
|
79
|
+
self._cache_dir = cache_dir
|
|
68
80
|
|
|
69
81
|
"""
|
|
70
82
|
Dictionnaire table → (None, [(nom_col, est_pk, clé_étrangère), ...]).
|
|
@@ -80,6 +92,31 @@ class SQLStepByStepService:
|
|
|
80
92
|
}
|
|
81
93
|
|
|
82
94
|
|
|
95
|
+
def _cache_file_name(self) -> str:
|
|
96
|
+
"""Nom du fichier de cache dédié à cette base (un fichier par BD+type).
|
|
97
|
+
|
|
98
|
+
Un fichier par base plutôt qu'un fichier partagé (contrairement au cache
|
|
99
|
+
IA) : cela permet une purge triviale (suppression du fichier) depuis la
|
|
100
|
+
page de configuration, sans avoir à filtrer les entrées d'un cache
|
|
101
|
+
commun à plusieurs bases.
|
|
102
|
+
|
|
103
|
+
Seul le nom de la base (sans chemin) entre dans le nom de fichier : pour
|
|
104
|
+
SQLite, ``getDatabaseName()`` renvoie le chemin complet, mais le fichier
|
|
105
|
+
de cache est de toute façon déjà dans le répertoire de l'instance —
|
|
106
|
+
inutile d'y refléter tout le chemin.
|
|
107
|
+
"""
|
|
108
|
+
db_name = Path(self._db.getDatabaseName() or "").name
|
|
109
|
+
safe_name = re.sub(r"[^A-Za-z0-9_.-]", "_", db_name)
|
|
110
|
+
return f"sbs_{self._db.getType()}_{safe_name}.json"
|
|
111
|
+
|
|
112
|
+
def purge_cache(self) -> bool:
|
|
113
|
+
"""Supprime le fichier de cache du pas-à-pas de cette base.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
True si un fichier a été supprimé, False s'il n'y en avait pas.
|
|
117
|
+
"""
|
|
118
|
+
return deleteCache(self._cache_file_name(), self._cache_dir)
|
|
119
|
+
|
|
83
120
|
def _create_step_context(self, sql_str: str, sql_tables: list | None = None) -> SQLContext:
|
|
84
121
|
"""Crée et exécute un SQLContext pour une étape intermédiaire."""
|
|
85
122
|
ctx = SQLContext()
|
|
@@ -656,6 +693,15 @@ class SQLStepByStepService:
|
|
|
656
693
|
Returns:
|
|
657
694
|
Tuple (nb_étapes, liste_étapes) où chaque étape est (index, représentation).
|
|
658
695
|
"""
|
|
696
|
+
cache_key = None
|
|
697
|
+
if self._cache_enabled:
|
|
698
|
+
cache_key = normalizeCacheKey(ctx.sql_request)
|
|
699
|
+
cache = loadCache(self._cache_file_name(), self._cache_duration, self._cache_dir)
|
|
700
|
+
if cache_key in cache:
|
|
701
|
+
(nb_stp, l) = cache[cache_key][0]
|
|
702
|
+
self.__logger.debug("sbs: résultat depuis le cache (%s)", self._cache_file_name())
|
|
703
|
+
return nb_stp, l
|
|
704
|
+
|
|
659
705
|
alltabs = self.sbs_sql(ctx)
|
|
660
706
|
l = []
|
|
661
707
|
prec = []
|
|
@@ -664,4 +710,13 @@ class SQLStepByStepService:
|
|
|
664
710
|
self.__logger.debug("sbs: %s" % step_ctx.sql_request)
|
|
665
711
|
l.append((i, self.table_with_name(step_ctx, step_name, prec)))
|
|
666
712
|
prec = step_ctx.sql_results[1:]
|
|
713
|
+
|
|
714
|
+
if self._cache_enabled:
|
|
715
|
+
# Passage par un aller-retour JSON : les données de résultats peuvent
|
|
716
|
+
# contenir des types non natifs JSON selon le SGBD (dates, Decimal...).
|
|
717
|
+
# Sans conséquence ici puisque cette structure ne sert plus qu'à
|
|
718
|
+
# l'affichage, jamais à un recalcul.
|
|
719
|
+
safe_result = json.loads(json.dumps([nb_stp, l], default=str))
|
|
720
|
+
saveCache(self._cache_file_name(), cache_key, safe_result, self._cache_dir)
|
|
721
|
+
|
|
667
722
|
return nb_stp, l
|
|
@@ -53,6 +53,7 @@
|
|
|
53
53
|
</div>
|
|
54
54
|
<div class="form-group" id="testBD-selector">
|
|
55
55
|
<button type="button" class="btn btn-primary js-test-bd">🛠 Tester la base de données</button>
|
|
56
|
+
<button type="button" class="btn btn-secondary js-purge-sbs-cache">🗑 Purger le cache du pas-à-pas</button>
|
|
56
57
|
<div class="alert" id="alertBoxBD"></div>
|
|
57
58
|
<div class="loading" id="loadingBD">
|
|
58
59
|
<div class="spinner"></div>
|
|
@@ -372,7 +373,7 @@
|
|
|
372
373
|
|
|
373
374
|
<div class="form-row">
|
|
374
375
|
<div class="form-group">
|
|
375
|
-
<label for="autre_cache">Cache IA</label>
|
|
376
|
+
<label for="autre_cache">Cache IA générative et pas à pas</label>
|
|
376
377
|
<select id="autre_cache" name="Autre.cache">
|
|
377
378
|
<option value="on" {{
|
|
378
379
|
'selected' if config.Autre.cache == 'on' }}>Activé</option>
|
|
@@ -42,6 +42,8 @@
|
|
|
42
42
|
<a href="http://desmontils.net/SQLSandbox/" target="_blank" class="link-btn">
|
|
43
43
|
📦 SQLSandbox
|
|
44
44
|
</a>
|
|
45
|
+
|
|
46
|
+
|
|
45
47
|
</div>
|
|
46
48
|
|
|
47
49
|
<!-- Obtenir une instance -->
|
|
@@ -65,6 +67,21 @@
|
|
|
65
67
|
</a>
|
|
66
68
|
</div>
|
|
67
69
|
|
|
70
|
+
<!-- Support / Contact -->
|
|
71
|
+
<div class="section">
|
|
72
|
+
<h2>💬 Une question ?</h2>
|
|
73
|
+
<p>
|
|
74
|
+
Un canal Tchap (la messagerie instantanée de l'État) est disponible pour poser vos questions
|
|
75
|
+
et obtenir des informations sur QueryCraft.
|
|
76
|
+
</p>
|
|
77
|
+
<a href="https://tchap.gouv.fr/#/room/!JhMtAFYUfoAKoWkQPm:agent.education.tchap.gouv.fr?via=agent.education.tchap.gouv.fr"
|
|
78
|
+
target="_blank" class="link-btn">
|
|
79
|
+
<img src="{{ url_for('static', filename='images/tchap-logo.svg') }}" alt="Tchap"
|
|
80
|
+
style="width: 20px; height: 24px; object-fit: contain;"/>
|
|
81
|
+
Rejoindre le canal Tchap
|
|
82
|
+
</a>
|
|
83
|
+
</div>
|
|
84
|
+
|
|
68
85
|
<!-- Auteur -->
|
|
69
86
|
<div class="section">
|
|
70
87
|
<h2>👨🏫 Auteurs</h2>
|
|
@@ -126,7 +143,7 @@
|
|
|
126
143
|
<div class="tech-item">
|
|
127
144
|
<div class="icon">🤖</div>
|
|
128
145
|
<div class="name">IA (LLM)</div>
|
|
129
|
-
<div class="version">Ollama, LM Studio, OpenAI, Google</div>
|
|
146
|
+
<div class="version">Ollama, LM Studio, OpenAI, Google, Anthropic, Albert (DINUM), ILaaS, Poe</div>
|
|
130
147
|
</div>
|
|
131
148
|
</div>
|
|
132
149
|
|
|
@@ -138,7 +155,7 @@
|
|
|
138
155
|
<li><strong>mysql-connector-python</strong> - Connecteur MySQL</li>
|
|
139
156
|
<li><strong>colorama</strong> - Colorisation du terminal</li>
|
|
140
157
|
<li><strong>markdown</strong> - Conversion Markdown vers HTML</li>
|
|
141
|
-
<li><strong>
|
|
158
|
+
<li><strong>plantuml</strong> - Génération des diagrammes du modèle relationnel</li>
|
|
142
159
|
<li><strong>jinja2</strong> - Génération de templates HTML</li>
|
|
143
160
|
<li><strong>argparse</strong> - Gestion des arguments en ligne de commande</li>
|
|
144
161
|
<li><strong>tincan</strong> - Génération de rapports xAPI</li>
|
|
@@ -146,7 +163,9 @@
|
|
|
146
163
|
|
|
147
164
|
<li><strong>openai</strong> - Intégration avec les modèles OpenAI</li>
|
|
148
165
|
<li><strong>ollama</strong> - Intégration avec les modèles Ollama</li>
|
|
149
|
-
<li><strong>google-
|
|
166
|
+
<li><strong>google-genai</strong> - Intégration avec les modèles Google</li>
|
|
167
|
+
<li><strong>anthropic</strong> - Intégration avec les modèles Anthropic (Claude)</li>
|
|
168
|
+
<li><strong>litellm</strong> - Abstraction unifiée pour certains fournisseurs IA (Albert, ILaaS...)</li>
|
|
150
169
|
<li><strong>lmstudio</strong> - Intégration avec les modèles LM Studio</li>
|
|
151
170
|
|
|
152
171
|
</ul>
|
|
@@ -164,8 +183,10 @@
|
|
|
164
183
|
<li>🤖 <strong>Aide par IA générative</strong> - Explications contextuelles des erreurs et suggestions de correction
|
|
165
184
|
</li>
|
|
166
185
|
<li>📚 <strong>Gestion d'exercices</strong> - Création et organisation d'exercices pédagogiques</li>
|
|
186
|
+
<li>📐 <strong>Diagramme relationnel</strong> - Génération automatique du schéma de la base de données</li>
|
|
167
187
|
<li>🎨 <strong>Interface moderne</strong> - Design responsive et intuitif</li>
|
|
168
188
|
<li>🗄️ <strong>Multi-SGBD</strong> - Support de SQLite, PostgreSQL et MySQL</li>
|
|
189
|
+
<li>🏢 <strong>Multi-tenant</strong> - Une instance dédiée par enseignant (configuration, bases et exercices propres)</li>
|
|
169
190
|
<li>⚙️ <strong>Configuration flexible</strong> - Personnalisation complète via interface web</li>
|
|
170
191
|
<!--li>📈 <strong>Traces d'apprentissage</strong> - Intégration xAPI/LRS pour le suivi pédagogique</li-->
|
|
171
192
|
</ul>
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Mode enseignant : connexion, page de configuration du tenant, sondes IA/BD.
|
|
4
|
+
|
|
5
|
+
(c) E. Desmontils, Nantes Université, 2026
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import secrets
|
|
9
|
+
import sqlite3
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
11
|
+
|
|
12
|
+
from flask import Blueprint, g, jsonify, redirect, render_template, request, session
|
|
13
|
+
from werkzeug.utils import secure_filename
|
|
14
|
+
|
|
15
|
+
from querycraft.__init__ import __version__
|
|
16
|
+
from querycraft.LLM_providers import LLMBuilder
|
|
17
|
+
from querycraft.configmanager import ConfigurationHelper
|
|
18
|
+
from querycraft.database import DatabaseProvider
|
|
19
|
+
from querycraft.logger import get_logger
|
|
20
|
+
from querycraft.web.context import ALLOWED_DB_EXTENSIONS, app_config, current_config, registry
|
|
21
|
+
from querycraft.web.helpers import error_ref, get_available_databases, json_errors
|
|
22
|
+
from querycraft.web.tenancy import admin_required, expected_admin_code
|
|
23
|
+
|
|
24
|
+
admin_bp = Blueprint("admin", __name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@admin_bp.route("/admin")
|
|
28
|
+
def admin_login():
|
|
29
|
+
"""Page de connexion au mode enseignant du tenant courant."""
|
|
30
|
+
if g.is_admin:
|
|
31
|
+
return redirect(f"{g.base_path}/")
|
|
32
|
+
return render_template("admin_login.html", version=__version__)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@admin_bp.route("/admin/login", methods=["POST"])
|
|
36
|
+
def admin_login_post():
|
|
37
|
+
"""Vérifie le code enseignant et déverrouille le mode enseignant (session)."""
|
|
38
|
+
code = g.tenant_code
|
|
39
|
+
submitted = (request.form.get("code") or "").strip()
|
|
40
|
+
expected = expected_admin_code(code)
|
|
41
|
+
if expected is not None and secrets.compare_digest(submitted, expected):
|
|
42
|
+
session[f"admin_{code}"] = True
|
|
43
|
+
return redirect(f"{g.base_path}/")
|
|
44
|
+
return render_template("admin_login.html", version=__version__, error=True), 401
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@admin_bp.route("/admin/logout")
|
|
48
|
+
def admin_logout():
|
|
49
|
+
"""Quitte le mode enseignant (retire le drapeau de session)."""
|
|
50
|
+
session.pop(f"admin_{g.tenant_code}", None)
|
|
51
|
+
return redirect(f"{g.base_path}/")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@admin_bp.route("/config/services-status")
|
|
55
|
+
@admin_required
|
|
56
|
+
def config_services_status():
|
|
57
|
+
"""Sonde tous les services IA connus en parallèle (clé/URL par défaut) et renvoie leur statut."""
|
|
58
|
+
results = {}
|
|
59
|
+
with ThreadPoolExecutor(max_workers=len(LLMBuilder.KNOWN_SERVICES)) as executor:
|
|
60
|
+
futures = {executor.submit(LLMBuilder.probeService, s, "None", "None"): s for s in LLMBuilder.KNOWN_SERVICES}
|
|
61
|
+
for future, service in futures.items():
|
|
62
|
+
try:
|
|
63
|
+
result = future.result(timeout=8)
|
|
64
|
+
except Exception:
|
|
65
|
+
result = {"status": "error", "message": "Délai dépassé ou erreur inattendue."}
|
|
66
|
+
results[service] = {"status": result["status"], "message": result["message"]}
|
|
67
|
+
return jsonify(results)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@admin_bp.route("/config/models")
|
|
71
|
+
@admin_required
|
|
72
|
+
def config_models():
|
|
73
|
+
"""Retourne la liste des modèles disponibles pour un service donné, avec son statut"""
|
|
74
|
+
service = request.args.get("service", "ollama")
|
|
75
|
+
url = request.args.get("url", "None")
|
|
76
|
+
api = request.args.get("api", "None")
|
|
77
|
+
return jsonify(LLMBuilder.probeService(service, url, api))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@admin_bp.route("/config")
|
|
81
|
+
@admin_required
|
|
82
|
+
def config_page():
|
|
83
|
+
"""Page de configuration"""
|
|
84
|
+
# Récupérer les modèles disponibles pour le provider actuel
|
|
85
|
+
probe = LLMBuilder.probeService(
|
|
86
|
+
app_config.ia_service or "ollama",
|
|
87
|
+
app_config.ia_url or "None",
|
|
88
|
+
app_config.ia_api_key or "None",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
config_data = ConfigurationHelper.get_config_display_data(current_config())
|
|
92
|
+
available_databases = get_available_databases()
|
|
93
|
+
|
|
94
|
+
return render_template(
|
|
95
|
+
"config.html",
|
|
96
|
+
config=config_data,
|
|
97
|
+
version=__version__,
|
|
98
|
+
available_databases=available_databases,
|
|
99
|
+
available_models=probe["models"],
|
|
100
|
+
ia_models_status=probe["status"],
|
|
101
|
+
ia_models_message=probe["message"],
|
|
102
|
+
currentmodel=app_config.llm_provider.modele if app_config.llm_provider else None,
|
|
103
|
+
currentservice=app_config.llm_provider.service if app_config.llm_provider else None,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@admin_bp.route("/config/save", methods=["POST"])
|
|
108
|
+
@admin_required
|
|
109
|
+
def config_save():
|
|
110
|
+
"""Sauvegarde la configuration du tenant courant"""
|
|
111
|
+
# Sécurité (#127) : Database.password et IA.api-key ne sont plus réémis au
|
|
112
|
+
# client (cf. ConfigurationHelper._SECRET_FIELDS) et un envoi vide les
|
|
113
|
+
# préserve au lieu de les effacer. Reste non traité : stockage en clair
|
|
114
|
+
# dans config-sbs.cfg et absence de garantie HTTPS sur le transport.
|
|
115
|
+
try:
|
|
116
|
+
data = request.get_json()
|
|
117
|
+
|
|
118
|
+
g.tenant_config = registry.save(g.tenant_code, data)
|
|
119
|
+
|
|
120
|
+
return jsonify(
|
|
121
|
+
{"success": True, "message": "Configuration sauvegardée avec succès"}
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
except Exception as e:
|
|
125
|
+
ref = error_ref()
|
|
126
|
+
get_logger("querycraft.web.config").error(
|
|
127
|
+
"[réf %s] Erreur lors de la sauvegarde : %s", ref, e, exc_info=True
|
|
128
|
+
)
|
|
129
|
+
return jsonify(
|
|
130
|
+
{
|
|
131
|
+
"success": False,
|
|
132
|
+
"error": f"Erreur lors de la sauvegarde : {str(e)} (réf: {ref})",
|
|
133
|
+
}
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@admin_bp.route("/config/cache/purge-sbs", methods=["POST"])
|
|
138
|
+
@admin_required
|
|
139
|
+
@json_errors
|
|
140
|
+
def config_purge_sbs_cache():
|
|
141
|
+
"""Purge le cache du pas-à-pas pour la base de données courante du tenant."""
|
|
142
|
+
deleted = current_config().step_by_step_service.purge_cache()
|
|
143
|
+
return jsonify({"success": True, "deleted": deleted})
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
@admin_bp.route("/config/upload-db", methods=["POST"])
|
|
147
|
+
@admin_required
|
|
148
|
+
def config_upload_db():
|
|
149
|
+
"""Téléverse une base SQLite dans le répertoire de données du tenant courant.
|
|
150
|
+
|
|
151
|
+
Le nom de fichier est sécurisé (``secure_filename``) et le fichier est stocké
|
|
152
|
+
dans ``instances/<code>/data``, jamais ailleurs : un tenant ne peut donc pas
|
|
153
|
+
écrire dans le dossier d'un autre. Le format SQLite est validé après écriture.
|
|
154
|
+
"""
|
|
155
|
+
try:
|
|
156
|
+
file = request.files.get("file")
|
|
157
|
+
if file is None or file.filename == "":
|
|
158
|
+
return jsonify({"success": False, "error": "Aucun fichier fourni"})
|
|
159
|
+
|
|
160
|
+
filename = secure_filename(file.filename)
|
|
161
|
+
if not filename.lower().endswith(ALLOWED_DB_EXTENSIONS):
|
|
162
|
+
return jsonify({"success": False,
|
|
163
|
+
"error": "Format attendu : " + ", ".join(ALLOWED_DB_EXTENSIONS)})
|
|
164
|
+
|
|
165
|
+
data_dir = current_config().paths.data_dir
|
|
166
|
+
data_dir.mkdir(parents=True, exist_ok=True)
|
|
167
|
+
dest = data_dir / filename
|
|
168
|
+
file.save(str(dest))
|
|
169
|
+
|
|
170
|
+
# Validation : le fichier doit être une base SQLite lisible
|
|
171
|
+
try:
|
|
172
|
+
con = sqlite3.connect(str(dest))
|
|
173
|
+
con.execute("PRAGMA schema_version;")
|
|
174
|
+
con.close()
|
|
175
|
+
except Exception:
|
|
176
|
+
try:
|
|
177
|
+
dest.unlink()
|
|
178
|
+
except OSError:
|
|
179
|
+
pass
|
|
180
|
+
return jsonify({"success": False, "error": "Fichier SQLite invalide"})
|
|
181
|
+
|
|
182
|
+
return jsonify({"success": True, "filename": filename})
|
|
183
|
+
except Exception as e:
|
|
184
|
+
return jsonify({"success": False, "error": f"Erreur lors du téléversement : {str(e)}"})
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@admin_bp.route("/bdactive", methods=["POST"])
|
|
188
|
+
@admin_required
|
|
189
|
+
def bdalive():
|
|
190
|
+
"""Vérifie si la base de données est accessible et retourne le résultat"""
|
|
191
|
+
data = request.get_json()
|
|
192
|
+
dbtype = data.get("dbtype", "")
|
|
193
|
+
dbname = data.get("dbname", "")
|
|
194
|
+
dbuser = data.get("dbuser", "")
|
|
195
|
+
dbpass = data.get("dbpass", "")
|
|
196
|
+
dbhost = data.get("dbhost", "")
|
|
197
|
+
dbport = data.get("dbport", "")
|
|
198
|
+
if not dbpass:
|
|
199
|
+
# Le champ mot de passe n'est jamais réémis au client (cf. TODO #127) :
|
|
200
|
+
# un envoi vide signifie "utiliser le mot de passe déjà enregistré".
|
|
201
|
+
stored_password = current_config().db_password
|
|
202
|
+
dbpass = stored_password if stored_password and stored_password != "None" else ""
|
|
203
|
+
log = get_logger("querycraft.web.evalBD")
|
|
204
|
+
try:
|
|
205
|
+
database = DatabaseProvider.get(type=dbtype, dbname=str(dbname), dbhost=dbhost, dbport=dbport, dbuser=dbuser,
|
|
206
|
+
dbpassword=dbpass, data_dir=current_config().paths.data_dir)
|
|
207
|
+
if database:
|
|
208
|
+
with database:
|
|
209
|
+
if database.isActive():
|
|
210
|
+
log.info(f"Connexion à la base de données {dbname} réussie.")
|
|
211
|
+
result = True
|
|
212
|
+
else:
|
|
213
|
+
log.info(f"Échec de la connexion à la base de données : {database}")
|
|
214
|
+
result = False
|
|
215
|
+
except Exception as e:
|
|
216
|
+
log.info(f"Erreur lors de la connexion à la base de données : {e}")
|
|
217
|
+
result = False
|
|
218
|
+
return jsonify({"success": result})
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
@admin_bp.route("/config/databases", methods=["POST"])
|
|
222
|
+
@admin_required
|
|
223
|
+
def config_databases():
|
|
224
|
+
"""Liste les bases pgsql/mysql accessibles avec les paramètres du formulaire"""
|
|
225
|
+
data = request.get_json()
|
|
226
|
+
dbtype = data.get("dbtype", "")
|
|
227
|
+
dbhost = data.get("dbhost", "")
|
|
228
|
+
dbport = data.get("dbport", "")
|
|
229
|
+
dbuser = data.get("dbuser", "")
|
|
230
|
+
dbpass = data.get("dbpass", "")
|
|
231
|
+
if not dbpass:
|
|
232
|
+
# Le champ mot de passe n'est jamais réémis au client (cf. TODO #127) :
|
|
233
|
+
# un envoi vide signifie "utiliser le mot de passe déjà enregistré".
|
|
234
|
+
stored_password = current_config().db_password
|
|
235
|
+
dbpass = stored_password if stored_password and stored_password != "None" else ""
|
|
236
|
+
try:
|
|
237
|
+
dbport_int = int(dbport) if dbport else 0
|
|
238
|
+
except ValueError:
|
|
239
|
+
dbport_int = 0
|
|
240
|
+
result = DatabaseProvider.listDatabases(type=dbtype, dbhost=dbhost, dbport=dbport_int, dbuser=dbuser, dbpassword=dbpass)
|
|
241
|
+
return jsonify(result)
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
@admin_bp.route("/iaalive", methods=["POST"])
|
|
245
|
+
@admin_required
|
|
246
|
+
def iaalive():
|
|
247
|
+
"""Vérifie si le service IA est accessible et retourne le résultat"""
|
|
248
|
+
data = request.get_json()
|
|
249
|
+
ia_service = data.get("ia_service", "ollama")
|
|
250
|
+
ia_model = data.get("ia_model", "gemma3:4b")
|
|
251
|
+
ia_url = data.get("ia_url", "None")
|
|
252
|
+
ia_api = data.get("ia_api", "None")
|
|
253
|
+
if not ia_api or ia_api == "None":
|
|
254
|
+
# La clé API n'est jamais réémise au client (cf. TODO #127) : un envoi
|
|
255
|
+
# vide/"None" signifie "utiliser la clé déjà enregistrée".
|
|
256
|
+
stored_key = current_config().ia_api_key
|
|
257
|
+
ia_api = stored_key if stored_key and stored_key != "None" else "None"
|
|
258
|
+
|
|
259
|
+
ok = False
|
|
260
|
+
log = get_logger("querycraft.web")
|
|
261
|
+
provider = LLMBuilder.buildFromParams(
|
|
262
|
+
service=ia_service or "ollama",
|
|
263
|
+
modele=ia_model or "",
|
|
264
|
+
url=ia_url or "None",
|
|
265
|
+
api=ia_api or "None",
|
|
266
|
+
)
|
|
267
|
+
if provider:
|
|
268
|
+
ok = provider.is_alive()
|
|
269
|
+
if ok:
|
|
270
|
+
log.info(f"LLM modèle actif : {provider.getName()}")
|
|
271
|
+
else:
|
|
272
|
+
log.info(f"LLM modèle absent : {provider.getName()}")
|
|
273
|
+
else:
|
|
274
|
+
log.info(f"LLM pas utilisable : service={ia_service} modele={ia_model} url={ia_url}")
|
|
275
|
+
|
|
276
|
+
defllm = LLMBuilder.buildDefault() is not None
|
|
277
|
+
return jsonify({"success": ok or defllm, "def": ok})
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Assemblage de l'application web : enregistre chaque blueprint sur ``app`` puis
|
|
4
|
+
duplique toutes les routes sous ``/<code>`` pour l'accès par tenant.
|
|
5
|
+
|
|
6
|
+
Point d'entrée unique pour obtenir l'app Flask complète — importer ce module
|
|
7
|
+
(plutôt que ``querycraft.web.context``) garantit que toutes les routes sont
|
|
8
|
+
enregistrées.
|
|
9
|
+
|
|
10
|
+
(c) E. Desmontils, Nantes Université, 2026
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from querycraft.web import tenancy
|
|
14
|
+
from querycraft.web.admin_routes import admin_bp
|
|
15
|
+
from querycraft.web.context import app
|
|
16
|
+
from querycraft.web.exercices_routes import exercices_bp
|
|
17
|
+
from querycraft.web.pages import pages_bp
|
|
18
|
+
from querycraft.web.sql_routes import sql_bp
|
|
19
|
+
|
|
20
|
+
app.register_blueprint(admin_bp)
|
|
21
|
+
app.register_blueprint(pages_bp)
|
|
22
|
+
app.register_blueprint(sql_bp)
|
|
23
|
+
app.register_blueprint(exercices_bp)
|
|
24
|
+
|
|
25
|
+
# Une fois toutes les routes "démo" enregistrées : les dupliquer sous /<code>.
|
|
26
|
+
tenancy.register_tenant_routes()
|
|
27
|
+
|
|
28
|
+
__all__ = ["app"]
|