Update app.py
Browse files
app.py
CHANGED
@@ -1,149 +1,158 @@
|
|
1 |
import re
|
2 |
import streamlit as st
|
3 |
from bs4 import BeautifulSoup
|
|
|
4 |
|
5 |
def parse_variable_file(variable_content):
|
6 |
"""Parses the SCSS variable content and returns a mapping of color names to their values."""
|
7 |
variables = {}
|
8 |
-
|
9 |
|
10 |
# First pass: collect direct color definitions
|
11 |
-
# Match both with and without !default, including rgba values
|
12 |
color_pattern = re.compile(r'^\s*\$([\w-]+):\s*(#[a-fA-F0-9]{3,6}|rgba?\([^)]+\))\s*(!default)?\s*;')
|
13 |
-
# Match variable references
|
14 |
reference_pattern = re.compile(r'^\s*\$([\w-]+):\s*\$([\w-]+)\s*(!default)?\s*;')
|
15 |
|
16 |
-
# Process each line
|
17 |
lines = variable_content.splitlines()
|
18 |
for line in lines:
|
19 |
-
|
20 |
-
if line.strip().startswith('//') or not line.strip():
|
21 |
continue
|
22 |
|
23 |
-
# Skip map-merge blocks
|
24 |
-
if 'map-merge' in line:
|
25 |
-
continue
|
26 |
-
|
27 |
-
# Try to match direct color values
|
28 |
color_match = color_pattern.match(line)
|
29 |
if color_match:
|
30 |
var_name = color_match.group(1)
|
31 |
color_value = color_match.group(2)
|
32 |
variables[color_value] = f"${var_name}"
|
33 |
-
# Store the variable name itself as a key for reference
|
34 |
-
variables[f"${var_name}"] = f"${var_name}"
|
35 |
continue
|
36 |
|
37 |
-
# Try to match variable references
|
38 |
ref_match = reference_pattern.match(line)
|
39 |
if ref_match:
|
40 |
-
|
41 |
referenced_var = ref_match.group(2)
|
42 |
-
|
|
|
|
|
43 |
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
|
50 |
-
return
|
51 |
|
52 |
def convert_css_to_scss(css_content, variable_mapping):
|
53 |
"""Converts CSS content to SCSS by replacing color values with variable names."""
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
|
|
58 |
|
59 |
-
# Process each line while preserving comments
|
60 |
result_lines = []
|
61 |
for line in css_content.splitlines():
|
62 |
processed_line = line
|
63 |
|
64 |
-
# Handle lines with comments
|
65 |
if '/*' in line and '*/' in line:
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
|
|
|
|
|
|
75 |
else:
|
76 |
-
|
77 |
-
|
78 |
-
if not color.startswith('$'): # Only replace actual color values
|
79 |
processed_line = processed_line.replace(color, variable)
|
80 |
|
81 |
result_lines.append(processed_line)
|
82 |
|
83 |
return '\n'.join(result_lines)
|
84 |
|
85 |
-
def extract_css_and_replace_with_variables(css_content, variables_content):
|
86 |
-
"""Replaces CSS properties with SCSS variables."""
|
87 |
-
try:
|
88 |
-
variable_mapping = parse_variable_file(variables_content)
|
89 |
-
scss_content = convert_css_to_scss(css_content, variable_mapping)
|
90 |
-
return scss_content
|
91 |
-
except Exception as e:
|
92 |
-
st.error(f"Error processing CSS to SCSS: {e}")
|
93 |
-
return None
|
94 |
-
|
95 |
def convert_html_to_twig(html_content):
|
96 |
"""Converts HTML to Twig format."""
|
97 |
try:
|
98 |
soup = BeautifulSoup(html_content, "html.parser")
|
99 |
-
|
|
|
|
|
100 |
for tag in soup.find_all():
|
101 |
-
# Replace text with Twig variables
|
102 |
if tag.string and tag.string.strip():
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
105 |
# Replace attributes with Twig variables
|
106 |
-
for attr, value in tag.attrs.items():
|
107 |
-
tag[attr] = f"{{{{ {attr}_{tag.name} }}}}"
|
108 |
-
|
109 |
-
#
|
110 |
-
twig_comments =
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
return f"{twig_comments}\n{soup.prettify()}"
|
118 |
except Exception as e:
|
119 |
st.error(f"Error converting HTML to Twig: {e}")
|
120 |
return None
|
121 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
122 |
# File uploaders
|
123 |
html_file = st.file_uploader("Upload HTML File", type=["html"], key="html_file")
|
124 |
-
css_file = st.file_uploader("Upload CSS File
|
125 |
variables_file = st.file_uploader("Upload SCSS Variables File", type=["scss"], key="variables_file")
|
126 |
|
127 |
# Handle HTML to Twig conversion
|
128 |
if html_file:
|
129 |
html_content = html_file.read().decode("utf-8")
|
130 |
twig_content = convert_html_to_twig(html_content)
|
131 |
-
|
132 |
if twig_content:
|
133 |
st.subheader("Twig Output")
|
134 |
st.code(twig_content, language="twig")
|
135 |
-
|
136 |
-
|
|
|
|
|
|
|
|
|
137 |
|
138 |
# Handle CSS to SCSS conversion
|
139 |
if css_file and variables_file:
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import re
|
2 |
import streamlit as st
|
3 |
from bs4 import BeautifulSoup
|
4 |
+
from copy import deepcopy
|
5 |
|
6 |
def parse_variable_file(variable_content):
|
7 |
"""Parses the SCSS variable content and returns a mapping of color names to their values."""
|
8 |
variables = {}
|
9 |
+
temp_references = {}
|
10 |
|
11 |
# First pass: collect direct color definitions
|
|
|
12 |
color_pattern = re.compile(r'^\s*\$([\w-]+):\s*(#[a-fA-F0-9]{3,6}|rgba?\([^)]+\))\s*(!default)?\s*;')
|
|
|
13 |
reference_pattern = re.compile(r'^\s*\$([\w-]+):\s*\$([\w-]+)\s*(!default)?\s*;')
|
14 |
|
|
|
15 |
lines = variable_content.splitlines()
|
16 |
for line in lines:
|
17 |
+
if not line.strip() or line.strip().startswith('//') or 'map-merge' in line:
|
|
|
18 |
continue
|
19 |
|
|
|
|
|
|
|
|
|
|
|
20 |
color_match = color_pattern.match(line)
|
21 |
if color_match:
|
22 |
var_name = color_match.group(1)
|
23 |
color_value = color_match.group(2)
|
24 |
variables[color_value] = f"${var_name}"
|
|
|
|
|
25 |
continue
|
26 |
|
|
|
27 |
ref_match = reference_pattern.match(line)
|
28 |
if ref_match:
|
29 |
+
referencing_var = ref_match.group(1)
|
30 |
referenced_var = ref_match.group(2)
|
31 |
+
temp_references[referencing_var] = referenced_var
|
32 |
+
|
33 |
+
final_variables = deepcopy(variables)
|
34 |
|
35 |
+
for referencing_var, referenced_var in temp_references.items():
|
36 |
+
for color, var_name in variables.items():
|
37 |
+
if var_name == f"${referenced_var}":
|
38 |
+
final_variables[color] = f"${referencing_var}"
|
39 |
+
break
|
40 |
|
41 |
+
return final_variables
|
42 |
|
43 |
def convert_css_to_scss(css_content, variable_mapping):
|
44 |
"""Converts CSS content to SCSS by replacing color values with variable names."""
|
45 |
+
replacements = sorted(
|
46 |
+
list(variable_mapping.items()),
|
47 |
+
key=lambda x: len(x[0]) if not x[0].startswith('$') else 0,
|
48 |
+
reverse=True
|
49 |
+
)
|
50 |
|
|
|
51 |
result_lines = []
|
52 |
for line in css_content.splitlines():
|
53 |
processed_line = line
|
54 |
|
|
|
55 |
if '/*' in line and '*/' in line:
|
56 |
+
comment_start = line.index('/*')
|
57 |
+
comment_end = line.index('*/') + 2
|
58 |
+
before_comment = line[:comment_start]
|
59 |
+
comment = line[comment_start:comment_end]
|
60 |
+
after_comment = line[comment_end:]
|
61 |
+
|
62 |
+
for color, variable in replacements:
|
63 |
+
if not color.startswith('$'):
|
64 |
+
before_comment = before_comment.replace(color, variable)
|
65 |
+
after_comment = after_comment.replace(color, variable)
|
66 |
+
|
67 |
+
processed_line = before_comment + comment + after_comment
|
68 |
else:
|
69 |
+
for color, variable in replacements:
|
70 |
+
if not color.startswith('$'):
|
|
|
71 |
processed_line = processed_line.replace(color, variable)
|
72 |
|
73 |
result_lines.append(processed_line)
|
74 |
|
75 |
return '\n'.join(result_lines)
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
def convert_html_to_twig(html_content):
|
78 |
"""Converts HTML to Twig format."""
|
79 |
try:
|
80 |
soup = BeautifulSoup(html_content, "html.parser")
|
81 |
+
|
82 |
+
# First pass: collect all tags that will need variables
|
83 |
+
tags_with_content = set()
|
84 |
for tag in soup.find_all():
|
|
|
85 |
if tag.string and tag.string.strip():
|
86 |
+
tags_with_content.add(tag.name)
|
87 |
+
|
88 |
+
# Second pass: replace content and attributes
|
89 |
+
for tag in soup.find_all():
|
90 |
+
# Replace text content with Twig variables
|
91 |
+
if tag.string and tag.string.strip():
|
92 |
+
tag.string = f"{{{{ {tag.name}_content }}}}"
|
93 |
+
|
94 |
# Replace attributes with Twig variables
|
95 |
+
for attr, value in list(tag.attrs.items()): # Use list to avoid runtime modification issues
|
96 |
+
tag[attr] = f"{{{{ {attr}_{tag.name} }}}}"
|
97 |
+
|
98 |
+
# Generate comments for Twig variables
|
99 |
+
twig_comments = []
|
100 |
+
for tag_name in sorted(tags_with_content):
|
101 |
+
twig_comments.append(
|
102 |
+
f"<!-- `{{{{ {tag_name}_content }}}}`: Content for <{tag_name}> -->"
|
103 |
+
)
|
104 |
+
|
105 |
+
return f"{chr(10).join(twig_comments)}\n{soup.prettify()}"
|
|
|
106 |
except Exception as e:
|
107 |
st.error(f"Error converting HTML to Twig: {e}")
|
108 |
return None
|
109 |
|
110 |
+
def extract_css_and_replace_with_variables(css_content, variables_content):
|
111 |
+
"""Replaces CSS properties with SCSS variables."""
|
112 |
+
try:
|
113 |
+
variable_mapping = parse_variable_file(variables_content)
|
114 |
+
return convert_css_to_scss(css_content, variable_mapping)
|
115 |
+
except Exception as e:
|
116 |
+
st.error(f"Error processing CSS to SCSS: {e}")
|
117 |
+
print(f"Debug - Error details: {str(e)}")
|
118 |
+
return None
|
119 |
+
|
120 |
+
# Streamlit app
|
121 |
+
st.title("HTML to Twig and SCSS Converter")
|
122 |
+
|
123 |
# File uploaders
|
124 |
html_file = st.file_uploader("Upload HTML File", type=["html"], key="html_file")
|
125 |
+
css_file = st.file_uploader("Upload CSS File", type=["css"], key="css_file")
|
126 |
variables_file = st.file_uploader("Upload SCSS Variables File", type=["scss"], key="variables_file")
|
127 |
|
128 |
# Handle HTML to Twig conversion
|
129 |
if html_file:
|
130 |
html_content = html_file.read().decode("utf-8")
|
131 |
twig_content = convert_html_to_twig(html_content)
|
|
|
132 |
if twig_content:
|
133 |
st.subheader("Twig Output")
|
134 |
st.code(twig_content, language="twig")
|
135 |
+
st.download_button(
|
136 |
+
"Download Twig File",
|
137 |
+
data=twig_content,
|
138 |
+
file_name="output.twig",
|
139 |
+
mime="text/plain"
|
140 |
+
)
|
141 |
|
142 |
# Handle CSS to SCSS conversion
|
143 |
if css_file and variables_file:
|
144 |
+
try:
|
145 |
+
css_content = css_file.read().decode("utf-8")
|
146 |
+
variables_content = variables_file.read().decode("utf-8")
|
147 |
+
scss_content = extract_css_and_replace_with_variables(css_content, variables_content)
|
148 |
+
if scss_content:
|
149 |
+
st.subheader("SCSS Output")
|
150 |
+
st.code(scss_content, language="scss")
|
151 |
+
st.download_button(
|
152 |
+
"Download SCSS File",
|
153 |
+
data=scss_content,
|
154 |
+
file_name="converted.scss",
|
155 |
+
mime="text/plain"
|
156 |
+
)
|
157 |
+
except Exception as e:
|
158 |
+
st.error(f"An error occurred: {str(e)}")
|