import os
import uuid
import time
from flask import Blueprint, send_file, request, jsonify, current_app
from pathlib import Path
from openai import OpenAI
from werkzeug.utils import secure_filename

text_bp = Blueprint('text_bp', __name__, template_folder='templates/text_templates')

# 初始化 OpenAI 客户端
client = OpenAI(
    api_key="sk-a1b6dqOjHmyTyR47ejD6SyAI7nLcxYgCGTdZweTrCF77y9T9",
    base_url="https://api.moonshot.cn/v1",
)

# 任务存储
text_tasks = {}

@text_bp.route('/upload', methods=['POST'])
def text_upload():
    if 'file' not in request.files:
        return jsonify({'error': 'No file selected'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'Invalid file'}), 400

    if not file.filename.lower().endswith('.pptx'):
        return jsonify({'error': 'Only PPTX files are allowed'}), 400

    task_id = str(uuid.uuid4())
    text_tasks[task_id] = {
        'status': 'uploading',
        'progress': 0,
        'message': 'Uploading file...'
    }

    save_dir = Path(current_app.config['TEXT_UPLOAD_FOLDER']) / task_id
    save_dir.mkdir(parents=True, exist_ok=True)

    filename = secure_filename(file.filename)
    file_path = save_dir / filename
    file.save(file_path)

    text_tasks[task_id].update({
        'status': 'processing',
        'progress': 20,
        'message': 'Processing file...',
        'file_path': str(file_path)
    })

    process_text_task(task_id)

    return jsonify({'task_id': task_id})

def process_text_task(task_id):
    try:
        task = text_tasks.get(task_id)
        if not task:
            return

        update_text_task(task_id, 30, 'Uploading to cloud...')
        file_id = upload_pptx(task['file_path'])

        update_text_task(task_id, 50, 'Extracting content...')
        content = get_pptx_content(file_id)

        update_text_task(task_id, 70, 'Generating script...')
        script = generate_script(content)

        update_text_task(task_id, 90, 'Saving results...')
        output_dir = Path(task['file_path']).parent / 'output'
        script_path = save_script(script, output_dir)

        text_tasks[task_id].update({
            'status': 'completed',
            'progress': 100,
            'result_path': str(script_path),
            'message': 'Process completed'
        })
    except Exception as e:
        text_tasks[task_id].update({
            'status': 'failed',
            'progress': 100,
            'message': f'Error: {str(e)}'
        })

def update_text_task(task_id, progress, message):
    if task_id in text_tasks:
        text_tasks[task_id].update({'progress': progress, 'message': message})

def upload_pptx(file_path):
    try:
        file_object = client.files.create(file=Path(file_path), purpose="file-extract")
        return file_object.id
    except Exception as e:
        raise RuntimeError(f"File upload failed: {str(e)}")

def get_pptx_content(file_id):
    for _ in range(5):
        try:
            return client.files.content(file_id=file_id).text
        except Exception:
            time.sleep(5)
    raise RuntimeError("File processing timeout")

def generate_script(content):
    response = client.chat.completions.create(
        model="moonshot-v1-32k",
        messages=[{
            "role": "system",
            "content": "身份:老师 职责:根据PPT内容深入讲解 语言风格:生动准确 每页开头语言:第n页"
        }, {
            "role": "user",
            "content": content
        }],
        temperature=0.3,
        max_tokens=2000
    )
    return response.choices[0].message.content

def save_script(script, output_dir):
    output_dir.mkdir(exist_ok=True)
    script_path = output_dir / "script.txt"
    with open(script_path, "w", encoding="utf-8") as f:
        f.write(script)
    return script_path

@text_bp.route('/status/<task_id>')
def text_status(task_id):
    return jsonify(text_tasks.get(task_id, {'status': 'not_found'}))

@text_bp.route('/download/<task_id>')
def text_download(task_id):
    task = text_tasks.get(task_id)
    if not task or task['status'] != 'completed':
        return jsonify({'error': 'File not available'}), 404
    file_path = os.path.join("D:/Project/VisualStudioCode/EduVoice/",str(task['result_path']).replace('\\','/'))
    print(file_path)
    return send_file(file_path,as_attachment=True)
posted on 2025-04-28 21:15  leapss  阅读(11)  评论(0)    收藏  举报