Diff_Text_pub / app.py
Rick-Xu315
debug
ca2a7b0
raw
history blame
2.52 kB
import gradio as gr
import difflib
from io import BytesIO
import matplotlib.pyplot as plt
import numpy as np
import gradio as gr
import difflib
def word_lcs(text1, text2):
words1 = text1.split()
words2 = text2.split()
m, n = len(words1), len(words2)
# Initialize a 2D array to store the length of word-level LCS
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Fill the dp array using bottom-up dynamic programming
for i in range(1, m + 1):
for j in range(1, n + 1):
if words1[i - 1] == words2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
# Reconstruct the word-level LCS from the dp array
i, j = m, n
word_lcs = []
while i > 0 and j > 0:
if words1[i - 1] == words2[j - 1]:
word_lcs.append(words1[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] > dp[i][j - 1]:
i -= 1
else:
j -= 1
# Reverse the word-level LCS to get the correct order
word_lcs = word_lcs[::-1]
result=[]
for word in text2.split():
if word in word_lcs:
result.append((word+" ","-"))
word_lcs.remove(word)
else:
result.append((word,"+"))
#result=[(word+" ",None) for word in word_lcs]
return result
#定义处理函数
# 定义处理函数 f
def process(text1, text2,function):
# 这里替换成你的处理逻辑,生成图片的代码
# 示例:使用Matplotlib生成一个简单的图像
if function=="naive":
d = difflib.Differ()
return [
(token[2:], token[0] if token[0] != " " else None)
for token in d.compare(text1, text2)
]
else:
return(word_lcs(text1,text2))
# 创建 Gradio 界面
iface = gr.Interface(
fn=process, # 此处的 fn 将在运行时动态设置
inputs=[
gr.Textbox(label="Origin Text",value="The quick brown fox jumped over the lazy dogs.",lines=3),
gr.Textbox(label="Edited Text",value="The fast brown fox jumps over lazy dogs.",lines=3),
gr.Radio(["naive", "Largest Common Subsequence"], label="Select Function")
],
outputs=gr.HighlightedText(
label="Diff",
combine_adjacent=True,
show_legend=True,
color_map={"+": "red", "-": "green"}),
theme=gr.themes.Base()
)
# 设置动态函数选择
# 启动 Gradio 应用
iface.launch()