first commit

This commit is contained in:
zhukang 2024-12-09 22:26:29 +08:00
parent 72a6ca9955
commit 94bb96f0a7
20 changed files with 13397 additions and 2 deletions

6
.gitignore vendored
View File

@ -1,3 +1,9 @@
#-->react
node_modules/
# ---> Python # ---> Python
# Byte-compiled / optimized / DLL files # Byte-compiled / optimized / DLL files
__pycache__/ __pycache__/

View File

@ -1,2 +1,84 @@
# Slide # 启动流程
好的,我来为您详细说明服务器的启动流程。这个流程包括后端 Python Flask 服务器和前端开发服务器(如果使用的话)的启动步骤。
1. 后端服务器启动流程:
```
1. 打开终端或命令提示符。
2. 导航到项目的后端目录:
cd /path/to/your/project/backend
3. 激活虚拟环境(如果使用):
source .venv/bin/activate # 在 Linux 或 macOS 上
# 或
.venv\Scripts\activate # 在 Windows 上
4. 确保所有必要的依赖已安装:
pip install -r requirements.txt
5. 设置 Flask 应用环境变量:
export FLASK_APP=app.py # 在 Linux 或 macOS 上
# 或
set FLASK_APP=app.py # 在 Windows 上
6. (可选)设置开发模式:
export FLASK_ENV=development # 在 Linux 或 macOS 上
# 或
set FLASK_ENV=development # 在 Windows 上
7. 启动 Flask 服务器:
flask run
# 或
python -m flask run
8. 服务器应该会在 http://localhost:5000 上启动。
```
2. 前端开发服务器启动流程(如果使用):
```
1. 打开新的终端或命令提示符窗口。
2. 导航到项目的前端目录:
cd /path/to/your/project/frontend
3. 如果使用 npm 管理依赖,确保安装了所有依赖:
npm install
4. 启动开发服务器:
npm run serve # 如果使用 Vue CLI
# 或
npm start # 对于一些其他框架
5. 前端开发服务器通常会在 http://localhost:8080 或类似端口上启动。
```
3. 验证服务器启动:
```
1. 在浏览器中打开 http://localhost:5000 确认后端服务器正在运行。
你应该能看到 Flask 的默认页面或您的 API 文档(如果有的话)。
2. 如果使用前端开发服务器,在浏览器中打开 http://localhost:8080
(或控制台输出的 URL来查看您的前端应用。
3. 在前端应用中尝试生成 PPT确保与后端的通信正常。
```
4. 故障排除:
```
- 如果遇到端口被占用的错误,可以尝试更改端口:
flask run --port=5001
- 确保 CORS 设置正确,允许前端访问后端 API。
- 检查控制台输出,查看是否有任何错误消息。
- 确保 `generated` 文件夹存在于后端目录中,并且有正确的读写权限。
```
请按照这个流程启动服务器,并确保每一步都正确执行。如果在任何步骤遇到问题,请告诉我具体的错误信息,我会帮您进一步诊断和解决问题。

37
backend/app.py Normal file
View File

@ -0,0 +1,37 @@
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from text_analyzer import analyze_text
from ppt_generator import generate_ppt_image
import os
import logging
app = Flask(__name__)
CORS(app)
@app.route('/generate', methods=['POST'])
def generate():
try:
data = request.json
text = data.get('text')
if not text:
return jsonify({"error": "No text provided"}), 400
analyzed_text = analyze_text(text)
logging.info(f"Text analysis result: {analyzed_text}")
image_path = generate_ppt_image(analyzed_text)
logging.info(f"Generated image path: {image_path}")
# 修改这里返回图片的URL而不是路径
image_url = f'/get_image/{os.path.basename(image_path)}'
return jsonify({"image_url": image_url})
except Exception as e:
logging.error(f"Error in generate endpoint: {str(e)}", exc_info=True)
return jsonify({"error": str(e)}), 500
@app.route('/get_image/<filename>', methods=['GET'])
def get_image(filename):
return send_file(f'generated/{filename}', mimetype='image/png')
if __name__ == '__main__':
app.run(debug=True)

BIN
backend/arial.ttf Normal file

Binary file not shown.

BIN
backend/generated/ppt_.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 179 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 129 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

32
backend/ppt_generator.py Normal file
View File

