Spaces:
Sleeping
Sleeping
File size: 2,012 Bytes
6dc5d80 | 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 54 55 56 | import gradio as gr
from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM
# 加载预训练模型(用于文本改写,适配不同语境)
model_name = "t5-small" # 轻量模型,加载快,适合演示
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
# 创建文本生成管道
context_pipeline = pipeline(
"text2text-generation",
model=model,
tokenizer=tokenizer,
max_length=128,
truncation=True
)
# 核心语境适配函数
def adapt_context(input_text, target_context):
# 根据选择的语境生成改写指令
prompts = {
"学术": f"paraphrase the text into academic style: {input_text}",
"口语": f"paraphrase the text into conversational style: {input_text}",
"职场": f"paraphrase the text into professional workplace style: {input_text}",
"营销": f"paraphrase the text into marketing promotional style: {input_text}"
}
# 调用模型生成结果
result = context_pipeline(prompts[target_context])
return result[0]["generated_text"]
# 构建Gradio界面(模仿示例网页的简洁风格)
with gr.Blocks(theme="huggingface") as demo:
gr.Markdown("# 文本语境适配工具")
gr.Markdown("输入文本并选择目标语境,即可生成适配该场景的文本内容")
# 输入组件
input_text = gr.Textbox(label="输入待适配文本", lines=5, placeholder="请在这里输入需要改写的文本...")
target_context = gr.Dropdown(
choices=["学术", "口语", "职场", "营销"],
label="选择目标语境",
value="口语" # 默认选项
)
# 输出组件
output_text = gr.Textbox(label="语境适配结果", lines=5)
# 按钮与交互逻辑
gr.Button("开始适配").click(
fn=adapt_context,
inputs=[input_text, target_context],
outputs=output_text
)
# 启动应用
if __name__ == "__main__":
demo.launch() |