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()