@ -0,0 +1,32 @@
from PIL import Image, ImageDraw, ImageFont
import os
def generate_ppt_image(analyzed_text):
# 创建一个空白图像
img = Image.new('RGB', (1920, 1080), color='white')
d = ImageDraw.Draw(img)
# 加载字体
title_font = ImageFont.truetype("霞鹜文楷.ttf", 60)
subtitle_font = ImageFont.truetype("霞鹜文楷.ttf", 40)
body_font = ImageFont.truetype("霞鹜文楷.ttf", 30)
# 绘制标题
d.text((100, 100), analyzed_text['title'], fill=(0,0,0), font=title_font)
# 绘制副标题
d.text((100, 200), analyzed_text['subtitle'], fill=(100,100,100), font=subtitle_font)
# 绘制要点
y_position = 300
for point in analyzed_text['key_points']:
d.text((100, y_position), f"{point}", fill=(0,0,0), font=body_font)
y_position += 50
# 保存图像
if not os.path.exists('generated'):
os.makedirs('generated')
image_path = f"generated/ppt_{analyzed_text['title'].replace(' ', '_')}.png"
img.save(image_path)
return image_path

67
backend/text_analyzer.py Normal file
View File

@ -0,0 +1,67 @@
import json
import logging
from openai import OpenAI
def analyze_text(text):
logging.info("开始分析文本:" + text)
client = OpenAI(
base_url="https://api.wlai.vip/v1",
api_key='sk-oDyv8xZqchRiUcjCODa5AT4f16H2rIjMidY3Ua0sZNf5u8al',
timeout=120
)
try:
logging.info("发送请求到OpenAI API")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "你是一个PPT生成助手。你的任务是分析给定的文本并提取出适合制作PPT的主标题、副标题和关键点。请严格按照指定的JSON格式输出结果。"},
{"role": "user", "content": f"""请分析以下文本并提取出主标题、副标题和5-7个关键点。主标题应该简洁有力副标题可以稍微详细一些关键点应该是文本中的重要信息每个关键点应该简短精炼便于在PPT中呈现。
请严格按照以下JSON格式输出结果
{{
"title": "主标题",
"subtitle": "副标题",
"key_points": [
"关键点1",
"关键点2",
"关键点3",
"关键点4",
"关键点5"
]
}}
关键点应该至少有5个最多7个以下是需要分析的文本
{text}"""},
],
temperature=0.7
)
logging.info("成功接收API响应")
analysis = response.choices[0].message.content
# 解析和验证JSON结果
logging.info("开始解析分析结果:" + analysis)
try:
result = json.loads(analysis)
# 验证JSON结构
assert 'title' in result, "缺少主标题"
assert 'subtitle' in result, "缺少副标题"
assert 'key_points' in result, "缺少关键点"
assert isinstance(result['key_points'], list), "关键点必须是一个列表"
assert 5 <= len(result['key_points']) <= 7, "关键点数量必须在5到7之间"
logging.info(f"分析完成,结果:{result}")
return result
except json.JSONDecodeError:
logging.error("JSON解析失败")
raise ValueError("API返回的结果不是有效的JSON格式")
except AssertionError as e:
logging.error(f"JSON结构验证失败: {str(e)}")
raise ValueError(f"API返回的JSON结构不符合要求: {str(e)}")
except Exception as e:
logging.error(f"分析过程中发生错误: {str(e)}")
raise

BIN
backend/霞鹜文楷.ttf Normal file

Binary file not shown.

26
frontend/index.html Normal file
View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>智能PPT生成器</title>
<link rel="stylesheet" href="style.css">
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<h1>智能PPT生成器</h1>
<div class="container">
<div class="input-section">
<textarea v-model="inputText" placeholder="请输入PPT内容..."></textarea>
<button @click="generatePPT" :disabled="isGenerating">{{ isGenerating ? '生成中...' : '生成PPT' }}</button>
</div>
<div class="preview-section">
<img v-if="pptImage" :src="pptImage" alt="生成的PPT">
<a v-if="pptImage" :href="pptImage" download>下载图片</a>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

12934
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
frontend/package.json Normal file
View File

@ -0,0 +1,20 @@
{
"name": "frontend",
"version": "1.0.0",
"description": "",
"main": "script.js",
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"test": "vue-cli-service test"
},
"dependencies": {
"axios": "^1.7.7",
"vue": "^2.6.11"
},
"devDependencies": {
"@vue/cli-service": "^4.5.0"
},
"author": "zhukang",
"license": "ISC"
}

