89 lines
3.0 KiB
Python
89 lines
3.0 KiB
Python
import random
|
|
import re
|
|
import importlib.util
|
|
import string
|
|
from typing import List
|
|
from pydantic import BaseModel
|
|
import sympy
|
|
|
|
class GeneratorOut(BaseModel):
|
|
calcul: str
|
|
correction: str | None = None
|
|
|
|
def parseOut(calcul):
|
|
"""Fait en sorte de séparer la correction présente dans le calcul"""
|
|
regex = r"\[(.*?)\]"
|
|
calculEx = calcul['calcul'].replace('[', ' [').replace(']', '] ')
|
|
splitted = calculEx.split()
|
|
|
|
if len(list(filter(lambda e: e.startswith("[") and e.endswith(']'), splitted))) == 0:
|
|
splitted.append('[]')
|
|
|
|
inputs = []
|
|
for i in range(len(splitted)):
|
|
c = splitted[i]
|
|
match = re.findall(regex, c)
|
|
if len(match) != 0:
|
|
correction = c[1:-1]
|
|
splitted[i] = f'[{len(inputs)}]'
|
|
inputs.append(
|
|
{'index': len(inputs), 'correction': correction, 'value': ""})
|
|
|
|
calculEx = ' '.join(splitted)
|
|
return {'calcul': calculEx, 'inputs': inputs}
|
|
|
|
|
|
|
|
def parseGeneratorOut(out: List[GeneratorOut]):
|
|
return [parseOut(c) for c in out]
|
|
|
|
def getObjectKey(obj, key):
|
|
if obj[key] == None:
|
|
return None
|
|
return key if obj[key] != False else 'calcul' if obj['calcul'] != False else None
|
|
|
|
|
|
def getCorrectionKey(obj, key):
|
|
return key if (obj[key] != False and obj['correction'] == False) else 'calcul' if(obj['calcul'] != False and obj['correction'] == False) else 'correction' if obj['correction'] != False else None
|
|
|
|
|
|
def parseCorrection(calc, replacer='...'):
|
|
exp_list = re.findall(r"\[(.*?)\]", calc)
|
|
for exp in exp_list:
|
|
calc = calc.replace(f'[{exp}]', replacer)
|
|
return calc
|
|
|
|
|
|
def generate_from_data(data, quantity, key, forcedCorrection=False):
|
|
locs = {}
|
|
exec(data, {"random": random, "string": string, "sympy": sympy}, locs)
|
|
try:
|
|
main_func = locs['main']
|
|
except:
|
|
return None
|
|
main_result = main_func()
|
|
default_object = {"calcul": False, 'pdf': False, 'csv': False,
|
|
'web': False, 'correction': False} # les valeurs par défaut
|
|
# Si l'utilisateur n'a pas entré une valeur, elle est définie à False
|
|
|
|
result_object = {**default_object, **main_result}
|
|
object_key = getObjectKey(result_object, key)
|
|
correction_key = getCorrectionKey(result_object, key)
|
|
op_list = []
|
|
try:
|
|
replacer = locs["CORRECTION_REPLACER"]
|
|
except:
|
|
replacer = '...'
|
|
|
|
for i in range(quantity):
|
|
main_result = main_func()
|
|
main = {**default_object, **main_result}
|
|
op_list.append({'calcul': parseCorrection(main[
|
|
object_key], replacer) if (forcedCorrection or (key != 'web' and main['correction'] == False)) else main[object_key], "correction": main[correction_key]})
|
|
return op_list
|
|
|
|
|
|
def generate_from_path(path, quantity, key, forcedCorrection=False):
|
|
data = open(path, "r").read()
|
|
return generate_from_data(data, quantity, key, forcedCorrection)
|