scoring.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import math
  2. from rapidfuzz import fuzz
  3. import re
  4. import regex
  5. from statistics import mean
  6. CHUNK_MIN_CHARS = 25
  7. def chunk_text(text, chunk_len=500):
  8. chunks = [text[i:i+chunk_len] for i in range(0, len(text), chunk_len)]
  9. chunks = [c for c in chunks if c.strip() and len(c) > CHUNK_MIN_CHARS]
  10. return chunks
  11. def overlap_score(hypothesis_chunks, reference_chunks):
  12. if len(reference_chunks) > 0:
  13. length_modifier = len(hypothesis_chunks) / len(reference_chunks)
  14. else:
  15. length_modifier = 0
  16. search_distance = max(len(reference_chunks) // 5, 10)
  17. chunk_scores = []
  18. for i, hyp_chunk in enumerate(hypothesis_chunks):
  19. max_score = 0
  20. total_len = 0
  21. i_offset = int(i * length_modifier)
  22. chunk_range = range(max(0, i_offset-search_distance), min(len(reference_chunks), i_offset+search_distance))
  23. for j in chunk_range:
  24. ref_chunk = reference_chunks[j]
  25. score = fuzz.ratio(hyp_chunk, ref_chunk, score_cutoff=30) / 100
  26. if score > max_score:
  27. max_score = score
  28. total_len = len(ref_chunk)
  29. chunk_scores.append(max_score)
  30. return chunk_scores
  31. def score_text(hypothesis, reference):
  32. # Returns a 0-1 alignment score
  33. hypothesis_chunks = chunk_text(hypothesis)
  34. reference_chunks = chunk_text(reference)
  35. chunk_scores = overlap_score(hypothesis_chunks, reference_chunks)
  36. if len(chunk_scores) > 0:
  37. mean_score = mean(chunk_scores)
  38. return mean_score
  39. else:
  40. return 0
  41. #return mean(chunk_scores)