Shami96 commited on
Commit
1804090
·
verified ·
1 Parent(s): 9e5331a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +15 -13
app.py CHANGED
@@ -7,6 +7,7 @@ from docx.shared import RGBColor
7
 
8
  from docx import Document
9
  from docx.shared import RGBColor
 
10
 
11
  def is_red_color(run):
12
  color = run.font.color
@@ -14,24 +15,25 @@ def is_red_color(run):
14
  return False
15
  if color.rgb:
16
  r, g, b = color.rgb[0], color.rgb[1], color.rgb[2]
17
- return r >= 200 and g <= 80 and b <= 80 # flexible red check
18
- if color.theme_color: # fallback if theme_color is set instead of RGB
19
- return str(color.theme_color).lower().endswith("accent2") or str(color.theme_color).lower().endswith("red")
20
  return False
 
21
 
22
- def replace_red_text_with_data(word_path, data_dict):
23
- doc = Document(word_path)
24
 
25
  for para in doc.paragraphs:
26
- full_text = para.text
27
- for i, run in enumerate(para.runs):
28
  if is_red_color(run):
29
- # Search for the key (label) before this red text
30
- preceding_text = ''.join(r.text for r in para.runs[:i]).lower()
31
- for key in data_dict:
32
- if key.lower() in preceding_text:
33
- run.text = data_dict[key]
34
- break
 
 
 
35
 
36
  return doc
37
 
 
7
 
8
  from docx import Document
9
  from docx.shared import RGBColor
10
+ from difflib import get_close_matches
11
 
12
  def is_red_color(run):
13
  color = run.font.color
 
15
  return False
16
  if color.rgb:
17
  r, g, b = color.rgb[0], color.rgb[1], color.rgb[2]
18
+ return r > 180 and g < 100 and b < 100 # any strong red tint
 
 
19
  return False
20
+
21
 
22
+ def replace_red_text_with_data(doc_path, data_dict):
23
+ doc = Document(doc_path)
24
 
25
  for para in doc.paragraphs:
26
+ for run in para.runs:
 
27
  if is_red_color(run):
28
+ red_text = run.text.strip()
29
+ # Try fuzzy match
30
+ key_match = get_close_matches(red_text.lower(), [k.lower() for k in data_dict.keys()], n=1, cutoff=0.6)
31
+ if key_match:
32
+ # Find original key with matching text
33
+ for key in data_dict:
34
+ if key.lower() == key_match[0]:
35
+ run.text = data_dict[key]
36
+ break
37
 
38
  return doc
39