Skip to content

Commit af85ee2

Browse files
committed
Corrections de typage et de logique
1 parent 52433f7 commit af85ee2

1 file changed

Lines changed: 67 additions & 66 deletions

File tree

src/utils.py

Lines changed: 67 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,36 @@
11
import math
22
import string
33
import sys
4-
import os
4+
from typing import Any, Dict, List, TypedDict
55

6-
def calculer_entropie(bytes) -> float:
7-
'''
8-
Calcul l'entropie (le désordre dans une suite de données) afin de déterminer le degré d'improbabilité d'une chaine de données.
6+
class StatsDict(TypedDict):
7+
imprimable: float
8+
nombre_mots: int
9+
p_mots_valide: float
10+
non_mots: List[str]
11+
ponctuation_valide: int
912

10-
Args:
11-
bytes(bytes): La donnée brute contenue dans le fichier crypté.
13+
def calculer_entropie(bytes: bytes) -> float:
14+
'''
15+
Calcul l'entropie (le désordre dans une suite de données) afin de déterminer le degré d'improbabilité d'une chaine de données.
16+
17+
Args:
18+
bytes(bytes): La donnée brute contenue dans le fichier crypté.
1219
13-
Returns:
14-
float: l'entropie calculée.
20+
Returns:
21+
float: l'entropie calculée.
1522
'''
16-
entropie = 0
17-
proba_byte = 0
18-
for specifique_byte in bytes:
19-
i = 1
20-
for chaque_byte in bytes:
21-
if(chaque_byte == specifique_byte):
22-
i += 1
23+
entropie = 0
24+
proba_byte = 0
25+
for specifique_byte in bytes:
26+
i = 1
27+
for chaque_byte in bytes:
28+
if(chaque_byte == specifique_byte):
29+
i += 1
2330

24-
proba_byte = 1 / i
25-
entropie += (proba_byte) * math.log(1/proba_byte, 8)
26-
return entropie
31+
proba_byte = 1 / i
32+
entropie += (proba_byte) * math.log(1/proba_byte, 8)
33+
return entropie
2734

2835

2936

@@ -52,11 +59,10 @@ def est_dechiffre(texte:str) -> bool:
5259
pourcent += 20
5360

5461
return True if pourcent > 70 else False
55-
56-
57-
5862

59-
def verifier_texte_dechiffre(texte: str) -> dict[int, int, int, list, int]:
63+
64+
65+
def verifier_texte_dechiffre(texte: str) -> Dict[str, Any]:
6066
"""
6167
Verifie que le dechiffrement d'un message a bien été effectué sur la base de certains critères.
6268
@@ -82,51 +88,51 @@ def verifier_texte_dechiffre(texte: str) -> dict[int, int, int, list, int]:
8288
'ponctuation_valide':0
8389
}
8490

91+
if not texte:
92+
return stats
93+
8594
#Verifier le pourcentage de caractères imprimables.
86-
87-
for lettre in texte:
88-
if lettre.isprintable():
89-
stats['imprimable']+= 100/len(texte)
90-
95+
stats['imprimable'] = int(sum(1 for char in texte if char.isprintable()) / len(texte) * 100)
96+
9197
# Traitement du texte brut pour obtenir une séquence distincte de pseudo-mot à cette étape séparé par des espaces
9298

9399
tab='./:!\\}{_%*$£&#;,~"()[]=§|`^@?'
94100
copy=texte
95101
for lettre in tab:
96102
copy=copy.replace(lettre, ' ')
97-
copy=copy.strip().split(' ')
98-
stats['nombre_mots']=len(copy)
103+
mots = [mot for mot in copy.strip().split(' ') if mot]
104+
stats['nombre_mots']=len(mots)
99105

100106
# Verifier que le chaque mot du texte est un mot anglais/francais
101107

102108
try:
103-
for mot in copy:
109+
mots_valides = 0
110+
for mot in mots:
104111
trouve=False
105-
if mot == '': continue
112+
if not mot: continue
113+
114+
first_char = mot[0].lower()
115+
106116
for syl in ['Fr', 'En']:
107-
chemin=f"{os.curdir}.\\CryptoForensic-Python\\dico{syl}\\{mot[0]}.txt"
108-
exit
109-
with open(chemin, 'r') as f:
110-
ligne=f.readline()
111-
ligne=ligne.removesuffix('\n')
112-
113-
while not trouve and ligne != "":
114-
115-
if ligne == mot:
116-
stats['p_mots_valide']+=100/len(copy)
117-
print('\n', stats['p_mots_valide'], mot,)
118-
trouve=True
119-
break
120-
121-
ligne=f.readline()
122-
ligne=ligne.removesuffix('\n')
123-
124-
f.close()
117+
chemin=f"dico{syl}/{first_char}.txt"
118+
try:
119+
with open(chemin, 'r', encoding='latin-1') as f:
120+
for ligne in f:
121+
if ligne.strip() == mot:
122+
mots_valides += 1
123+
trouve=True
124+
break
125+
except FileNotFoundError:
126+
continue
125127

126128
if trouve : break
127129

128130
if not trouve :
129131
stats['non_mots'].append(mot)
132+
if mots:
133+
stats['p_mots_valide'] = round((mots_valides / len(mots)) * 100, 2)
134+
else:
135+
stats['p_mots_valide'] = 0.0
130136

131137
except Exception:
132138
tb=sys.exception().__traceback__
@@ -136,24 +142,17 @@ def verifier_texte_dechiffre(texte: str) -> dict[int, int, int, list, int]:
136142
#Verifier la structure de ponctuation.
137143

138144
points='.?!;,'
139-
nbr_ponct=0
140-
for point in points :
141-
nbr_ponct+=texte.count(point)
142-
for point in points :
143-
partition= texte.partition(point)
144-
if partition[2].startswith(' ') :
145-
if (point in '?!.' and partition[2].lstrip()[0].isupper()) or (point in ';,' and partition[2].lstrip()[0].islower()):
146-
stats['ponctuation_valide']+=100/nbr_ponct
147-
148-
for key in stats:
149-
print(key)
150-
if isinstance(stats[key], float):
151-
stats[key]=round(stats[key], 2)
145+
count = 0
146+
for i, char in enumerate(texte):
147+
if char in points:
148+
if (i == len(texte) - 1) or (texte[i+1] == ' '):
149+
count += 1
150+
stats['ponctuation_valide'] = count
152151

153152
return stats
154153

155154

156-
def rangerDico():
155+
def rangerDico() -> None:
157156
"""
158157
Fonction utilitaire de rangement du dictionnaire anglais téléchargé
159158
Pour effectuer des tests
@@ -162,11 +161,13 @@ def rangerDico():
162161
compte = 0
163162
# Ouverture du grand dictionnaire.
164163
try :
165-
with open(f"{os.path.abspath(os.curdir)}\\words_alpha.txt",'r') as f:
164+
# Utilisation de Path pour un chemin portable
165+
words_path = Path.cwd() / "words_alpha.txt"
166+
with open(words_path,'r') as f:
166167
while i<26:
167168
# Définition du chemin vers le fichier de chaque mot en fonction de l'alphabet.
168-
chemin=f"{os.curdir}\\dicoEn\\{string.ascii_lowercase[i]}.txt"
169-
with open(chemin, 'a') as fichier:
169+
dico_path = Path.cwd() / "dicoEn" / f"{string.ascii_lowercase[i]}.txt"
170+
with open(dico_path, 'a') as fichier:
170171
#Ecriture dans le fichier.
171172
fichier.write(string.ascii_lowercase[i]+'\n')
172173
while 1 :

0 commit comments

Comments
 (0)