Files
sisvietnamvn_01/sisvietnamvn_main/extract_styles.py
T

75 lines
2.5 KiB
Python

import re
import os
html_path = '/home/x79/sisvietnamvn_01/sisvietnamvn_main/src/main/resources/templates/dao-tao-detail.html'
css_path = '/home/x79/sisvietnamvn_01/sisvietnamvn_main/src/main/resources/static/css/custom.css'
with open(html_path, 'r', encoding='utf-8') as f:
content = f.read()
css_rules = []
class_counter = 1
def process_html(text):
global class_counter
start = 0
while True:
idx = text.find(' style="', start)
if idx == -1:
idx = text.find(" style='", start)
if idx == -1:
break
quote = text[idx + 7]
end_idx = text.find(quote, idx + 8)
if end_idx == -1:
break
style_content = text[idx+8:end_idx]
if "animation-composition" in style_content:
new_class = f"devtools-style-{class_counter}"
class_counter += 1
# Format CSS rule
styles = [s.strip() for s in style_content.split(';') if s.strip()]
css_rule = f".{new_class} {{\n"
for s in styles:
css_rule += f" {s};\n"
css_rule += "}\n"
css_rules.append(css_rule)
# Remove style attribute
text = text[:idx] + text[end_idx+1:]
# Now we need to inject new_class into the nearest preceding class="..."
# Search backwards for `class="` before `idx` (but only within the current tag, so stop at `<`)
tag_start = text.rfind('<', 0, idx)
class_idx = text.find('class="', tag_start, idx)
if class_idx != -1:
# insert new_class inside the existing class attribute
insert_pos = class_idx + 7
text = text[:insert_pos] + new_class + " " + text[insert_pos:]
start = idx # adjust start roughly
else:
# element has no class attribute, insert one where style was
text = text[:idx] + f' class="{new_class}"' + text[idx:]
start = idx
else:
start = end_idx + 1
return text
new_html = process_html(content)
if css_rules:
with open(css_path, 'a', encoding='utf-8') as f:
f.write("\n/* --- Extracted Inline Styles --- */\n")
f.write("\n".join(css_rules))
with open(html_path, 'w', encoding='utf-8') as f:
f.write(new_html)
print(f"Extracted {len(css_rules)} styles to custom.css")
else:
print("No styles found.")