Spaces:
Running
Running
Update app.py
Browse files
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
|
| 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(
|
| 23 |
-
doc = Document(
|
| 24 |
|
| 25 |
for para in doc.paragraphs:
|
| 26 |
-
|
| 27 |
-
for i, run in enumerate(para.runs):
|
| 28 |
if is_red_color(run):
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
for
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
|