90 lines
2.9 KiB
Python
90 lines
2.9 KiB
Python
import math
|
|
import re
|
|
import unicodedata
|
|
from difflib import SequenceMatcher
|
|
|
|
import numpy as np
|
|
|
|
_reader = None
|
|
|
|
|
|
def norm(text):
|
|
s = unicodedata.normalize("NFKD", text.lower())
|
|
return "".join(c for c in s if not unicodedata.combining(c))
|
|
|
|
|
|
def tokens(text):
|
|
return re.findall(r"[a-z0-9]+", norm(text))
|
|
|
|
|
|
def name_tokens(name):
|
|
"""Mots d'un nom de produit (ex. 'Aroma Gold' -> ['aroma', 'gold'])."""
|
|
return [t for t in tokens(name) if len(t) >= 3]
|
|
|
|
|
|
def fuzzy_in(word, toks):
|
|
"""Le mot est-il lu dans le texte (avec tolérance aux petites erreurs de lecture) ?"""
|
|
for t in toks:
|
|
if t == word:
|
|
return True
|
|
if len(word) >= 4 and len(t) >= 4 and abs(len(t) - len(word)) <= 2 \
|
|
and SequenceMatcher(None, word, t).ratio() >= 0.75:
|
|
return True
|
|
return False
|
|
|
|
|
|
def text_scores(toks, sigs, df, n_products):
|
|
"""Score texte (0 à 1) de chaque produit : part de sa signature retrouvée dans le texte lu.
|
|
Un mot rare (porté par peu de produits) pèse plus qu'un mot courant."""
|
|
out = {}
|
|
for sku, sig in sigs.items():
|
|
num = den = 0.0
|
|
for w, f in sig.items():
|
|
idf = math.log((n_products + 1) / (df.get(w, 1) + 0.5))
|
|
den += idf * f
|
|
if fuzzy_in(w, toks):
|
|
num += idf * f
|
|
out[sku] = num / den if den > 0 else 0.0
|
|
return out
|
|
|
|
|
|
def read_text(pil_image, min_conf=0.35):
|
|
"""Lit le texte d'un recadrage. Retourne [(texte, confiance, hauteur)], le plus grand texte d'abord."""
|
|
global _reader
|
|
if _reader is None:
|
|
import easyocr
|
|
_reader = easyocr.Reader(["fr", "en"], gpu=False, verbose=False)
|
|
im = pil_image.convert("RGB")
|
|
if max(im.size) < 300:
|
|
im = im.resize((im.width * 2, im.height * 2))
|
|
out = []
|
|
for box, txt, conf in _reader.readtext(np.array(im)):
|
|
if conf >= min_conf and txt.strip():
|
|
ys = [p[1] for p in box]
|
|
out.append((txt.strip(), float(conf), float(max(ys) - min(ys))))
|
|
out.sort(key=lambda line: -line[2])
|
|
return out
|
|
|
|
|
|
def full_text(lines):
|
|
return " ".join(t for t, _, _ in lines)
|
|
|
|
|
|
def letters_count(lines):
|
|
return sum(len(t) for t in tokens(full_text(lines)) if t.isalpha())
|
|
|
|
|
|
def strong_words(lines, n_lines=3, min_conf=0.5, min_len=4):
|
|
"""Mots lisibles des plus grandes lignes de texte (là où se trouve en général la marque)."""
|
|
words = set()
|
|
for txt, conf, _ in lines[:n_lines]:
|
|
if conf >= min_conf:
|
|
words.update(t for t in tokens(txt) if t.isalpha() and len(t) >= min_len)
|
|
return words
|
|
|
|
|
|
def guess_name(lines, n=2):
|
|
"""Propose un nom de produit à partir des lignes de texte les plus grandes."""
|
|
picks = [t for t, c, _ in lines if c >= 0.5 and sum(ch.isalpha() for ch in t) >= 3][:n]
|
|
return " ".join(p.title() if p.isupper() else p for p in picks)
|