AI与Web

AI在Web中的应用

人工智能技术正在深刻改变Web开发和应用的方式。

东巴文(db-w.cn) 认为:AI技术正在重塑Web开发的方方面面,从代码生成到用户体验优化,AI正在成为Web开发的重要工具。掌握AI在Web中的应用,是现代Web开发者的必备技能。

AI技术概述

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI在Web中的应用 - 东巴文</title>
    
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #764ba2;
            margin: 30px 0 15px;
            border-left: 4px solid #764ba2;
            padding-left: 15px;
        }
        
        .ai-demo {
            background: #f8f9fa;
            padding: 20px;
            border: 2px solid #ddd;
            margin: 15px 0;
            border-radius: 10px;
        }
        
        .ai-demo h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
        
        .ai-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .ai-table th,
        .ai-table td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
        }
        
        .ai-table th {
            background: #667eea;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>AI在Web中的应用</h1>
        
        <h2>AI技术分类</h2>
        
        <div class="ai-demo">
            <h3>Web中的AI技术</h3>
            <table class="ai-table">
                <thead>
                    <tr>
                        <th>技术类型</th>
                        <th>应用场景</th>
                        <th>示例</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>机器学习</strong></td>
                        <td>预测、分类、推荐</td>
                        <td>推荐系统、垃圾邮件过滤</td>
                    </tr>
                    <tr>
                        <td><strong>深度学习</strong></td>
                        <td>图像识别、语音识别</td>
                        <td>人脸识别、语音助手</td>
                    </tr>
                    <tr>
                        <td><strong>自然语言处理</strong></td>
                        <td>文本分析、翻译、对话</td>
                        <td>聊天机器人、机器翻译</td>
                    </tr>
                    <tr>
                        <td><strong>计算机视觉</strong></td>
                        <td>图像处理、视频分析</td>
                        <td>图像搜索、AR滤镜</td>
                    </tr>
                    <tr>
                        <td><strong>生成式AI</strong></td>
                        <td>内容生成、创意设计</td>
                        <td>文本生成、图像生成</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <h2>浏览器端AI</h2>
        
        <div class="ai-demo">
            <h3>TensorFlow.js示例</h3>
            <div class="code-block">
                <pre>
// TensorFlow.js - 在浏览器中运行机器学习模型

// 1. 引入TensorFlow.js
// &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"&gt;&lt;/script&gt;

// 2. 创建简单模型
async function createModel() {
    // 创建序贯模型
    const model = tf.sequential();
    
    // 添加层
    model.add(tf.layers.dense({
        units: 1,
        inputShape: [1]
    }));
    
    // 编译模型
    model.compile({
        optimizer: 'sgd',
        loss: 'meanSquaredError'
    });
    
    return model;
}

// 3. 训练模型
async function trainModel(model) {
    // 准备数据
    const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
    const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);
    
    // 训练
    await model.fit(xs, ys, {
        epochs: 100,
        callbacks: {
            onEpochEnd: (epoch, logs) =&gt; {
                console.log(`Epoch ${epoch}: loss = ${logs.loss}`);
            }
        }
    });
    
    // 清理内存
    xs.dispose();
    ys.dispose();
}

// 4. 使用模型预测
async function predict(model, input) {
    const prediction = model.predict(tf.tensor2d([input], [1, 1]));
    const result = prediction.dataSync()[0];
    prediction.dispose();
    return result;
}

// 完整示例
async function run() {
    const model = await createModel();
    await trainModel(model);
    
    const result = await predict(model, 5);
    console.log('预测结果:', result); // 应该接近9
    
    model.dispose();
}

// 5. 图像分类示例
async function classifyImage() {
    // 加载预训练模型
    const model = await mobilenet.load();
    
    // 获取图像
    const img = document.getElementById('image');
    
    // 分类
    const predictions = await model.classify(img);
    
    console.log('分类结果:', predictions);
    /*
    [
        { className: 'golden retriever', probability: 0.92 },
        { className: 'cocker spaniel', probability: 0.05 },
        { className: 'Irish setter', probability: 0.02 }
    ]
    */
}

