Spaces:
Runtime error
Runtime error
import os | |
import gradio as gr | |
import easyocr | |
from dotenv import load_dotenv | |
from openai import OpenAI | |
from PIL import Image | |
import numpy as np | |
# 加载环境变量 | |
load_dotenv() | |
# 初始化 OpenAI 客户端 | |
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY')) | |
# 初始化 EasyOCR | |
reader = easyocr.Reader(['ch_sim', 'en']) | |
def extract_text_from_image(image): | |
"""从图片中提取文字""" | |
if isinstance(image, str): | |
image_path = image | |
else: | |
# 将 numpy array 转换为 PIL Image | |
if isinstance(image, np.ndarray): | |
image = Image.fromarray(image) | |
# 保存临时文件 | |
image_path = "temp_image.png" | |
image.save(image_path) | |
# 使用 EasyOCR 识别文字 | |
result = reader.readtext(image_path) | |
# 如果是临时文件,删除它 | |
if image_path == "temp_image.png": | |
os.remove(image_path) | |
# 提取文字内容 | |
text = ' '.join([item[1] for item in result]) | |
return text | |
def analyze_slide(text): | |
"""使用 GPT-4 分析幻灯片内容""" | |
prompt = f"""请分析以下幻灯片内容,并提供详细的讲解: | |
{text} | |
请从以下几个方面进行分析: | |
1. 主要内容概述 | |
2. 重点概念解释 | |
3. 与其他知识的联系 | |
4. 实际应用场景 | |
请用中文回答。""" | |
response = client.chat.completions.create( | |
model="gpt-4", | |
messages=[{"role": "user", "content": prompt}] | |
) | |
return response.choices[0].message.content | |
def chat_with_assistant(message, history): | |
"""与 AI 助手对话""" | |
messages = [ | |
{"role": "system", "content": "你是一位专业的课程助教,负责帮助学生理解课程内容。请用中文回答问题。"} | |
] | |
# 添加历史对话 | |
for human, assistant in history: | |
messages.append({"role": "user", "content": human}) | |
messages.append({"role": "assistant", "content": assistant}) | |
# 添加当前问题 | |
messages.append({"role": "user", "content": message}) | |
response = client.chat.completions.create( | |
model="gpt-4", | |
messages=messages | |
) | |
return response.choices[0].message.content | |
# 创建 Gradio 界面 | |
with gr.Blocks(title="课程幻灯片理解助手") as demo: | |
gr.Markdown("# 课程幻灯片理解助手") | |
gr.Markdown("上传幻灯片图片,AI 将帮助你理解内容并回答问题。") | |
with gr.Row(): | |
with gr.Column(): | |
image_input = gr.Image(label="上传幻灯片图片") | |
analyze_button = gr.Button("分析幻灯片") | |
with gr.Column(): | |
text_output = gr.Textbox(label="识别的文字内容", lines=5) | |
analysis_output = gr.Textbox(label="AI 分析结果", lines=10) | |
gr.Markdown("---") | |
gr.Markdown("### 与 AI 助手对话") | |
chatbot = gr.Chatbot() | |
msg = gr.Textbox(label="输入你的问题") | |
clear = gr.Button("清除对话历史") | |
# 设置事件处理 | |
analyze_button.click( | |
fn=lambda img: (extract_text_from_image(img), analyze_slide(extract_text_from_image(img))), | |
inputs=[image_input], | |
outputs=[text_output, analysis_output] | |
) | |
msg.submit( | |
fn=chat_with_assistant, | |
inputs=[msg, chatbot], | |
outputs=[chatbot], | |
clear_input=True | |
) | |
clear.click(lambda: None, None, chatbot, queue=False) | |
# 启动应用 | |
if __name__ == "__main__": | |
demo.launch() |