Spaces:
Sleeping
Sleeping
import streamlit as st | |
from diff_match_patch import diff_match_patch | |
import re | |
def main(): | |
st.set_page_config(page_title="Text Comparison Tool", layout="wide") | |
st.title("Text Comparison Tool") | |
# Initialize session state | |
if 'old_text' not in st.session_state: | |
st.session_state.old_text = "" | |
if 'new_text' not in st.session_state: | |
st.session_state.new_text = "" | |
# Create two columns for text areas | |
col1, col2 = st.columns(2) | |
with col1: | |
st.session_state.old_text = st.text_area( | |
"Old Text:", | |
height=300, | |
value=st.session_state.old_text, | |
placeholder="Enter original text..." | |
) | |
with col2: | |
# Display diffs directly in the New Text area | |
new_text_display = st.empty() | |
# Show either editable text area or diff result | |
if 'show_diff' not in st.session_state or not st.session_state.show_diff: | |
st.session_state.new_text = new_text_display.text_area( | |
"New Text:", | |
height=300, | |
value=st.session_state.new_text, | |
placeholder="Enter modified text...", | |
key="new_text_editable" | |
) | |
else: | |
new_text_display.markdown( | |
st.session_state.diff_html, | |
unsafe_allow_html=True | |
) | |
# Button controls | |
col_compare, col_clear, col_copy = st.columns([1, 1, 1]) | |
with col_compare: | |
if st.button("Compare"): | |
dmp = diff_match_patch() | |
diffs = dmp.diff_main(st.session_state.old_text, st.session_state.new_text) | |
dmp.diff_cleanupSemantic(diffs) | |
html = [] | |
for op, text in diffs: | |
text = text.replace("\n", "<br>") | |
if op == 1: # Insertion | |
html.append(f'<span style="background-color: #c8e6c9; border-radius: 4px; padding: 2px 4px;">{text}</span>') | |
elif op == -1: # Deletion | |
html.append(f'<span style="background-color: #ffcdd2; text-decoration: line-through; border-radius: 4px; padding: 2px 4px;">{text}</span>') | |
else: | |
html.append(text) | |
st.session_state.diff_html = "".join(html) | |
st.session_state.show_diff = True | |
st.rerun() | |
with col_clear: | |
if st.button("Clear"): | |
st.session_state.old_text = "" | |
st.session_state.new_text = "" | |
st.session_state.show_diff = False | |
st.rerun() | |
# Copy functionality | |
with col_copy: | |
if st.button("Copy Result"): | |
if 'diff_html' in st.session_state: | |
clean_text = re.sub(r'<br>', '\n', st.session_state.diff_html) | |
clean_text = re.sub(r'<[^>]+>', '', clean_text) | |
try: | |
import pyperclip | |
pyperclip.copy(clean_text) | |
st.success("Result copied to clipboard!") | |
except: | |
st.error("Clipboard access requires extra permissions. Please copy manually:") | |
st.code(clean_text) | |
else: | |
st.warning("No comparison result to copy") | |
if __name__ == "__main__": | |
main() |