File size: 1,997 Bytes
bfedf71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import gradio as gr
from difflib import Differ

def diff_texts(text1, text2):
    d = Differ()
    # 使用 splitlines(keepends=True) 可以保留换行符,使 diff 更自然
    # 但 HighlightedText 通常基于 token/word,这里我们按单词分割来做细粒度对比
    # 如果需要按行对比,可以调整逻辑
    
    # 这里演示按单词/字符流的对比,效果类似 Code Diff
    return [
        (token[2:], token[0] if token[0] != " " else None)
        for token in d.compare(text1.splitlines(keepends=True), text2.splitlines(keepends=True))
    ]

def diff_texts_word_level(text1, text2):
    d = Differ()
    # 按单词分割,更适合文章类文本
    diff = d.compare(text1.split(), text2.split())
    result = []
    for token in diff:
        code = token[0]
        word = token[2:] + " " # 补回空格
        if code == " ":
            result.append((word, None))
        elif code == "-":
            result.append((word, "-")) # 删除
        elif code == "+":
            result.append((word, "+")) # 新增
    return result

def create_ui():
    with gr.Row():
        with gr.Column():
            t1 = gr.Textbox(label="原始文本 (Original)", lines=15, placeholder="输入旧版本文本...")
        with gr.Column():
            t2 = gr.Textbox(label="新文本 (New)", lines=15, placeholder="输入新版本文本...")
    
    with gr.Row():
        btn = gr.Button("🔍 对比差异", variant="primary")
    
    # HighlightedText 组件非常适合展示 Diff
    # color_map 定义了不同标记的颜色:+ 为绿色(新增),- 为红色(删除)
    diff_output = gr.HighlightedText(
        label="差异视图 (Diff View)",
        combine_adjacent=True,
        show_legend=True,
        color_map={"+": "green", "-": "red"}
    )
    
    # 这里使用 word level diff,视觉效果更好
    btn.click(diff_texts_word_level, inputs=[t1, t2], outputs=[diff_output])