// 6. 实时对象检测
async function detectObjects() {
    const model = await cocoSsd.load();
    
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');
    
    async function detect() {
        const predictions = await model.detect(video);
        
        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 绘制检测结果
        predictions.forEach(prediction =&gt; {
            const [x, y, width, height] = prediction.bbox;
            
            ctx.strokeStyle = '#00FFFF';
            ctx.lineWidth = 4;
            ctx.strokeRect(x, y, width, height);
            
            ctx.fillStyle = '#00FFFF';
            ctx.fillText(
                `${prediction.class} ${Math.round(prediction.score * 100)}%`,
                x, y - 10
            );
        });
        
        requestAnimationFrame(detect);
    }
    
    detect();
}
                </pre>
            </div>
        </div>
        
        <h2>AI API集成</h2>
        
        <div class="ai-demo">
            <h3>调用AI服务API</h3>
            <div class="code-block">
                <pre>
// 1. OpenAI API集成
async function callOpenAI(prompt) {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            model: 'gpt-3.5-turbo',
            messages: [
                { role: 'system', content: '你是一个有帮助的助手。' },
                { role: 'user', content: prompt }
            ],
            temperature: 0.7
        })
    });
    
    const data = await response.json();
    return data.choices[0].message.content;
}

// 2. 流式响应
async function streamOpenAI(prompt) {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            model: 'gpt-3.5-turbo',
            messages: [
                { role: 'user', content: prompt }
            ],
            stream: true
        })
    });
    
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    
    while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line =&gt; line.trim() !== '');
        
        for (const line of lines) {
            if (line.startsWith('data: ')) {
                const data = line.slice(6);
                if (data === '[DONE]') continue;
                
                const parsed = JSON.parse(data);
                const content = parsed.choices[0]?.delta?.content || '';
                console.log(content); // 实时输出
            }
        }
    }
}

// 3. 图像生成
async function generateImage(prompt) {
    const response = await fetch('https://api.openai.com/v1/images/generations', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            prompt: prompt,
            n: 1,
            size: '1024x1024'
        })
    });
    
    const data = await response.json();
    return data.data[0].url;
}

// 4. 语音识别
async function transcribeAudio(audioFile) {
    const formData = new FormData();
    formData.append('file', audioFile);
    formData.append('model', 'whisper-1');
    
    const response = await fetch('https://api.openai.com/v1/audio/transcriptions', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${API_KEY}`
        },
        body: formData
    });
    
    const data = await response.json();
    return data.text;
}

// 5. 嵌入向量
async function getEmbedding(text) {
    const response = await fetch('https://api.openai.com/v1/embeddings', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${API_KEY}`
        },
        body: JSON.stringify({
            model: 'text-embedding-ada-002',
            input: text
        })
    });
    
    const data = await response.json();
    return data.data[0].embedding;
}

// 6. 语义搜索
async function semanticSearch(query, documents) {
    // 获取查询向量
    const queryEmbedding = await getEmbedding(query);
    
    // 获取文档向量
    const documentEmbeddings = await Promise.all(
        documents.map(doc =&gt; getEmbedding(doc))
    );
    
    // 计算相似度
    const similarities = documentEmbeddings.map((embedding, i) =&gt; ({
        index: i,
        document: documents[i],
        similarity: cosineSimilarity(queryEmbedding, embedding)
    }));
    
    // 排序
    return similarities.sort((a, b) =&gt; b.similarity - a.similarity);
}

// 余弦相似度
function cosineSimilarity(a, b) {
    const dotProduct = a.reduce((sum, val, i) =&gt; sum + val * b[i], 0);
    const magnitudeA = Math.sqrt(a.reduce((sum, val) =&gt; sum + val * val, 0));
    const magnitudeB = Math.sqrt(b.reduce((sum, val) =&gt; sum + val * val, 0));
    return dotProduct / (magnitudeA * magnitudeB);
}
                </pre>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px;">
            <strong>东巴文提示:</strong>AI技术正在改变Web开发的方式。从浏览器端机器学习到云端AI服务,AI为Web应用带来了新的可能性。掌握AI在Web中的应用,能构建更智能、更强大的Web应用。
        </div>
    </div>
</body>
</html>

智能Web应用

构建智能Web应用需要整合多种AI技术。