110
frontend/src/App.vue Normal file
View File

@ -0,0 +1,110 @@
<template>
<div id="app">
<h1>智能PPT生成器</h1>
<div class="container">
<div class="input-section">
<textarea v-model="inputText" placeholder="请输入PPT内容..."></textarea>
<button @click="generatePPT" :disabled="isGenerating">{{ isGenerating ? '生成中...' : '生成PPT' }}</button>
</div>
<div class="preview-section">
<img v-if="pptImage" :src="pptImage" alt="生成的PPT">
<a v-if="pptImage" :href="pptImage" download>下载图片</a>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
inputText: '',
pptImage: null,
isGenerating: false
};
},
methods: {
generatePPT() {
this.isGenerating = true;
axios.post('http://localhost:5000/generate', {
text: this.inputText
})
.then(response => {
this.pptImage = 'http://localhost:5000' + response.data.image_url;
})
.catch(error => {
console.error('Error:', error);
alert('生成PPT时发生错误请重试。');
})
.finally(() => {
this.isGenerating = false;
});
}
}
};
</script>
<style scoped>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
}
#app {
max-width: 1200px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 {
text-align: center;
color: #333;
}
.container {
display: flex;
gap: 20px;
}
.input-section, .preview-section {
flex: 1;
}
textarea {
width: 100%;
height: 300px;
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
button, a {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-decoration: none;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
img {
max-width: 100%;
border: 1px solid #ddd;
border-radius: 4px;
}
</style>

10
frontend/src/main.js Normal file
View File

@ -0,0 +1,10 @@
import Vue from 'vue/dist/vue.esm.js'; // 使用包含模板编译器的版本
import App from './App.vue';
import axios from 'axios';
Vue.config.productionTip = false;
new Vue({
el: '#app',
render: h => h(App)
});

60
frontend/style.css Normal file
View File

@ -0,0 +1,60 @@
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 20px;
background-color: #f0f0f0;
}
#app {
max-width: 1200px;
margin: 0 auto;
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
h1 {
text-align: center;
color: #333;
}
.container {
display: flex;
gap: 20px;
}
.input-section, .preview-section {
flex: 1;
}
textarea {
width: 100%;
height: 300px;
margin-bottom: 10px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
button, a {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
text-decoration: none;
}
button:disabled {
background-color: #cccccc;
cursor: not-allowed;
}
img {
max-width: 100%;
border: 1px solid #ddd;
border-radius: 4px;
}

4
requirements.txt Normal file
View File

@ -0,0 +1,4 @@
flask
flask-cors
openai
pillow

7
test.txt Normal file
View File

@ -0,0 +1,7 @@
prompt:
本报北京10月13日电 (记者王观)国家税务总局最新发布的增值税发票数据显示:今年前三季度,我国经济运行总体平稳、稳中有进,新质生产力加快发展。
工业运行总体平稳。前三季度全国工业企业销售收入同比增长3.6%。其中装备制造业同比增长5.3%特别是计算机通信设备制造业、仪器仪表制造业等先进制造业发展向好同比分别增长13.5%和10.5%。
新质生产力加快成长。前三季度高技术产业销售收入同比增长11.6%。其中高技术服务业、高技术制造业同比分别增长13.7%和8.6%反映创新产业持续壮大。数字经济核心产业销售收入同比增长7.7%。
“两新”发展势头良好。前三季度在大规模设备更新政策带动下全国企业采购机械设备金额同比增长6.5%其中9月份较8月份同比增速加快2.4个百分点。在消费品以旧换新政策带动下电视机等家用视听设备、冰箱等日用家电零售同比分别增长10.2%和6.5%与家装相关的家具、卫生洁具零售同比分别增长13.9%和10.5%。
绿色低碳加快发展。前三季度生态保护和环境治理业销售收入同比增长11.4%其中9月份同比增长12.7%。新能源、节能、环保等绿色技术服务业同比分别增长22.5%、18.7%和6%。清洁能源产业保持较快增速太阳能、水力、风力发电同比分别增长30.3%、13.6%和10.9%新能源车制造业同比增长31.8%。
交通物流更加畅通。前三季度交通运输物流业销售收入同比增长10%特别是多式联运和运输代理、邮政快递业同比分别增长33.5%和11.3%。全国省际间销售额同比增长2.5%较全国企业销售收入总体增速快1.1个百分点,反映省际间商品服务贸易较为畅通。