大家好,我是小林,今天在天津做了一场 AI 编程主题分享,其中有一些是近期一线实践后理解的 vibe coding 盲区。
刚好最近和大鹏在参加阿里的比赛,做了个视频分析工具,给大家分享下心得。
提示词(Prompt)是新时代的编程语言,重要性不用多说。
AI 产出代码效率很高,但代码堆在一起就是一盘散沙,怎么设计模块、怎么规划流程、怎么保证代码质量、以后怎么维护,这些 AI 都不会。
所以第二个能力软件工程便体现了出来,AI时代一样需要人作为架构师去操盘。
比如用户说我想要一匹更快的马,其实他是想更快地到达目的地。
技术门槛越来越低,功能实现门槛虽然降低了,但长得丑、难用的东西根本没人想碰。
审美能力,UI/UX 产品的脸面,用户的第一印象决定是否继续使用。
流量启动星球已经有很多做流量的文章,大家可以多看精华,打造自己的 IP。
AI 编程实现下面我会通过一个具体的案例(视频分析工具开发)再来给大家演示下。
这个能力是最容易被培养起来的,需要大家在实践的过程中分清楚什么活人来干,什么活 AI 干。
收藏夹越堆越满,但真正会回头去看的没几个。最让我头疼的是那些长视频,想要精准地捕捉核心内容和关键点更是耗时费力,经常是看着看着就漏掉了关键信息。尤其在赶时间或者查找资料时,这种低效真的很让人抓狂。
为了解决这个效率难题,我迫切需要有一款工具,可以帮我快速总结视频内容,自动生成视频章节标记,方便我快速了解关键信息。
本次使用通义灵码 IDE,结合 Qwen3-Coder 模型,从 0 到 1,完成开发并部署一款视频处理工具。
提交体验申请,填写完问卷之后,就可以获得下载链接了。
安装好软件,打开之后,会看到默认已经选中了 Qwen3-Coder 模型。
在正式写代码之前,把我要做的需求,跟 AI 沟通清楚,让 AI 完全理解我们的需求,评估是否可行。需求理解到位,是后续所有开发的前提。
我有一批视频,我想知道视频的主要内容,或者基于视频内容,回答我的提问。
开发一个Web应用,我可以输入单个视频或者多个视频链接,提交视频链接,经过后台服务处理之后,快速获取该视频的智能摘要,并能通过自然语言问答的方式,深入挖掘视频内的特定信息。
你看一下我想要做的功能,你觉得不合理的地方,可以指出来,如果完全理解了,你复述一遍我的需求功能。 从回答中,能看出,Qwen3-Coder 模型确实完全理解了我的需求,也评估了技术实现方案的可行性。
在回答中,提到了阿里云百炼平台支持视频理解功能。为了确保真实可靠,我去阿里云百炼大模型平台看了一下使用文档,确实也提到了视频理解,说明 Qwen3-Coder 模型给出的方案是准确的。
确认了有大模型能提供能力支持,接下来还需要有一个简单的框架,可以将大模型返回的数据,展示到页面上。
你刚才提到了用 Python 作为后端服务,但是我希望提供一个前端页面,允许用户提交一个或多个视频链接,并输入想要获取的信息或问题。如果后端使用 Python 开发,处理视频内容,有没有轻量化的 Python 框架,我希望整体框架轻量化,能够快速开发和部署,快速完成我的需求功能。 Qwen3-Coder 模型推荐使用 Flask 框架来快速上手,构建 完整的 Web 应用。
现在,Qwen3-Coder 模型完全理解了我的需求,要使用到的技术也清晰了。
需求沟通清楚之后,不用着急写代码。先让 AI 设计技术方案,技术方案是后续写代码很重要的依据。
你理解的非常好。基于你的理解,你帮我设计一个具体的技术实现方案,并将该方案详细写入到当前目录下的 plan.md文件中 等 AI 完成了方案,自己看一遍,认可方案的话,就可以开始写代码了。
还细心的拆分了阶段任务,我觉得这一点非常好,避免一次写太多,产生混乱。
基于你的实现方案 plan.md,我们先专注于实现第一阶段中的核心基础架构:即搭建一个基于 Flask 的 Web 框架和用户界面。这个基础框架将能够接收用户输入,并返回一个模拟数据,以此验证整个请求和响应流程是否通畅。在我测试确认无误后,我们再继续实现后续复杂功能。 现在,生成了 Python 代码,对于之前没接触 Python 的朋友,需要先安装 Python 相关的环境。
我是 Python 新人,我希望寻找一些工具来快速配置 Python 开发环境和运行代码。请推荐一些适合初学者的软件。
最好能满足以下特点:
1.提供图形化界面(非命令行操作),方便直观地管理环境和项目;
2.集成度高,能简化安装和依赖管理的流程;
3.适合新手快速上手,能轻松编写和调试代码。
请主要推荐这样的可视化工具,并简要说明它们的核心优势。 从回答中,可以看到推荐 Anaconda + PyCharm,Anaconda 内置了大量的常用库(可以理解为别人已经写好,可以直接使用的功能),开箱即用,能省去 80% 的环境配置时间。
下载安装成功之后,就配置好默认 Python 环境了,可以看到已经安装了很多常用库,能满足大部分需求场景。
为了快速运行 Python,下载 PyCharm 这款 IDE,适合新手,社区版免费且功能足够。它提供了智能代码补全、错误检测等功能,对初学者很友好。
配置好 Python 环境,安装好 PyCharm 之后,就可以运行代码了。在 PyCharm 中打开文件,在 Python 文件中右键选择运行,即可快速运行 Python 代码。
输入一个链接,能够正常显示分析结果(当前返回的都是假数据,在 Python 中固定写好的数据),测试没有报错,说明整个前后端服务链路是没问题的。现在还没开始接入大模型服务,只是让 AI 完成了基础框架代码。接下来就可以开始开发核心功能了。
基本流程跑通之后,就可以开始增加大模型处理功能了。
为提升响应速度与用户体验,大模型会采用流式输出模式,将计算过程中的中间结果实时返回给用户,大幅减少了用户等待的焦虑感,并有效避免了因生成时间过长而导致的请求超时问题。
非常好,我测试基础功能没问题。可以继续实现第一阶段的其他功能,集成阿里云百炼平台 API 和实现流式结果返回。
如果你不太清楚如何调用 API,可以参考这个文档:https://bailian.console.aliyun.com/?tab=doc#/doc/?type=model&url=2845871 如果没有配置真实的 API 密钥,默认情况下,返回了模拟数据。
注意: 创建的 API KEY,只要不删除,默认是长期有效的,一定要保管好,发现异常之后,及时删除。
将新建的密钥,填写到代码配置中,除了 API KEY 这个关键参数之外,还可以设置使用哪个大模型。
阿里云百炼平台有很多大模型可以使用,当前 qwen-vl-max 、 qwen-vl-plus 模型已支持 上下文缓存 。如果请求被系统判断命中了缓存,会减少 token 费用, cached_token 单价为 input_token 单价的 40%
配置好 API 密钥之后,在页面上输入一个视频链接,效果如图所示:
整个开发过程中分阶段开发的,代码会比较多,考虑到后面我们还要增加新功能,为了避免新的改动影响之前的代码,建议用 git 管理代码。
不了解 git 没关系,可以理解为给代码的每次重要改动拍快照,有了快照,就可以快速回退到之前的任意版本。
使用 git 也很简单,只需用自然语言描述清楚就行。
请用 Git 工具协助我管理代码,检测当前计算机是否已安装 Git,若未检测到 Git,请自动帮我安装,安装成功之后,自动提交代码。 自动帮我完成了一次代码提交。在哪里可以看到提交记录呢?
点击左边第 3 个图标,就能看到所有的提交记录了。
第一阶段,主要是完成了单个视频的处理,希望在此基础上,能批量处理多条视频。
非常棒,第一阶段的基础功能已通过测试,运行稳定。开始第二阶段开发,核心任务如下:
1.批量处理:增加批量视频链接处理功能,支持用户同时提交多个链接。
2.界面优化:优化前端页面布局与交互,使其更加美观、专业且用户友好。
请基于现有代码架构进行上述迭代开发。 测试一下功能是否正常可用。打开页面,输入 2 个视频链接,看看效果怎么样。
至此,整个工具的核心流程就开发完了。在本地启动 Python 服务,就可以正常使用了。
在本地使用的时候,每次都需要启动服务,比较麻烦。服务器可以理解为 7*24 不关机的电脑,部署到服务器上,就不用重复启动服务了。
一般而言,生产环境用的代码,会比本地开发环境性能好一些。
作为 Python 新手,我希望将开发好的 Flask Web 应用部署到线上服务器,并能够通过外网访问。
请推荐一个适合新手的、提供可视化操作界面的部署平台或工具,目标是尽可能简化配置流程,避免复杂的命令行操作。同时,请简要说明基本的部署步骤和注意事项。 在回答中提到了宝塔面板,该怎么配置使用呢,告诉 AI 你的服务器系统,不同的服务器系统,操作会有一些差异。
我的服务器操作系统是 CentOS 8。我需要一份详细、分步骤的指南,用于安装宝塔面板。请确保所有命令和步骤都明确针对 CentOS 8 系统。 我按照详细步骤,在服务器上安装了宝塔面板,接下来就该配置项目环境了。
选择 Python 项目,之前没有配置过,添加一个新项目。
上传文件,我用到了 WindTerm 这款软件,可视化操作,将文件上传到服务器很方便。
AI 在回答里面,结合当前项目,已经给出了这些配置要如何填写,对照着填写就行。
默认是未启动,启动成功,就可以通过服务器 IP + 端口号访问了。如果有自己的域名,也可以通过域名来访问。
整个过程,在 AI 工具的辅助下,从沟通需求,到最终部署上线,花费了 2 个小时,完成了一款符合自己要求的工具,还是挺方便的。
在开发过程中,国产编程模型 Qwen3-Coder ,代码生成的速度还是很流畅的,编程工作效率大幅提升。
个人感觉,国产编程大模型已从追赶者转向定义者,下一阶段竞争焦点在于垂直场景的深度优化。
from flask import Flask, render_template, request, jsonify, Response
import os
import json
import time
import re
import threading
import queue
from typing import Optional
import dashscope
from dashscope import MultiModalConversation
template_dir = 'templates'
static_dir = 'static'
if not os.path.exists(template_dir):
os.makedirs(template_dir)
if not os.path.exists(static_dir):
os.makedirs(static_dir)
app = Flask(
__name__, template_folder=template_dir, static_folder=static_dir
)
dashscope.api_key = ""
def _format_sse ( event_type: str , data, video_url: Optional [ str ] = None ):
payload = { "type" : event_type, "data" : data}
if video_url is not None :
payload[ "video_url" ] = video_url
return f"data: {json.dumps(payload, ensure_ascii= False )} \n\n"
def generate_video_analysis_stream ( video_urls, question= None , max_workers: int = 3 ):
"""
并发流式处理多个视频:
- 为每个视频并发请求模型接口,逐块发送 `api_response` 事件
- 每个事件包含 `video_url` 以便前端分组展示
- 额外发送 `start_video` 与 `end_video` 事件标注边界
"""
if not getattr (dashscope, "api_key" , None ):
yield _format_sse( "error" , "未配置 API Key,请设置环境变量 DASHSCOPE_API_KEY" )
return
event_queue = queue.Queue()
semaphore = threading.Semaphore(max_workers if max_workers > 0 else 1 )
def worker ( video_url: str ):
nonlocal question
with semaphore:
event_queue.put(( "start_video" , video_url, "开始分析" ))
try :
messages = [
{
"role" : "user" ,
"content" : [
{ "video" : video_url},
{
"text" : (
question
if question
else "请用中文直接解析该视频内容,输出 Markdown,总结摘要、关键物体、场景与关键片段。"
)
},
],
}
]
responses = MultiModalConversation.call(
model= "qwen-vl-plus" ,
messages=messages,
stream= True ,
incremental_output= True ,
)
for response in responses:
if (
response.output.choices
and response.output.choices[ 0 ].message.content
):
content = response.output.choices[ 0 ].message.content
if isinstance (content, list ):
for item in content:
if isinstance (item, dict ) and "text" in item:
chunk = str (item[ "text" ])
event_queue.put(( "api_response" , video_url, chunk))
else :
chunk = str (content)
event_queue.put(( "api_response" , video_url, chunk))
event_queue.put(( "end_video" , video_url, "分析完成" ))
except Exception as e:
event_queue.put(( "error" , video_url, f"发生错误: { str (e)} " ))
event_queue.put(( "end_video" , video_url, "分析结束(异常)" ))
threads = []
for url in video_urls:
t = threading.Thread(target=worker, args=(url,), daemon= True )
t.start()
threads.append(t)
completed = 0
total = len (video_urls)
while completed < total:
event_type, video_url, content = event_queue.get()
if event_type == "end_video" :
completed += 1
yield _format_sse(event_type, content, video_url)
yield _format_sse( "all_complete" , "全部视频处理完成" , None )
@app.route( '/' )
def index ():
return render_template( 'index.html' )
@app.route( '/stream_analyze' , methods=[ 'POST' ] )
def stream_analyze ():
"""
流式处理视频分析请求
"""
try :
data = request.get_json()
video_urls = data.get( 'video_urls' , [])
question = data.get( 'question' , None )
if not video_urls:
def error_generator ():
yield f"data: {json.dumps({ 'type' : 'error' , 'data' : '请提供至少一个视频链接' } )}\n\n"
return Response(error_generator(), mimetype= 'text/event-stream' )
for url in video_urls:
if not url.startswith(( 'http://' , 'https://' )):
def error_generator ():
yield f"data: {json.dumps({ 'type' : 'error' , 'data' : f'无效的视频链接: {url} ' } )}\n\n"
return Response(error_generator(), mimetype= 'text/event-stream' )
return Response(
generate_video_analysis_stream(video_urls, question),
mimetype= 'text/event-stream' ,
headers={
'Cache-Control' : 'no-cache' ,
'Connection' : 'keep-alive'
}
)
except Exception as e:
def error_generator ():
yield f"data: {json.dumps({ 'type' : 'error' , 'data' : str (e)} )}\n\n"
return Response(error_generator(), mimetype= 'text/event-stream' )
if __name__ == '__main__' :
app.run(debug= True , threaded= True , host= '0.0.0.0' , port= 5000 )
<!DOCTYPE html >
< html lang = "zh-CN" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content = "width=device-width, initial-scale=1.0" >
< title > 视频分析工具 </ title >
< style >
body {
font-family : 'Segoe UI' , Tahoma, Geneva, Verdana, sans-serif;
max-width : 1000px ;
margin : 0 auto;
padding : 20px ;
background-color : #f5f5f5 ;
}
.container {
background-color : white;
padding : 30px ;
border-radius : 10px ;
box-shadow : 0 0 10px rgba ( 0 , 0 , 0 , 0.1 );
max-width : 1200px ;
position : relative;
}
.layout {
display : grid;
grid-template-columns : 380px 1 fr;
gap : 24px ;
align-items : start;
}
@media ( max-width : 980px ) {
.layout { grid-template-columns : 1 fr; }
}
h1 {
color : #333 ;
text-align : center;
}
.form-group {
margin-bottom : 20px ;
}
label {
display : block;
margin-bottom : 5px ;
font-weight : bold;
color : #555 ;
}
input [type= "url" ] , textarea {
width : 100% ;
padding : 12px ;
border : 1px solid #ddd ;
border-radius : 5px ;
font-size : 16px ;
box-sizing : border-box;
}
textarea {
height : 100px ;
resize : vertical;
}
.button-group {
display : flex;
gap : 10px ;
margin-top : 20px ;
}
button {
background-color : #4CAF50 ;
color : white;
padding : 12px 20px ;
border : none;
border-radius : 5px ;
cursor : pointer;
font-size : 16px ;
flex : 1 ;
}
button :hover {
background-color : #45a049 ;
}
button :disabled {
background-color : #cccccc ;
cursor : not-allowed;
}
.stream-btn {
background-color : #2196F3 ;
}
.stream-btn :hover {
background-color : #0b7dda ;
}
.result {
margin-top : 20px ;
padding : 15px ;
border-radius : 5px ;
display : none;
}
.result .success {
background-color : #dff0d8 ;
border : 1px solid #d6e9c6 ;
color : #3c763d ;
}
.result .error {
background-color : #f2dede ;
border : 1px solid #ebccd1 ;
color : #a94442 ;
}
.loading {
position : absolute;
inset : 0 ;
display : none;
align-items : center;
justify-content : center;
flex-direction : column;
text-align : center;
gap : 8px ;
background : rgba ( 255 , 255 , 255 , 0.6 );
z-index : 10 ;
}
.spinner {
border : 4px solid #f3f3f3 ;
border-top : 4px solid #3498db ;
border-radius : 50% ;
width : 30px ;
height : 30px ;
animation : spin 2s linear infinite;
margin : 0 auto;
}
@keyframes spin {
0% { transform : rotate ( 0deg ); }
100% { transform : rotate ( 360deg ); }
}
.video-result {
border : 1px solid #ddd ;
border-radius : 5px ;
padding : 15px ;
margin-bottom : 15px ;
background-color : #fafafa ;
}
.video-url {
font-weight : bold;
color : #337ab7 ;
margin-bottom : 10px ;
}
.video-info {
margin-top : 10px ;
}
.video-info h3 {
color : #333 ;
border-bottom : 1px solid #eee ;
padding-bottom : 5px ;
margin-top : 15px ;
}
.video-info ul {
padding-left : 20px ;
}
.video-info li {
margin-bottom : 5px ;
}
.question-answer {
background-color : #e8f5e9 ;
padding : 10px ;
border-radius : 5px ;
margin-top : 10px ;
}
.stream-container {
border : 1px solid #ddd ;
border-radius : 5px ;
padding : 15px ;
margin-top : 20px ;
background-color : #f9f9f9 ;
height : 60vh ;
overflow : auto;
display : block;
position : relative;
}
.cards-grid {
display : grid;
grid-template-columns : repeat ( 2 , minmax ( 0 , 1 fr));
gap : 20px ;
}
@media ( max-width : 980px ) {
.cards-grid { grid-template-columns : 1 fr; }
}
.cards-grid .single { grid-template-columns : 1 fr; }
.video-card {
background : #ffffff ;
border : 1px solid #e5e7eb ;
border-radius : 8px ;
padding : 12px 12px 8px 12px ;
box-shadow : 0 1px 2px rgba ( 0 , 0 , 0 , 0.04 );
display : flex;
flex-direction : column;
min-height : 160px ;
position : relative;
}
.card-header {
display : flex;
align-items : center;
gap : 8px ;
margin-bottom : 8px ;
}
.card-title { font-size : 13px ; font-weight : 600 ; flex : 1 1 auto; min-width : 0 ; }
.card-title a { color : #2563eb ; text-decoration : none; word-break : break-all; }
.card-title a :hover { text-decoration : underline; }
.header-actions { display : none; }
.copy-btn { position : absolute; top : 8px ; right : 8px ; width : 28px ; height : 28px ; border-radius : 6px ; border : 1px solid #c7d2fe ; background : #eef2ff ; color : #3730a3 ; display : inline-flex; align-items : center; justify-content : center; cursor : pointer; transition : background . 15s ease, border-color . 15s ease; }
.copy-btn :hover { background : #e0e7ff ; border-color : #a5b4fc ; }
.copy-btn :active { background : #c7d2fe ; }
.copy-btn svg { width : 14px ; height : 14px ; }
.copy-btn [data-tooltip] { position : absolute; }
.copy-btn [data-tooltip] ::after { content : attr (data-tooltip); position : absolute; top : - 34px ; right : 0 ; background : #111827 ; color : #fff ; font-size : 12px ; padding : 4px 8px ; border-radius : 6px ; box-shadow : 0 10px 15px - 3px rgba ( 0 , 0 , 0 , 0.1 ); opacity : 0 ; transform : translateY ( 4px ); transition : all . 15s ease; pointer-events : none; white-space : nowrap; }
.copy-btn :hover ::after { opacity : 1 ; transform : translateY ( 0 ); }
.status-badge {
font-size : 12px ;
padding : 2px 8px ;
border-radius : 999px ;
border : 1px solid #e5e7eb ;
color : #374151 ;
background : #f9fafb ;
white-space : nowrap;
}
.status-running { color : #1d4ed8 ; background : #dbeafe ; border-color : #bfdbfe ; }
.status-done { color : #065f46 ; background : #d1fae5 ; border-color : #a7f3d0 ; }
.status-error { color : #991b1b ; background : #fee2e2 ; border-color : #fecaca ; }
.card-content {
flex : 1 ;
overflow : auto;
padding-top : 4px ;
border-top : 1px dashed #e5e7eb ;
}
.stream-line {
margin-bottom : 10px ;
padding : 5px ;
border-radius : 3px ;
animation : fadeIn 0.3s ;
}
@keyframes fadeIn {
from { opacity : 0 ; }
to { opacity : 1 ; }
}
.stream-start { color : #666 ; font-style : italic; }
.stream-progress { color : #31708f ; background-color : #d9edf7 ; }
.stream-question { font-weight : bold; color : #333 ; border-bottom : 1px dashed #ccc ; }
.stream-answer { color : #3c763d ; background-color : #dff0d8 ; }
.stream-detail { color : #333 ; padding-left : 15px ; }
.stream-summary { font-weight : bold; color : #333 ; border-bottom : 1px dashed #ccc ; }
.stream-objects { color : #3c763d ; background-color : #dff0d8 ; }
.stream-scenes { color : #8a6d3b ; background-color : #fcf8e3 ; }
.stream-key_moments { color : #a94442 ; background-color : #f2dede ; }
.stream-complete { color : #3c763d ; font-weight : bold; }
.stream-end { color : #3c763d ; font-weight : bold; text-align : center; background-color : #dff0d8 ; }
.stream-error { color : #a94442 ; background-color : #f2dede ; }
.stream-warning { color : #8a6d3b ; background-color : #fcf8e3 ; font-weight : bold; }
.stream-info { color : #31708f ; background-color : #d9edf7 ; }
.stream-api_response { color : #333 ; }
.toast { position : absolute; top : 12px ; left : 50% ; transform : translate (- 50% , - 8px ); background : #111827 ; color : #fff ; padding : 10px 14px ; border-radius : 8px ; box-shadow : 0 10px 15px - 3px rgba ( 0 , 0 , 0 , 0.1 ); opacity : 0 ; transition : all . 2s ease; pointer-events : none; z-index : 100 ; }
.toast .show { opacity : 1 ; transform : translate (- 50% , 0 ); }
</ style >
< script src = "https://cdn.jsdelivr.net/npm/marked/marked.min.js" > </ script >
< script src = "https://cdn.jsdelivr.net/npm/dompurify@3.0.8/dist/purify.min.js" > </ script >
</ head >
< body >
< div class = "container" >
< h1 > 视频分析工具 </ h1 >
< div class = "layout" >
< div class = "left-panel" >
< form id = "analysisForm" >
< div class = "form-group" >
< label for = "video_urls" > 视频链接(每行一个): </ label >
< textarea id = "video_urls" name = "video_urls" placeholder = "请输入视频链接,每行一个,例如:
https://example.com/video1.mp4
https://example.com/video2.mp4" required style = "height: 350px;" > </ textarea >
</ div >
< div class = "form-group" >
< label for = "question" > 问题(可选): </ label >
< textarea id = "question" name = "question" placeholder = "您可以在这里输入关于视频内容的问题..." > </ textarea >
</ div >
< div class = "button-group" >
< button type = "button" id = "streamBtn" class = "stream-btn" > 分析视频 </ button >
</ div >
</ form >
</ div >
< div class = "right-panel" >
< div class = "stream-container" id = "streamContainer" >
< h3 > 实时分析过程 </ h3 >
< div id = "streamContent" class = "cards-grid" > </ div >
</ div >
< div class = "result" id = "result" > </ div >
</ div >
</ div >
< div class = "toast" id = "toast" > </ div >
</ div >
< script >
document . getElementById ( 'streamBtn' ). addEventListener ( 'click' , function ( e ) {
e. preventDefault ();
const videoUrlsText = document . getElementById ( 'video_urls' ). value ;
const question = document . getElementById ( 'question' ). value ;
const streamBtn = document . getElementById ( 'streamBtn' );
const resultDiv = document . getElementById ( 'result' );
const streamContainer = document . getElementById ( 'streamContainer' );
const streamContent = document . getElementById ( 'streamContent' );
const toast = document . getElementById ( 'toast' );
const videoUrls = videoUrlsText. split ( '\n' )
. map ( url => url. trim ())
. filter ( url => url. length > 0 );
if (videoUrls. length === 0 ) {
alert ( '请至少输入一个视频链接' );
return ;
}
streamBtn. disabled = true ;
resultDiv. style . display = 'none' ;
streamContainer. style . display = 'block' ;
streamContent. innerHTML = '' ;
const videoState = new Map ();
function ensureVideoCard ( videoUrl ) {
if (videoState. has (videoUrl)) return videoState. get (videoUrl);
const card = document . createElement ( 'div' );
card. className = 'video-card' ;
const header = document . createElement ( 'div' );
header. className = 'card-header' ;
const title = document . createElement ( 'div' );
title. className = 'card-title' ;
const a = document . createElement ( 'a' );
a. href = videoUrl;
a. target = '_blank' ;
a. rel = 'noopener noreferrer' ;
a. textContent = videoUrl;
title. appendChild (a);
const statusEl = document . createElement ( 'span' );
statusEl. className = 'status-badge status-running' ;
statusEl. textContent = '分析中' ;
const actions = document . createElement ( 'div' );
actions. className = 'header-actions' ;
const copyBtn = document . createElement ( 'button' );
copyBtn. className = 'copy-btn' ;
copyBtn. type = 'button' ;
copyBtn. setAttribute ( 'data-tooltip' , '复制结果' );
copyBtn. innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>' ;
copyBtn. addEventListener ( 'click' , async () => {
const state = videoState. get (videoUrl);
try {
await navigator. clipboard . writeText (state?. mdBuffer || '' );
showToast ( '已复制到剪贴板' );
} catch (_) {
showToast ( '复制失败' );
}
});
actions. appendChild (copyBtn);
header. appendChild (title);
const contentEl = document . createElement ( 'div' );
contentEl. className = 'card-content' ;
card. appendChild (header);
card. appendChild (contentEl);
streamContent. appendChild (card);
const count = streamContent. querySelectorAll ( '.video-card' ). length ;
streamContent. classList . toggle ( 'single' , count === 1 );
const state = { card, statusEl, contentEl, mdBuffer : '' , flushScheduled : false };
videoState. set (videoUrl, state);
return state;
}
function setStatus ( videoUrl, status, kind ) {
const state = ensureVideoCard (videoUrl);
state. statusEl . textContent = status;
state. statusEl . className = `status-badge ${kind} ` ;
}
function appendMarkdown ( videoUrl, chunk ) {
const state = ensureVideoCard (videoUrl);
state. mdBuffer += String (chunk);
if (state. flushScheduled ) return ;
state. flushScheduled = true ;
requestAnimationFrame ( () => {
const html = window . marked ? marked. parse (state. mdBuffer ) : state. mdBuffer ;
state. contentEl . innerHTML = window . DOMPurify ? DOMPurify . sanitize (html) : html;
state. flushScheduled = false ;
});
}
const xhr = new XMLHttpRequest ();
xhr. open ( 'POST' , '/stream_analyze' , true );
xhr. setRequestHeader ( 'Content-Type' , 'application/json' );
xhr. responseType = 'text' ;
let position = 0 ;
let sseBuffer = '' ;
xhr. onreadystatechange = function ( ) {
if (xhr. readyState === 3 ) {
processStreamData (xhr. responseText . substring (position));
position = xhr. responseText . length ;
} else if (xhr. readyState === 4 ) {
if (position < xhr. responseText . length ) {
processStreamData (xhr. responseText . substring (position));
position = xhr. responseText . length ;
}
if (xhr. status !== 200 ) {
addStreamMessage ( 'error' , '连接错误: ' + xhr. status );
}
streamBtn. disabled = false ;
}
};
xhr. onerror = function ( ) {
addStreamMessage ( 'error' , '网络错误' );
streamBtn. disabled = false ;
};
xhr. send ( JSON . stringify ({
video_urls : videoUrls,
question : question
}));
function processStreamData ( text ) {
if (!text) return ;
sseBuffer += text;
const events = sseBuffer. split ( '\n\n' );
sseBuffer = events. pop () || '' ;
for ( const line of events) {
if (line. startsWith ( 'data: ' )) {
const payload = line. slice ( 6 );
try {
const data = JSON . parse (payload);
addStreamMessage (data. type , data. data , data. video_url );
} catch (e) {
console . error ( '解析数据出错:' , e);
}
}
}
}
if ( window . marked ) {
marked. setOptions ({
gfm : true ,
breaks : true
});
}
function addStreamMessage ( type, content, videoUrl ) {
if (videoUrl) {
if (type === 'start_video' ) {
ensureVideoCard (videoUrl);
setStatus (videoUrl, '分析中' , 'status-running' );
return ;
}
if (type === 'api_response' ) {
appendMarkdown (videoUrl, content);
return ;
}
if (type === 'end_video' ) {
setStatus (videoUrl, '完成' , 'status-done' );
return ;
}
if (type === 'error' ) {
setStatus (videoUrl, '错误' , 'status-error' );
const state = ensureVideoCard (videoUrl);
const err = document . createElement ( 'div' );
err. className = 'stream-line stream-error' ;
err. textContent = String (content);
state. contentEl . appendChild (err);
return ;
}
}
if (type === 'all_complete' ) {
showToast ( '全部视频处理完成' );
return ;
}
if (type === 'error' ) {
showToast ( String (content));
return ;
}
}
function showToast ( text ) {
if (!toast) return ;
toast. textContent = text;
toast. classList . add ( 'show' );
setTimeout ( () => toast. classList . remove ( 'show' ), 2000 );
}
});
</ script >
</ body >
</ html > 代码文件放到对应位置,app.py 放到项目根目录,index.html 放到 templates 目录下。
在 app.py 中填入 api_key(百炼平台申请的密钥)
不论国产 AI coding 工具,还是海外,进化的都非常快,可见今年的热度,对于普通人来说,让自己动起来,机会一直在。