应用示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能Web应用 - 东巴文</title>
    
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #764ba2;
            margin: 30px 0 15px;
            border-left: 4px solid #764ba2;
            padding-left: 15px;
        }
        
        .app-demo {
            background: #f8f9fa;
            padding: 20px;
            border: 2px solid #ddd;
            margin: 15px 0;
            border-radius: 10px;
        }
        
        .app-demo h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>智能Web应用</h1>
        
        <h2>智能聊天机器人</h2>
        
        <div class="app-demo">
            <h3>AI聊天界面</h3>
            <div class="code-block">
                <pre>
&lt;!DOCTYPE html&gt;
&lt;html lang="zh-CN"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;AI聊天机器人 - 东巴文&lt;/title&gt;
    
    &lt;style&gt;
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .chat-container {
            max-width: 600px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        
        .chat-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            text-align: center;
        }
        
        .chat-messages {
            height: 400px;
            overflow-y: auto;
            padding: 20px;
        }
        
        .message {
            margin: 10px 0;
            padding: 10px 15px;
            border-radius: 10px;
            max-width: 80%;
        }
        
        .message.user {
            background: #667eea;
            color: white;
            margin-left: auto;
        }
        
        .message.assistant {
            background: #f0f0f0;
            color: #333;
        }
        
        .chat-input {
            display: flex;
            padding: 15px;
            border-top: 1px solid #ddd;
        }
        
        .chat-input input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-right: 10px;
        }
        
        .chat-input button {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .chat-input button:hover {
            background: #764ba2;
        }
        
        .typing {
            display: none;
            color: #999;
            font-style: italic;
            margin: 10px 0;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="chat-container"&gt;
        &lt;div class="chat-header"&gt;
            &lt;h1&gt;AI助手&lt;/h1&gt;
            &lt;p&gt;东巴文智能聊天机器人&lt;/p&gt;
        &lt;/div&gt;
        
        &lt;div class="chat-messages" id="messages"&gt;
            &lt;div class="message assistant"&gt;
                你好!我是AI助手,有什么可以帮助你的吗?
            &lt;/div&gt;
        &lt;/div&gt;
        
        &lt;div class="typing" id="typing"&gt;AI正在输入...&lt;/div&gt;
        
        &lt;div class="chat-input"&gt;
            &lt;input type="text" id="userInput" placeholder="输入你的问题..." /&gt;
            &lt;button onclick="sendMessage()"&gt;发送&lt;/button&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    
    &lt;script&gt;
        const messagesDiv = document.getElementById('messages');
        const userInput = document.getElementById('userInput');
        const typingDiv = document.getElementById('typing');
        
        // 添加消息
        function addMessage(content, isUser) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user' : 'assistant'}`;
            messageDiv.textContent = content;
            messagesDiv.appendChild(messageDiv);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }
        
        // 发送消息
        async function sendMessage() {
            const message = userInput.value.trim();
            if (!message) return;
            
            // 添加用户消息
            addMessage(message, true);
            userInput.value = '';
            
            // 显示输入中
            typingDiv.style.display = 'block';
            
            try {
                // 调用AI API
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ message })
                });
                
                const data = await response.json();
                
                // 添加AI回复
                addMessage(data.reply, false);
            } catch (error) {
                addMessage('抱歉,出现了错误。请稍后再试。', false);
            } finally {
                typingDiv.style.display = 'none';
            }
        }
        
        // 回车发送
        userInput.addEventListener('keypress', (e) =&gt; {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
                </pre>
            </div>
        </div>
        
        <h2>智能图像处理</h2>
        
        <div class="app-demo">
            <h3>图像识别应用</h3>
            <div class="code-block">
                <pre>
&lt;!DOCTYPE html&gt;
&lt;html lang="zh-CN"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;智能图像处理 - 东巴文&lt;/title&gt;
    
    &lt;style&gt;
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            text-align: center;
        }
        
        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin: 20px 0;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .upload-area:hover {
            background: #f8f9fa;
        }
        
        .preview-container {
            position: relative;
            margin: 20px 0;
        }
        
        .preview-container img {
            max-width: 100%;
            border-radius: 10px;
        }
        
        .results {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .result-item {
            display: flex;
            justify-content: space-between;
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        
        .confidence-bar {
            width: 200px;
            height: 20px;
            background: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }
        
        .confidence-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            transition: width 0.3s;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div class="container"&gt;
        &lt;h1&gt;智能图像识别&lt;/h1&gt;
        
        &lt;div class="upload-area" id="uploadArea"&gt;
            &lt;p&gt;点击或拖拽上传图片&lt;/p&gt;
            &lt;input type="file" id="fileInput" accept="image/*" style="display: none;" /&gt;
        &lt;/div&gt;
        
        &lt;div class="preview-container" id="previewContainer" style="display: none;"&gt;
            &lt;img id="previewImage" /&gt;
        &lt;/div&gt;
        
        &lt;div class="results" id="results" style="display: none;"&gt;
            &lt;h2&gt;识别结果&lt;/h2&gt;
            &lt;div id="resultsList"&gt;&lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
    
    &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"&gt;&lt;/script&gt;
    &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet"&gt;&lt;/script&gt;
    
    &lt;script&gt;
        let model;
        
        // 加载模型
        async function loadModel() {
            model = await mobilenet.load();
            console.log('模型加载完成');
        }
        
        loadModel();
        
        const uploadArea = document.getElementById('uploadArea');
        const fileInput = document.getElementById('fileInput');
        const previewContainer = document.getElementById('previewContainer');
        const previewImage = document.getElementById('previewImage');
        const results = document.getElementById('results');
        const resultsList = document.getElementById('resultsList');
        
        // 点击上传
        uploadArea.addEventListener('click', () =&gt; {
            fileInput.click();
        });
        
        // 拖拽上传
        uploadArea.addEventListener('dragover', (e) =&gt; {
            e.preventDefault();
            uploadArea.style.background = '#f0f0f0';
        });
        
        uploadArea.addEventListener('dragleave', () =&gt; {
            uploadArea.style.background = '';
        });
        
        uploadArea.addEventListener('drop', (e) =&gt; {
            e.preventDefault();
            uploadArea.style.background = '';
            const file = e.dataTransfer.files[0];
            if (file &amp;&amp; file.type.startsWith('image/')) {
                processImage(file);
            }
        });
        
        // 文件选择
        fileInput.addEventListener('change', (e) =&gt; {
            const file = e.target.files[0];
            if (file) {
                processImage(file);
            }
        });
        
        // 处理图像
        function processImage(file) {
            const reader = new FileReader();
            reader.onload = async (e) =&gt; {
                // 显示预览
                previewImage.src = e.target.result;
                previewContainer.style.display = 'block';
                
                // 识别图像
                if (model) {
                    const predictions = await model.classify(previewImage);
                    displayResults(predictions);
                }
            };
            reader.readAsDataURL(file);
        }
        
        // 显示结果
        function displayResults(predictions) {
            resultsList.innerHTML = '';
            
            predictions.forEach(prediction =&gt; {
                const confidence = Math.round(prediction.probability * 100);
                
                const item = document.createElement('div');
                item.className = 'result-item';
                item.innerHTML = `
                    &lt;span&gt;${prediction.className}&lt;/span&gt;
                    &lt;div class="confidence-bar"&gt;
                        &lt;div class="confidence-fill" style="width: ${confidence}%"&gt;&lt;/div&gt;
                    &lt;/div&gt;
                    &lt;span&gt;${confidence}%&lt;/span&gt;
                `;
                resultsList.appendChild(item);
            });
            
            results.style.display = 'block';
        }
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
                </pre>
            </div>
        </div>
        
        <h2>智能推荐系统</h2>
        
        <div class="app-demo">
            <h3>个性化推荐</h3>
            <div class="code-block">
                <pre>
// 推荐系统示例

// 1. 协同过滤
class CollaborativeFiltering {
    constructor() {
        this.userRatings = {};
        this.itemUsers = {};
    }
    
    // 添加评分
    addRating(userId, itemId, rating) {
        if (!this.userRatings[userId]) {
            this.userRatings[userId] = {};
        }
        this.userRatings[userId][itemId] = rating;
        
        if (!this.itemUsers[itemId]) {
            this.itemUsers[itemId] = new Set();
        }
        this.itemUsers[itemId].add(userId);
    }
    
    // 计算相似度
    similarity(user1, user2) {
        const ratings1 = this.userRatings[user1];
        const ratings2 = this.userRatings[user2];
        
        let sum1 = 0, sum2 = 0, sumProduct = 0;
        let count = 0;
        
        for (const item in ratings1) {
            if (item in ratings2) {
                sum1 += ratings1[item];
                sum2 += ratings2[item];
                sumProduct += ratings1[item] * ratings2[item];
                count++;
            }
        }
        
        if (count === 0) return 0;
        
        const mean1 = sum1 / count;
        const mean2 = sum2 / count;
        
        let numerator = 0;
        let denominator1 = 0;
        let denominator2 = 0;
        
        for (const item in ratings1) {
            if (item in ratings2) {
                const diff1 = ratings1[item] - mean1;
                const diff2 = ratings2[item] - mean2;
                
                numerator += diff1 * diff2;
                denominator1 += diff1 * diff1;
                denominator2 += diff2 * diff2;
            }
        }
        
        const denominator = Math.sqrt(denominator1 * denominator2);
        return denominator === 0 ? 0 : numerator / denominator;
    }
    
    // 推荐物品
    recommend(userId, n = 5) {
        const userRatings = this.userRatings[userId];
        if (!userRatings) return [];
        
        // 找到相似用户
        const similarities = [];
        for (const otherUser in this.userRatings) {
            if (otherUser !== userId) {
                const sim = this.similarity(userId, otherUser);
                similarities.push({ userId: otherUser, similarity: sim });
            }
        }
        
        similarities.sort((a, b) =&gt; b.similarity - a.similarity);
        
        // 推荐未评分物品
        const recommendations = {};
        
        for (const { userId: otherUser, similarity } of similarities.slice(0, 10)) {
            const otherRatings = this.userRatings[otherUser];
            
            for (const item in otherRatings) {
                if (!(item in userRatings)) {
                    if (!recommendations[item]) {
                        recommendations[item] = { score: 0, count: 0 };
                    }
                    
                    recommendations[item].score += otherRatings[item] * similarity;
                    recommendations[item].count++;
                }
            }
        }
        
        // 排序
        const sorted = Object.entries(recommendations)
            .map(([item, data]) =&gt; ({
                item,
                score: data.score / data.count
            }))
            .sort((a, b) =&gt; b.score - a.score);
        
        return sorted.slice(0, n);
    }
}

// 2. 内容推荐
class ContentBasedRecommender {
    constructor() {
        this.items = {};
        this.userProfiles = {};
    }
    
    // 添加物品
    addItem(itemId, features) {
        this.items[itemId] = features;
    }
    
    // 更新用户画像
    updateUserProfile(userId, itemId, rating) {
        if (!this.userProfiles[userId]) {
            this.userProfiles[userId] = {};
        }
        
        const features = this.items[itemId];
        for (const feature in features) {
            if (!this.userProfiles[userId][feature]) {
                this.userProfiles[userId][feature] = 0;
            }
            this.userProfiles[userId][feature] += features[feature] * rating;
        }
    }
    
    // 推荐物品
    recommend(userId, n = 5) {
        const profile = this.userProfiles[userId];
        if (!profile) return [];
        
        const scores = [];
        
        for (const itemId in this.items) {
            const features = this.items[itemId];
            let score = 0;
            
            for (const feature in features) {
                if (profile[feature]) {
                    score += features[feature] * profile[feature];
                }
            }
            
            scores.push({ item: itemId, score });
        }
        
        scores.sort((a, b) =&gt; b.score - a.score);
        return scores.slice(0, n);
    }
}

// 使用示例
const cf = new CollaborativeFiltering();

// 添加评分数据
cf.addRating('user1', 'item1', 5);
cf.addRating('user1', 'item2', 3);
cf.addRating('user2', 'item1', 4);
cf.addRating('user2', 'item3', 5);

// 获取推荐
const recommendations = cf.recommend('user1');
console.log('推荐结果:', recommendations);
                </pre>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px;">
            <strong>东巴文提示:</strong>智能Web应用正在改变用户体验。从聊天机器人到图像识别,从个性化推荐到智能搜索,AI技术为Web应用带来了新的可能性。掌握这些技术,能构建更智能、更人性化的Web应用。
        </div>
    </div>
</body>
</html>

AI辅助开发

AI工具正在改变Web开发的工作流程。

开发工具

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI辅助开发 - 东巴文</title>
    
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #764ba2;
            margin: 30px 0 15px;
            border-left: 4px solid #764ba2;
            padding-left: 15px;
        }
        
        .tool-demo {
            background: #f8f9fa;
            padding: 20px;
            border: 2px solid #ddd;
            margin: 15px 0;
            border-radius: 10px;
        }
        
        .tool-demo h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
        
        .tool-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .tool-table th,
        .tool-table td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
        }
        
        .tool-table th {
            background: #667eea;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>AI辅助开发</h1>
        
        <h2>AI开发工具</h2>
        
        <div class="tool-demo">
            <h3>主流AI开发工具</h3>
            <table class="tool-table">
                <thead>
                    <tr>
                        <th>工具类型</th>
                        <th>代表工具</th>
                        <th>功能</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td><strong>代码补全</strong></td>
                        <td>GitHub Copilot, Tabnine, CodeWhisperer</td>
                        <td>智能代码补全,代码生成</td>
                    </tr>
                    <tr>
                        <td><strong>代码审查</strong></td>
                        <td>CodeGuru, DeepSource, Codacy</td>
                        <td>代码质量分析,安全检查</td>
                    </tr>
                    <tr>
                        <td><strong>测试生成</strong></td>
                        <td>Diffblue Cover, Testim, Mabl</td>
                        <td>自动生成测试用例</td>
                    </tr>
                    <tr>
                        <td><strong>文档生成</strong></td>
                        <td>Docstring AI, Mintlify, Swimm</td>
                        <td>自动生成代码文档</td>
                    </tr>
                    <tr>
                        <td><strong>UI设计</strong></td>
                        <td>Figma AI, Galileo AI, Uizard</td>
                        <td>AI辅助UI设计</td>
                    </tr>
                </tbody>
            </table>
        </div>
        
        <h2>代码生成</h2>
        
        <div class="tool-demo">
            <h3>AI代码生成示例</h3>
            <div class="code-block">
                <pre>
// AI辅助代码生成

// 1. 函数生成
// 提示: "编写一个函数,验证邮箱格式"
function validateEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// 2. 组件生成
// 提示: "创建一个React按钮组件,支持不同样式"
function Button({ children, variant = 'primary', onClick, disabled }) {
    const styles = {
        primary: {
            background: '#667eea',
            color: 'white'
        },
        secondary: {
            background: '#764ba2',
            color: 'white'
        },
        outline: {
            background: 'transparent',
            border: '2px solid #667eea',
            color: '#667eea'
        }
    };
    
    return (
        &lt;button
            style={{
                padding: '10px 20px',
                borderRadius: '5px',
                border: 'none',
                cursor: disabled ? 'not-allowed' : 'pointer',
                opacity: disabled ? 0.5 : 1,
                ...styles[variant]
            }}
            onClick={onClick}
            disabled={disabled}
        &gt;
            {children}
        &lt;/button&gt;
    );
}

// 3. API调用
// 提示: "创建一个获取用户数据的API函数"
async function fetchUserData(userId) {
    try {
        const response = await fetch(`/api/users/${userId}`);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('获取用户数据失败:', error);
        throw error;
    }
}

// 4. 表单验证
// 提示: "创建一个表单验证函数,验证用户名、密码和确认密码"
function validateForm(formData) {
    const errors = {};
    
    // 用户名验证
    if (!formData.username) {
        errors.username = '用户名不能为空';
    } else if (formData.username.length &lt; 3) {
        errors.username = '用户名至少3个字符';
    }
    
    // 密码验证
    if (!formData.password) {
        errors.password = '密码不能为空';
    } else if (formData.password.length &lt; 8) {
        errors.password = '密码至少8个字符';
    } else if (!/[A-Z]/.test(formData.password)) {
        errors.password = '密码必须包含大写字母';
    } else if (!/[0-9]/.test(formData.password)) {
        errors.password = '密码必须包含数字';
    }
    
    // 确认密码验证
    if (formData.password !== formData.confirmPassword) {
        errors.confirmPassword = '两次密码不一致';
    }
    
    return {
        isValid: Object.keys(errors).length === 0,
        errors
    };
}

// 5. 数据处理
// 提示: "创建一个函数,对数组进行分组"
function groupBy(array, key) {
    return array.reduce((result, item) =&gt; {
        const groupKey = typeof key === 'function' ? key(item) : item[key];
        
        if (!result[groupKey]) {
            result[groupKey] = [];
        }
        
        result[groupKey].push(item);
        
        return result;
    }, {});
}

// 使用示例
const users = [
    { name: 'Alice', age: 25, department: 'Engineering' },
    { name: 'Bob', age: 30, department: 'Marketing' },
    { name: 'Charlie', age: 25, department: 'Engineering' }
];

const grouped = groupBy(users, 'department');
console.log(grouped);
/*
{
    Engineering: [
        { name: 'Alice', age: 25, department: 'Engineering' },
        { name: 'Charlie', age: 25, department: 'Engineering' }
    ],
    Marketing: [
        { name: 'Bob', age: 30, department: 'Marketing' }
    ]
}
*/
                </pre>
            </div>
        </div>
        
        <h2>测试自动化</h2>
        
        <div class="tool-demo">
            <h3>AI测试生成</h3>
            <div class="code-block">
                <pre>
// AI辅助测试生成

// 1. 单元测试
// 提示: "为validateEmail函数生成单元测试"
describe('validateEmail', () =&gt; {
    test('应该返回true对于有效的邮箱', () =&gt; {
        expect(validateEmail('test@example.com')).toBe(true);
        expect(validateEmail('user.name@domain.co.uk')).toBe(true);
    });
    
    test('应该返回false对于无效的邮箱', () =&gt; {
        expect(validateEmail('invalid-email')).toBe(false);
        expect(validateEmail('test@')).toBe(false);
        expect(validateEmail('@example.com')).toBe(false);
    });
    
    test('应该返回false对于空字符串', () =&gt; {
        expect(validateEmail('')).toBe(false);
    });
});

// 2. 集成测试
// 提示: "为用户API生成集成测试"
describe('User API', () =&gt; {
    test('GET /api/users/:id 应该返回用户数据', async () =&gt; {
        const response = await request(app).get('/api/users/1');
        
        expect(response.status).toBe(200);
        expect(response.body).toHaveProperty('id', 1);
        expect(response.body).toHaveProperty('name');
        expect(response.body).toHaveProperty('email');
    });
    
    test('POST /api/users 应该创建新用户', async () =&gt; {
        const newUser = {
            name: 'Test User',
            email: 'test@example.com'
        };
        
        const response = await request(app)
            .post('/api/users')
            .send(newUser);
        
        expect(response.status).toBe(201);
        expect(response.body).toHaveProperty('id');
        expect(response.body.name).toBe(newUser.name);
    });
});

// 3. E2E测试
// 提示: "为登录流程生成E2E测试"
describe('登录流程', () =&gt; {
    test('用户应该能够成功登录', async () =&gt; {
        await page.goto('https://example.com/login');
        
        await page.type('#username', 'testuser');
        await page.type('#password', 'password123');
        await page.click('#login-button');
        
        await page.waitForNavigation();
        
        const url = page.url();
        expect(url).toContain('/dashboard');
    });
    
    test('应该显示错误消息对于无效凭据', async () =&gt; {
        await page.goto('https://example.com/login');
        
        await page.type('#username', 'invalid');
        await page.type('#password', 'wrong');
        await page.click('#login-button');
        
        await page.waitForSelector('.error-message');
        
        const errorMessage = await page.$eval('.error-message', el =&gt; el.textContent);
        expect(errorMessage).toContain('用户名或密码错误');
    });
});
                </pre>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px;">
            <strong>东巴文提示:</strong>AI工具正在改变Web开发的工作流程。从代码生成到测试自动化,AI辅助开发能提高开发效率,减少重复劳动。但AI工具是辅助而非替代,开发者仍需理解代码逻辑,保证代码质量。
        </div>
    </div>
</body>
</html>

学习检验

完成本章学习后,请尝试回答以下问题:

  1. 选择题: 以下哪个不是浏览器端机器学习库?

    • A. TensorFlow.js
    • B. Brain.js
    • C. PyTorch
    • D. ONNX.js
  2. 填空题: OpenAI的GPT模型主要用于____处理。

  3. 简答题: 协同过滤和内容推荐的原理分别是什么?各有什么优缺点?

  4. 实践题: 使用TensorFlow.js创建一个简单的图像分类应用。

  5. 应用题: 设计一个智能Web应用的架构,说明如何集成AI技术。