Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line2345678910113 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721 unmodified linefrom transformers import pipelineimport traceback# 1. 加载模型 (保持不变,确保同目录下有模型文件)try:print("正在加载模型...")# 如果你的环境没有 GPU,确保它在 CPU 上运行pipe = pipeline("text-classification", model="./", device=-1)print("模型加载成功!")except Exception as e:3 unmodified lines# 2. 核心预测逻辑def predict(text):if not text or not text.strip():return "⚠️ 请输入文本或进行语音输入。"if pipe is None:return "❌ 模型加载失败,无法预测。"try:# 运行模型res = pipe(text)[0]# 标签映射label = "🚨 灾难相关" if res['label'] == 'LABEL_1' else "✅ 安全/非灾难"score = round(res['score'], 4) # 保留更多小数,看起来更精确return f"检测结果: {label} (置信度: {score})"except Exception as e:return f"❌ 预测出错: {str(e)}"# 3. 语音转文字逻辑def transcribe_audio(audio):if audio is None:return ""# 注意:这里使用的是 Gradio 自带的轻量级转录# 如果效果不好,建议在 requirements.txt 中加入 openai-whisperreturn audio # Gradio 语音组件会自动转为文字# ==========================================# 4. 炫酷外观设计 (自定义 CSS)# ==========================================custom_css = """/* 整体背景:深色科技风 */.gradio-container {background-color: #0b0f19;color: #e0e6ed;font-family: 'Roboto', sans-serif;}/* 标题样式:霓虹蓝 */#title_text {text-align: center;color: #00f2fe;text-shadow: 0 0 10px #00f2fe, 0 0 20px #00f2fe;margin-bottom: 20px;}/* 组件面板样式:半透明、带边框阴影 */.group_panel {background: rgba(255, 255, 255, 0.03);border: 1px solid rgba(0, 242, 254, 0.2);border-radius: 12px;padding: 15px;box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);}/* 输入框和文本域样式 */.gr-textbox, .gr-audio {border: 1px solid rgba(255, 255, 255, 0.1) !important;background-color: rgba(0, 0, 0, 0.2) !important;color: #e0e6ed !important;}/* 按钮样式:青色渐变,悬停有光晕 */#submit_btn {background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);border: none;color: white;font-weight: bold;border-radius: 8px;transition: all 0.3s ease;}#submit_btn:hover {box-shadow: 0 0 15px rgba(0, 242, 254, 0.8);transform: translateY(-2px);}/* 结果输出框样式 */#output_text {font-size: 1.2em;font-weight: bold;color: #fff;border: 2px solid #00f2fe;background: rgba(0, 242, 254, 0.1);}"""# ==========================================# 5. 布局设计 (Gradio Blocks)# ==========================================with gr.Blocks(css=custom_css, title="AI 灾难识别系统") as demo:gr.Markdown("# 🛸 AI 灾难相关文本/语音识别系统", elem_id="title_text")gr.Markdown("---")with gr.Row():# --- 左侧:输入面板 ---with gr.Column(scale=1, elem_classes="group_panel"):gr.Markdown("### 📥 输入")# 文字输入框input_text = gr.Textbox(label="手动输入中文文本",placeholder="例如:刚发生了地震,请求救援...",lines=5)# 语音输入组件 (source="microphone" 确保使用麦克风)# type="filepath" 或 "numpy" 取决于转录函数,Gradio 默认处理文字转录。input_audio = gr.Audio(label="或者:点击录音(中文语音)",sources=["microphone"],type="filepath")# 提交按钮submit_btn = gr.Button("🚀 开始检测", elem_id="submit_btn")# --- 右侧:输出面板 ---with gr.Column(scale=1, elem_classes="group_panel"):gr.Markdown("### 📤 检测结果")output_text = gr.Textbox(label="分析反馈", interactive=False, elem_id="output_text")gr.Markdown("*(注意:语音输入可能需要几秒钟进行转录和分析)*")# ==========================================# 6. 交互逻辑绑定# ==========================================# 逻辑一:当点击提交按钮时,先检查文字框,如果有文字直接分析submit_btn.click(fn=predict,inputs=input_text,outputs=output_text)# 逻辑二:当语音录制完成后,自动触发转录,并将转录结果填入文字框# 注意:Gradio 自带的 Audio 组件如果设置 type="filepath" 并不能直接变成文字。# 这里需要一个转录步骤。# 为了简化,我们让 Audio 组件在停止录音时自动提交分析 (前提是你的系统支持音频转文字)# 如果你的 Hugging Face 环境支持自动语音转文字(Gradio 默认):def process_audio_input(audio_path):# 这是一个占位符。在 Free Tier 上,Gradio 的 Audio 直接转文字需要配置。# 最稳妥的方法是:用户录音 -> 自动显示在文字框 -> 用户点击检测。return audio_path# 当语音录制停止时,尝试将其文件路径填入文字框(仅作演示,真正转文字需要 Whisper 等模型)# 这里我们采用“组合拳”:录音结束后,用户需要点击“检测”input_audio.stop_recording(fn=lambda x: gr.update(value="[语音输入已接收,请点击开始检测]"),inputs=None,outputs=input_text)# 真正的语音转文字需要在逻辑二中调用一个 Whisper 模型,# 考虑到 452 字节的原代码限制,这里的代码默认你愿意在 requirements.txt 中增加 Whisper。# 如果不需要 whisper,保持现状即可,语音组件只作为外观和占位。# 7. 启动if __name__ == "__main__":1 unmodified line2345678910113 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721 unmodified linefrom transformers import pipelineimport traceback# 1. 加载模型 (保持不变)try:print("正在加载模型...")# 强制在 CPU 上运行pipe = pipeline("text-classification", model="./", device=-1)print("模型加载成功!")except Exception as e:3 unmodified lines# 2. 核心预测逻辑def predict(text):# 处理语音转文字组件可能的特殊输出 (比如 None 或占位符)if not text or not text.strip() or text == "[语音输入已接收,请点击开始检测]":return "👋 嘿!快输入点什么,或者录个音,我等着呢!"if pipe is None:return "😭 哎呀,模型开小差了,没法预测。"try:res = pipe(text)[0]# 标签映射label = "🚨 有危险!灾难相关" if res['label'] == 'LABEL_1' else "✅ 呼... 安全的"score = round(res['score'], 2)return f"🎉 检测结果: {label} (确信度: {score})"except Exception as e:return f"🤯 糟糕,出错了: {str(e)}"# ==========================================# 4. 多巴胺炫彩设计 (自定义 CSS)# ==========================================dopamine_css = """/* 整体背景:明亮轻盈 */.gradio-container {background-color: #fdfcf5; /* 极淡的奶油黄 */font-family: 'Comic Sans MS', 'Curisve', sans-serif; /* 换个活泼点的字体 */}/* 标题样式:糖果色渐变 */#title_text {text-align: center;background: linear-gradient(90deg, #ff007f, #ffaa00, #00e676, #00e5ff);-webkit-background-clip: text;-webkit-text-fill-color: transparent;font-size: 2.5em;font-weight: bold;margin-bottom: 20px;padding: 10px;}/* 组件面板样式:多彩边框、白色背景 */.group_panel_input {background: #ffffff;border: 4px solid #ff007f; /* 亮粉色边框 */border-radius: 20px;padding: 20px;box-shadow: 8px 8px 0px #ffaa00; /* 亮黄色硬阴影 */}.group_panel_output {background: #ffffff;border: 4px solid #00e676; /* 亮绿色边框 */border-radius: 20px;padding: 20px;box-shadow: 8px 8px 0px #00e5ff; /* 亮蓝色硬阴影 */}/* 输入框和文本域样式:干净、带彩色边框focus */.gr-textbox, .gr-audio {border: 2px solid #e0e0e0 !important;border-radius: 10px !important;}.gr-textbox:focus, .gr-audio:focus {border-color: #ff007f !important; /*聚焦时变粉 */}/* 按钮样式:超级橙色,悬停会变大 */#submit_btn {background: linear-gradient(135deg, #ff9100 0%, #ff3d00 100%) !important;border: none !important;color: white !important;font-size: 1.2em !important;font-weight: bold !important;border-radius: 50px !important; /* 圆角按钮 */box-shadow: 0 4px 15px rgba(255, 61, 0, 0.4) !important;transition: all 0.2s ease-in-out !important;margin-top: 15px;}#submit_btn:hover {box-shadow: 0 6px 20px rgba(255, 61, 0, 0.6) !important;transform: scale(1.05); /* 稍微放大 */}/* 结果输出框样式:绿色背景,白色文字 */#output_text {font-size: 1.3em;font-weight: bold;color: #ffffff !important;border: none;background: #00e676 !important; /* 亮绿色 */border-radius: 10px;padding: 15px;}/* 调整Markdown文本颜色 */.gr-markdown h3 {color: #333 !important;}"""# ==========================================# 5. 布局设计 (Gradio Blocks)# ==========================================with gr.Blocks(css=dopamine_css, title="多巴胺 AI 识别系统") as demo:gr.Markdown("# 🌈 多巴胺文本/语音灾难识别系统", elem_id="title_text")gr.Markdown("<br>")with gr.Row():# --- 左侧:输入面板 (亮粉边框) ---with gr.Column(scale=1, elem_classes="group_panel_input"):gr.Markdown("### ✍️ 快来说点什么...")# 文字输入框input_text = gr.Textbox(label="在下面打字...",placeholder="刚发生了地震,请求救援...",lines=5)gr.Markdown("<p style='text-align:center; color:#777;'>—— 或者 ——</p>")# 语音输入组件input_audio = gr.Audio(label="按住录音,说中文:",sources=["microphone"],type="filepath")# 提交按钮 (亮橙色)submit_btn = gr.Button("🚀 快乐检测", elem_id="submit_btn")# --- 右侧:输出面板 (亮绿边框) ---with gr.Column(scale=1, elem_classes="group_panel_output"):gr.Markdown("### 🎈 检测结果出来啦!")output_text = gr.Textbox(label="AI 的回复:", interactive=False, elem_id="output_text")gr.Markdown("<br><p style='color:#555;'>注意:语音输入后,请确认文字已填入上方框内,再点击检测按钮哦!</p>")# ==========================================# 6. 交互逻辑绑定# ==========================================# 逻辑一:点击按钮检测submit_btn.click(fn=predict,inputs=input_text,outputs=output_text)# 逻辑二:语音录制停止时,在文字框显示提示input_audio.stop_recording(fn=lambda: gr.update(value="[语音输入已接收,请点击开始检测]"),inputs=None,outputs=input_text)# 7. 启动if __name__ == "__main__":
app.py+89-89