Merge "personal page"
diff --git a/1.txt b/1.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/1.txt
diff --git a/API/API-TRM/.gitignore b/API/API-TRM/.gitignore
new file mode 100644
index 0000000..efc0820
--- /dev/null
+++ b/API/API-TRM/.gitignore
@@ -0,0 +1,10 @@
+node_modules/
+.vscode/
+dist/
+*.log
+.DS_Store
+.env
+.env.local
+.env.production
+.env.development
+package-lock.json
diff --git a/API/API-TRM/TRM/Back/README.md b/API/API-TRM/TRM/Back/README.md
new file mode 100644
index 0000000..cef32ef
--- /dev/null
+++ b/API/API-TRM/TRM/Back/README.md
@@ -0,0 +1,70 @@
+# Back-end Flask Project
+
+## Overview
+This project is a basic Flask application structure designed to demonstrate the organization of a Flask project. It includes essential components such as routes, models, templates, and configuration files.
+
+## Project Structure
+```
+Back
+├── app
+│   ├── __init__.py
+│   ├── routes.py
+│   ├── models.py
+│   └── templates
+│       ├── base.html
+│       └── index.html
+├── tests
+│   └── test_app.py
+├── app.py
+├── config.py
+├── requirements.txt
+└── README.md
+```
+
+## Setup Instructions
+
+1. **Clone the repository**:
+   ```
+   git clone <repository-url>
+   cd Back
+   ```
+
+2. **Create a virtual environment**:
+   ```
+   python -m venv venv
+   ```
+
+3. **Activate the virtual environment**:
+   - On Windows:
+     ```
+     venv\Scripts\activate
+     ```
+   - On macOS/Linux:
+     ```
+     source venv/bin/activate
+     ```
+
+4. **Install dependencies**:
+   ```
+   pip install -r requirements.txt
+   ```
+
+5. **Run the application**:
+   ```
+   python app.py
+   ```
+
+## Usage
+Once the application is running, you can access it at `http://127.0.0.1:5000/`. The index page will be displayed.
+
+## Testing
+To run the tests, ensure the virtual environment is activated and execute:
+```
+pytest tests/test_app.py
+```
+
+## Contributing
+Feel free to submit issues or pull requests for improvements or bug fixes.
+
+## License
+This project is licensed under the MIT License.
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/__pycache__/__init__.cpython-312.pyc b/API/API-TRM/TRM/Back/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..aad3f55
--- /dev/null
+++ b/API/API-TRM/TRM/Back/__pycache__/__init__.cpython-312.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/__pycache__/config.cpython-310.pyc b/API/API-TRM/TRM/Back/__pycache__/config.cpython-310.pyc
new file mode 100644
index 0000000..02c50aa
--- /dev/null
+++ b/API/API-TRM/TRM/Back/__pycache__/config.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app.py b/API/API-TRM/TRM/Back/app.py
new file mode 100644
index 0000000..5465905
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app.py
@@ -0,0 +1,6 @@
+from app import create_app
+
+app = create_app()
+
+if __name__ == "__main__":
+    app.run(debug=True,port=5713,host='0.0.0.0')
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/__init__.py b/API/API-TRM/TRM/Back/app/__init__.py
new file mode 100644
index 0000000..5587d2a
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/__init__.py
@@ -0,0 +1,15 @@
+from flask import Flask
+
+def create_app():
+    app = Flask(__name__)
+    
+    # Load configuration
+    app.config.from_object('config.Config')
+
+    # Register blueprints or routes
+    from .routes import main as main_blueprint
+    app.register_blueprint(main_blueprint)
+
+    return app
+
+app = create_app()
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/__pycache__/__init__.cpython-310.pyc b/API/API-TRM/TRM/Back/app/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000..19d389d
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/__pycache__/__init__.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/__pycache__/__init__.cpython-312.pyc b/API/API-TRM/TRM/Back/app/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..eaa8e71
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/__pycache__/__init__.cpython-312.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/__pycache__/routes.cpython-310.pyc b/API/API-TRM/TRM/Back/app/__pycache__/routes.cpython-310.pyc
new file mode 100644
index 0000000..af72069
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/__pycache__/routes.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/functions/Fpost.py b/API/API-TRM/TRM/Back/app/functions/Fpost.py
new file mode 100644
index 0000000..e51cf5c
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/functions/Fpost.py
@@ -0,0 +1,23 @@
+from ..models.users import User as users
+from ..models.post import Post as post
+
+from sqlalchemy.orm import Session
+class Fpost:
+    def __init__(self,session:Session):
+        self.session=session
+        return
+    
+
+    def getlist(self):
+        results = self.session.query(post.id, post.title,post.status)
+        return results
+    def getpost(self,postid):
+        res=self.session.query(post).filter(post.id==postid).first()
+        return res
+    def checkid(self,userid):
+        res=self.session.query(users).filter(users.id==userid).first()
+        if(not res):
+            return False
+        if res.role !='superadmin':
+            return False
+        return True
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/functions/__pycache__/Fpost.cpython-310.pyc b/API/API-TRM/TRM/Back/app/functions/__pycache__/Fpost.cpython-310.pyc
new file mode 100644
index 0000000..2b6cd6d
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/functions/__pycache__/Fpost.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/models/__init__.py b/API/API-TRM/TRM/Back/app/models/__init__.py
new file mode 100644
index 0000000..f726a19
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/__init__.py
@@ -0,0 +1,8 @@
+from sqlalchemy.ext.declarative import declarative_base
+
+Base = declarative_base()
+
+# 先定义好 Base,再把所有 model import 进来,让 SQLAlchemy 一次性注册它们
+from .users import User
+from .topics import Topic
+from .post   import Post
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/models/__pycache__/__init__.cpython-310.pyc b/API/API-TRM/TRM/Back/app/models/__pycache__/__init__.cpython-310.pyc
new file mode 100644
index 0000000..f30dbeb
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/__pycache__/__init__.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/models/__pycache__/post.cpython-310.pyc b/API/API-TRM/TRM/Back/app/models/__pycache__/post.cpython-310.pyc
new file mode 100644
index 0000000..263b592
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/__pycache__/post.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/models/__pycache__/topics.cpython-310.pyc b/API/API-TRM/TRM/Back/app/models/__pycache__/topics.cpython-310.pyc
new file mode 100644
index 0000000..e291b93
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/__pycache__/topics.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/models/__pycache__/users.cpython-310.pyc b/API/API-TRM/TRM/Back/app/models/__pycache__/users.cpython-310.pyc
new file mode 100644
index 0000000..e6286c3
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/__pycache__/users.cpython-310.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/app/models/post.py b/API/API-TRM/TRM/Back/app/models/post.py
new file mode 100644
index 0000000..041e263
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/post.py
@@ -0,0 +1,111 @@
+from .users import User
+from . import Base
+
+from sqlalchemy import (
+    Column, Integer, String, Text, JSON, Enum,
+    TIMESTAMP, ForeignKey, Index, func, text
+)
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+
+
+class Post(Base):
+    __tablename__ = 'posts'
+    __table_args__ = (
+        # 索引
+        Index('idx_posts_heat', 'heat'),
+        # MySQL 引擎、字符集、校对规则、表注释
+        {
+            'mysql_engine': 'InnoDB',
+            'mysql_charset': 'utf8mb4',
+            'mysql_collate': 'utf8mb4_general_ci',
+            'comment': '内容帖子表'
+        }
+    )
+
+    def to_dict(self):
+        return {
+            'id': self.id if self.id else None,
+            'user_id': self.user_id if self.user_id else None,
+            'topic_id': self.topic_id if self.topic_id else None,
+            'type': self.type if self.type else None,
+            'title': self.title if self.title else None,
+            'content': self.content if self.content else None,
+            'media_urls': self.media_urls if self.media_urls else None,
+            'status': self.status if self.status else None,
+            'heat': self.heat if self.heat else None,
+            'created_at': self.created_at.isoformat() if self.created_at else None,
+            'updated_at': self.updated_at.isoformat() if self.updated_at else None
+        }
+
+
+    id = Column(
+        Integer,
+        primary_key=True,
+        autoincrement=True,
+        comment='帖子ID'
+    )
+    user_id = Column(
+        Integer,
+        ForeignKey('users.id', ondelete='CASCADE'),
+        nullable=False,
+        index=True,
+        comment='作者ID'
+    )
+    topic_id = Column(
+        Integer,
+        ForeignKey('topics.id', ondelete='SET NULL'),
+        nullable=True,
+        index=True,
+        comment='所属话题ID'
+    )
+    type = Column(
+        Enum('text', 'image', 'video', 'document', name='post_type'),
+        nullable=False,
+        server_default=text("'text'"),
+        comment='内容类型'
+    )
+    title = Column(
+        String(255),
+        nullable=False,
+        comment='标题'
+    )
+    content = Column(
+        Text,
+        nullable=False,
+        comment='正文内容'
+    )
+    media_urls = Column(
+        JSON,
+        nullable=True,
+        comment='媒体资源URL数组'
+    )
+    status = Column(
+        Enum('draft', 'pending', 'published', 'deleted', 'rejected', name='post_status'),
+        nullable=False,
+        server_default=text("'draft'"),
+        comment='状态'
+    )
+    heat = Column(
+        Integer,
+        nullable=False,
+        server_default=text('0'),
+        comment='热度值'
+    )
+    created_at = Column(
+        TIMESTAMP,
+        nullable=True,
+        server_default=func.current_timestamp(),
+        comment='创建时间'
+    )
+    updated_at = Column(
+        TIMESTAMP,
+        nullable=True,
+        server_default=func.current_timestamp(),
+        onupdate=func.current_timestamp(),
+        comment='更新时间'
+    )
+
+    # 可选:与 User/Topic 模型的关系(需要在 User、Topic 中也定义 back_populates)
+    # user = relationship('User', back_populates='posts')
+    # topic = relationship('Topic', back_populates='posts')
diff --git a/API/API-TRM/TRM/Back/app/models/topics.py b/API/API-TRM/TRM/Back/app/models/topics.py
new file mode 100644
index 0000000..1a35a38
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/topics.py
@@ -0,0 +1,26 @@
+from . import Base
+from sqlalchemy import Column, Integer, String, Text, Enum, TIMESTAMP
+from sqlalchemy.sql import func
+
+class Topic(Base):
+    __tablename__ = 'topics'
+    __table_args__ = {
+        'mysql_engine': 'InnoDB',
+        'mysql_charset': 'utf8mb4',
+        'mysql_collate': 'utf8mb4_general_ci',
+        'comment': '话题/超话表'
+    }
+
+    id = Column(Integer, primary_key=True, autoincrement=True, comment='话题ID')
+    name = Column(String(100, collation='utf8mb4_general_ci'), nullable=False, unique=True, comment='话题名称')
+    description = Column(Text(collation='utf8mb4_general_ci'), comment='话题描述')
+    status = Column(
+        Enum('active', 'archived', name='topic_status', collation='utf8mb4_general_ci'),
+        default='active',
+        comment='状态'
+    )
+    created_at = Column(
+        TIMESTAMP,
+        server_default=func.current_timestamp(),
+        comment='创建时间'
+    )
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/models/users.py b/API/API-TRM/TRM/Back/app/models/users.py
new file mode 100644
index 0000000..0505e86
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/models/users.py
@@ -0,0 +1,51 @@
+from . import Base
+from sqlalchemy import (
+    Column, Integer, String, Enum, TIMESTAMP, text
+)
+from sqlalchemy.ext.declarative import declarative_base
+
+
+class User(Base):
+    __tablename__ = 'users'
+
+    def to_dict(self):
+        return {
+            'id': self.id,
+            'username': self.username if self.username else None,
+            'email': self.email if self.email else None,
+            'avatar': self.avatar if self.avatar else None,
+            'role': self.role if self.role else None,
+            'bio': self.bio if self.bio else None,
+            'status': self.status if self.status else None,
+            'created_at': self.created_at.isoformat() if self.created_at else None,
+            'updated_at': self.updated_at.isoformat() if self.updated_at else None
+        }
+
+
+
+    id = Column(Integer, primary_key=True, autoincrement=True, comment='用户ID')
+    username = Column(String(50), nullable=False, unique=True, comment='用户名')
+    password = Column(String(255), nullable=False, comment='加密密码')
+    email = Column(String(100), nullable=False, unique=True, comment='邮箱')
+    avatar = Column(String(255), comment='头像URL')
+    role = Column(Enum('user', 'admin', 'superadmin', name='user_role'), comment='角色')
+    bio = Column(String(255), comment='个人简介')
+    status = Column(
+        Enum('active','banned','muted', name='user_status'),
+        nullable=False,
+        server_default=text("'active'"),
+        comment='账号状态'
+    )
+    created_at = Column(
+        TIMESTAMP,
+        nullable=True,
+        server_default=text('CURRENT_TIMESTAMP'),
+        comment='创建时间'
+    )
+    updated_at = Column(
+        TIMESTAMP,
+        nullable=True,
+        server_default=text('CURRENT_TIMESTAMP'),
+        onupdate=text('CURRENT_TIMESTAMP'),
+        comment='更新时间'
+    )
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/routes.py b/API/API-TRM/TRM/Back/app/routes.py
new file mode 100644
index 0000000..1238364
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/routes.py
@@ -0,0 +1,44 @@
+from flask import Blueprint, render_template
+from .functions.Fpost import Fpost;
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+from config import Config
+from flask import jsonify,request
+
+main = Blueprint('main', __name__)
+
+
+@main.route('/spostlist',methods=['POST','GET'])
+def postlist():
+    data=request.get_json()
+    engine=create_engine(Config.SQLURL)
+    SessionLocal = sessionmaker(bind=engine)
+    session = SessionLocal()
+    f=Fpost(session)
+    checres=f.checkid(data['userid'])
+    if(not checres):
+        return jsonify()
+    res=f.getlist()
+    respons=[]
+    for datai in res:
+        respons.append({
+            'id': datai[0],
+            'title': datai[1],
+            'status': datai[2]
+        })
+    return jsonify(respons)
+
+@main.route('/sgetpost',methods=['POST','GET'])
+def post():
+    data=request.get_json()
+    engine=create_engine(Config.SQLURL)
+    SessionLocal = sessionmaker(bind=engine)
+    session = SessionLocal()
+    f=Fpost(session)
+    checres=f.checkid(data['userid'])
+    if(not checres):
+        return jsonify()
+    res=f.getpost(data['postid'])
+
+    return jsonify(res.to_dict() if res else {})
+
diff --git a/API/API-TRM/TRM/Back/app/templates/base.html b/API/API-TRM/TRM/Back/app/templates/base.html
new file mode 100644
index 0000000..3c6f3cb
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/templates/base.html
@@ -0,0 +1,29 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>{% block title %}My Flask App{% endblock %}</title>
+    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
+</head>
+<body>
+    <header>
+        <h1>Welcome to My Flask App</h1>
+        <nav>
+            <ul>
+                <li><a href="{{ url_for('index') }}">Home</a></li>
+                <!-- Add more navigation links here -->
+            </ul>
+        </nav>
+    </header>
+    
+    <main>
+        {% block content %}
+        {% endblock %}
+    </main>
+    
+    <footer>
+        <p>&copy; 2023 My Flask App</p>
+    </footer>
+</body>
+</html>
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/app/templates/index.html b/API/API-TRM/TRM/Back/app/templates/index.html
new file mode 100644
index 0000000..6631bea
--- /dev/null
+++ b/API/API-TRM/TRM/Back/app/templates/index.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Index Page</title>
+    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
+</head>
+<body>
+    {% extends 'base.html' %}
+
+    {% block content %}
+    <h1>Welcome to the Index Page</h1>
+    <p>This is the main page of the application.</p>
+    {% endblock %}
+</body>
+</html>
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/config.py b/API/API-TRM/TRM/Back/config.py
new file mode 100644
index 0000000..d4a2e88
--- /dev/null
+++ b/API/API-TRM/TRM/Back/config.py
@@ -0,0 +1,12 @@
+import os
+from dotenv import load_dotenv
+load_dotenv()
+class Config:
+    SECRET_KEY = os.environ.get('SECRET_KEY') or 'a_default_secret_key'
+    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or 'sqlite:///site.db'
+    SQLALCHEMY_TRACK_MODIFICATIONS = False
+    SQLURL=os.getenv('SQLURL')
+    SQLPORT=os.getenv('SQLPORT')
+    SQLNAME=os.getenv('SQLNAME')
+    SQLUSER=os.getenv('SQLUSER')
+    SQLPWD=os.getenv('SQLPWD')
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/requirements.txt b/API/API-TRM/TRM/Back/requirements.txt
new file mode 100644
index 0000000..8e65f82
--- /dev/null
+++ b/API/API-TRM/TRM/Back/requirements.txt
@@ -0,0 +1,6 @@
+Flask==2.2.2
+SQLAlchemy==1.4.36
+Flask-Migrate==3.1.0
+Flask-WTF==1.0.0
+pytest==7.1.2
+```
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Back/tests/__init__.py b/API/API-TRM/TRM/Back/tests/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/API/API-TRM/TRM/Back/tests/__init__.py
diff --git a/API/API-TRM/TRM/Back/tests/__pycache__/__init__.cpython-312.pyc b/API/API-TRM/TRM/Back/tests/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000..48c8068
--- /dev/null
+++ b/API/API-TRM/TRM/Back/tests/__pycache__/__init__.cpython-312.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/tests/__pycache__/test_app.cpython-312-pytest-7.4.4.pyc b/API/API-TRM/TRM/Back/tests/__pycache__/test_app.cpython-312-pytest-7.4.4.pyc
new file mode 100644
index 0000000..b21ba04
--- /dev/null
+++ b/API/API-TRM/TRM/Back/tests/__pycache__/test_app.cpython-312-pytest-7.4.4.pyc
Binary files differ
diff --git a/API/API-TRM/TRM/Back/tests/test_app.py b/API/API-TRM/TRM/Back/tests/test_app.py
new file mode 100644
index 0000000..5643282
--- /dev/null
+++ b/API/API-TRM/TRM/Back/tests/test_app.py
@@ -0,0 +1,27 @@
+import requests
+url = 'http://127.0.0.1:5713/'
+
+def test_get_postlist():
+    print()
+    urlx=url+'spostlist'
+    payload = {
+        'userid': 3
+    }
+    headers = {'Content-Type': 'application/json'}
+
+    resp = requests.get(urlx, json=payload, headers=headers)
+    # print(resp.status_code)
+    print(resp.json())
+
+def test_get_post():
+    print()
+    urlx=url+'sgetpost'
+    payload = {
+        'userid': 3,
+        'postid': 21
+        }
+    headers = {'Content-Type': 'application/json'}
+
+    resp = requests.get(urlx, json=payload, headers=headers)
+    # print(resp.status_code)
+    print(resp.json())
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Front/trm-front/.gitignore b/API/API-TRM/TRM/Front/trm-front/.gitignore
new file mode 100644
index 0000000..4d29575
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/.gitignore
@@ -0,0 +1,23 @@
+# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
+
+# dependencies
+/node_modules
+/.pnp
+.pnp.js
+
+# testing
+/coverage
+
+# production
+/build
+
+# misc
+.DS_Store
+.env.local
+.env.development.local
+.env.test.local
+.env.production.local
+
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
diff --git a/API/API-TRM/TRM/Front/trm-front/README.md b/API/API-TRM/TRM/Front/trm-front/README.md
new file mode 100644
index 0000000..58beeac
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/README.md
@@ -0,0 +1,70 @@
+# Getting Started with Create React App
+
+This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
+
+## Available Scripts
+
+In the project directory, you can run:
+
+### `npm start`
+
+Runs the app in the development mode.\
+Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
+
+The page will reload when you make changes.\
+You may also see any lint errors in the console.
+
+### `npm test`
+
+Launches the test runner in the interactive watch mode.\
+See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
+
+### `npm run build`
+
+Builds the app for production to the `build` folder.\
+It correctly bundles React in production mode and optimizes the build for the best performance.
+
+The build is minified and the filenames include the hashes.\
+Your app is ready to be deployed!
+
+See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
+
+### `npm run eject`
+
+**Note: this is a one-way operation. Once you `eject`, you can't go back!**
+
+If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
+
+Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
+
+You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
+
+## Learn More
+
+You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
+
+To learn React, check out the [React documentation](https://reactjs.org/).
+
+### Code Splitting
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
+
+### Analyzing the Bundle Size
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
+
+### Making a Progressive Web App
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
+
+### Advanced Configuration
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
+
+### Deployment
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
+
+### `npm run build` fails to minify
+
+This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
diff --git a/API/API-TRM/TRM/Front/trm-front/package.json b/API/API-TRM/TRM/Front/trm-front/package.json
new file mode 100644
index 0000000..dbe27a6
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/package.json
@@ -0,0 +1,39 @@
+{
+  "name": "trm-front",
+  "version": "0.1.0",
+  "private": true,
+  "dependencies": {
+    "@testing-library/dom": "^10.4.0",
+    "@testing-library/jest-dom": "^6.6.3",
+    "@testing-library/react": "^16.3.0",
+    "@testing-library/user-event": "^13.5.0",
+    "react": "^19.1.0",
+    "react-dom": "^19.1.0",
+    "react-scripts": "5.0.1",
+    "web-vitals": "^2.1.4"
+  },
+  "scripts": {
+    "start": "react-scripts start",
+    "build": "react-scripts build",
+    "test": "react-scripts test",
+    "eject": "react-scripts eject"
+  },
+  "eslintConfig": {
+    "extends": [
+      "react-app",
+      "react-app/jest"
+    ]
+  },
+  "browserslist": {
+    "production": [
+      ">0.2%",
+      "not dead",
+      "not op_mini all"
+    ],
+    "development": [
+      "last 1 chrome version",
+      "last 1 firefox version",
+      "last 1 safari version"
+    ]
+  }
+}
diff --git a/API/API-TRM/TRM/Front/trm-front/public/favicon.ico b/API/API-TRM/TRM/Front/trm-front/public/favicon.ico
new file mode 100644
index 0000000..a11777c
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/public/favicon.ico
Binary files differ
diff --git a/API/API-TRM/TRM/Front/trm-front/public/index.html b/API/API-TRM/TRM/Front/trm-front/public/index.html
new file mode 100644
index 0000000..aa069f2
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/public/index.html
@@ -0,0 +1,43 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8" />
+    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
+    <meta name="viewport" content="width=device-width, initial-scale=1" />
+    <meta name="theme-color" content="#000000" />
+    <meta
+      name="description"
+      content="Web site created using create-react-app"
+    />
+    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
+    <!--
+      manifest.json provides metadata used when your web app is installed on a
+      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
+    -->
+    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
+    <!--
+      Notice the use of %PUBLIC_URL% in the tags above.
+      It will be replaced with the URL of the `public` folder during the build.
+      Only files inside the `public` folder can be referenced from the HTML.
+
+      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
+      work correctly both with client-side routing and a non-root public URL.
+      Learn how to configure a non-root public URL by running `npm run build`.
+    -->
+    <title>React App</title>
+  </head>
+  <body>
+    <noscript>You need to enable JavaScript to run this app.</noscript>
+    <div id="root"></div>
+    <!--
+      This HTML file is a template.
+      If you open it directly in the browser, you will see an empty page.
+
+      You can add webfonts, meta tags, or analytics to this file.
+      The build step will place the bundled scripts into the <body> tag.
+
+      To begin the development, run `npm start` or `yarn start`.
+      To create a production bundle, use `npm run build` or `yarn build`.
+    -->
+  </body>
+</html>
diff --git a/API/API-TRM/TRM/Front/trm-front/public/logo192.png b/API/API-TRM/TRM/Front/trm-front/public/logo192.png
new file mode 100644
index 0000000..fc44b0a
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/public/logo192.png
Binary files differ
diff --git a/API/API-TRM/TRM/Front/trm-front/public/logo512.png b/API/API-TRM/TRM/Front/trm-front/public/logo512.png
new file mode 100644
index 0000000..a4e47a6
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/public/logo512.png
Binary files differ
diff --git a/API/API-TRM/TRM/Front/trm-front/public/manifest.json b/API/API-TRM/TRM/Front/trm-front/public/manifest.json
new file mode 100644
index 0000000..080d6c7
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/public/manifest.json
@@ -0,0 +1,25 @@
+{
+  "short_name": "React App",
+  "name": "Create React App Sample",
+  "icons": [
+    {
+      "src": "favicon.ico",
+      "sizes": "64x64 32x32 24x24 16x16",
+      "type": "image/x-icon"
+    },
+    {
+      "src": "logo192.png",
+      "type": "image/png",
+      "sizes": "192x192"
+    },
+    {
+      "src": "logo512.png",
+      "type": "image/png",
+      "sizes": "512x512"
+    }
+  ],
+  "start_url": ".",
+  "display": "standalone",
+  "theme_color": "#000000",
+  "background_color": "#ffffff"
+}
diff --git a/API/API-TRM/TRM/Front/trm-front/public/robots.txt b/API/API-TRM/TRM/Front/trm-front/public/robots.txt
new file mode 100644
index 0000000..e9e57dc
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/public/robots.txt
@@ -0,0 +1,3 @@
+# https://www.robotstxt.org/robotstxt.html
+User-agent: *
+Disallow:
diff --git a/API/API-TRM/TRM/Front/trm-front/src/App.css b/API/API-TRM/TRM/Front/trm-front/src/App.css
new file mode 100644
index 0000000..74b5e05
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/App.css
@@ -0,0 +1,38 @@
+.App {
+  text-align: center;
+}
+
+.App-logo {
+  height: 40vmin;
+  pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+  .App-logo {
+    animation: App-logo-spin infinite 20s linear;
+  }
+}
+
+.App-header {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.App-link {
+  color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+  from {
+    transform: rotate(0deg);
+  }
+  to {
+    transform: rotate(360deg);
+  }
+}
diff --git a/API/API-TRM/TRM/Front/trm-front/src/App.js b/API/API-TRM/TRM/Front/trm-front/src/App.js
new file mode 100644
index 0000000..3784575
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/App.js
@@ -0,0 +1,25 @@
+import logo from './logo.svg';
+import './App.css';
+
+function App() {
+  return (
+    <div className="App">
+      <header className="App-header">
+        <img src={logo} className="App-logo" alt="logo" />
+        <p>
+          Edit <code>src/App.js</code> and save to reload.
+        </p>
+        <a
+          className="App-link"
+          href="https://reactjs.org"
+          target="_blank"
+          rel="noopener noreferrer"
+        >
+          Learn React
+        </a>
+      </header>
+    </div>
+  );
+}
+
+export default App;
diff --git a/API/API-TRM/TRM/Front/trm-front/src/App.test.js b/API/API-TRM/TRM/Front/trm-front/src/App.test.js
new file mode 100644
index 0000000..1f03afe
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/App.test.js
@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});
diff --git a/API/API-TRM/TRM/Front/trm-front/src/index.css b/API/API-TRM/TRM/Front/trm-front/src/index.css
new file mode 100644
index 0000000..ec2585e
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/index.css
@@ -0,0 +1,13 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}
diff --git a/API/API-TRM/TRM/Front/trm-front/src/index.js b/API/API-TRM/TRM/Front/trm-front/src/index.js
new file mode 100644
index 0000000..d563c0f
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/index.js
@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();
diff --git a/API/API-TRM/TRM/Front/trm-front/src/logo.svg b/API/API-TRM/TRM/Front/trm-front/src/logo.svg
new file mode 100644
index 0000000..9dfc1c0
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/logo.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>
\ No newline at end of file
diff --git a/API/API-TRM/TRM/Front/trm-front/src/reportWebVitals.js b/API/API-TRM/TRM/Front/trm-front/src/reportWebVitals.js
new file mode 100644
index 0000000..5253d3a
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/reportWebVitals.js
@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;
diff --git a/API/API-TRM/TRM/Front/trm-front/src/setupTests.js b/API/API-TRM/TRM/Front/trm-front/src/setupTests.js
new file mode 100644
index 0000000..8f2609b
--- /dev/null
+++ b/API/API-TRM/TRM/Front/trm-front/src/setupTests.js
@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';
diff --git a/API/API-TRM/all_tables.sql b/API/API-TRM/all_tables.sql
new file mode 100644
index 0000000..f1e8547
--- /dev/null
+++ b/API/API-TRM/all_tables.sql
@@ -0,0 +1,181 @@
+/*
+数据库设计说明:
+1.	核心表结构:
+	users:存储用户信息,包含角色管理和账号状态
+	posts:核心内容表,支持多模态内容(图文/视频/文档)
+	behaviors:记录用户互动行为(点赞/收藏/浏览等)
+	comments:评论系统,支持多级回复
+	follows:用户社交关系
+2.	推荐系统支持:
+	posts.heat 字段存储动态计算的热度值
+	behaviors 表记录用户行为用于协同过滤
+	user_tags 表构建用户兴趣画像
+	通过 post_tags 实现内容标签分类
+3.	多模态内容处理:
+	posts.media_urls 使用 JSON 类型存储多个资源 URL
+	posts.type 区分不同类型的内容(图文/视频/文档)
+4.	审核与安全:
+	audits 表记录内容审核历史
+	posts.status 管理内容生命周期状态
+	logs 表记录系统操作和访问日志
+5.	性能优化:
+	为查询频繁字段添加索引(热度/行为类型/时间)
+	使用 JSON 类型存储灵活数据(通知内容/媒体资源)
+	通过 heat 字段预计算支持热门排序
+6.	扩展性设计:
+	用户画像系统通过 user_tags 表实现
+	通知系统支持多种互动类型
+	行为表设计支持未来扩展新行为类型
+*/
+
+
+-- 创建数据库
+CREATE DATABASE IF NOT EXISTS redbook DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_general_ci;
+USE redbook;
+
+-- 用户表
+CREATE TABLE users (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '用户ID',
+    username VARCHAR(50) NOT NULL UNIQUE COMMENT '用户名',
+    password VARCHAR(255) NOT NULL COMMENT '加密密码',
+    email VARCHAR(100) NOT NULL UNIQUE COMMENT '邮箱',
+    avatar VARCHAR(255) COMMENT '头像URL',
+    role ENUM('user', 'admin') DEFAULT 'user' COMMENT '角色',
+    bio VARCHAR(255) COMMENT '个人简介',
+    status ENUM('active', 'banned', 'muted') DEFAULT 'active' COMMENT '账号状态',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
+) ENGINE=InnoDB COMMENT='用户表';
+
+-- 标签表
+CREATE TABLE tags (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '标签ID',
+    name VARCHAR(50) NOT NULL UNIQUE COMMENT '标签名称',
+    description VARCHAR(255) COMMENT '标签描述',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
+) ENGINE=InnoDB COMMENT='内容标签表';
+
+-- 话题/超话表
+CREATE TABLE topics (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '话题ID',
+    name VARCHAR(100) NOT NULL UNIQUE COMMENT '话题名称',
+    description TEXT COMMENT '话题描述',
+    status ENUM('active', 'archived') DEFAULT 'active' COMMENT '状态',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间'
+) ENGINE=InnoDB COMMENT='话题/超话表';
+
+-- 内容帖子表
+CREATE TABLE posts (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '帖子ID',
+    user_id INT NOT NULL COMMENT '作者ID',
+    topic_id INT COMMENT '所属话题ID',
+    type ENUM('text', 'image', 'video', 'document') DEFAULT 'text' COMMENT '内容类型',
+    title VARCHAR(255) NOT NULL COMMENT '标题',
+    content TEXT NOT NULL COMMENT '正文内容',
+    media_urls JSON COMMENT '媒体资源URL数组',
+    status ENUM('draft', 'pending', 'published', 'deleted', 'rejected') DEFAULT 'draft' COMMENT '状态',
+    heat INT DEFAULT 0 COMMENT '热度值',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+    FOREIGN KEY (topic_id) REFERENCES topics(id) ON DELETE SET NULL
+) ENGINE=InnoDB COMMENT='内容帖子表';
+
+-- 帖子标签关联表
+CREATE TABLE post_tags (
+    post_id INT NOT NULL COMMENT '帖子ID',
+    tag_id INT NOT NULL COMMENT '标签ID',
+    PRIMARY KEY (post_id, tag_id),
+    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+    FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='帖子标签关联表';
+
+-- 用户行为表
+CREATE TABLE behaviors (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '行为ID',
+    user_id INT NOT NULL COMMENT '用户ID',
+    post_id INT NOT NULL COMMENT '帖子ID',
+    type ENUM('like', 'comment', 'favorite', 'view', 'share') NOT NULL COMMENT '行为类型',
+    value INT DEFAULT 1 COMMENT '行为值',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '行为时间',
+    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='用户行为记录表';
+
+-- 评论表
+CREATE TABLE comments (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '评论ID',
+    post_id INT NOT NULL COMMENT '帖子ID',
+    user_id INT NOT NULL COMMENT '用户ID',
+    parent_id INT DEFAULT NULL COMMENT '父评论ID',
+    content TEXT NOT NULL COMMENT '评论内容',
+    status ENUM('active', 'deleted') DEFAULT 'active' COMMENT '状态',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+    FOREIGN KEY (parent_id) REFERENCES comments(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='评论表';
+
+-- 用户关注关系表
+CREATE TABLE follows (
+    follower_id INT NOT NULL COMMENT '关注者ID',
+    followee_id INT NOT NULL COMMENT '被关注者ID',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '关注时间',
+    PRIMARY KEY (follower_id, followee_id),
+    FOREIGN KEY (follower_id) REFERENCES users(id) ON DELETE CASCADE,
+    FOREIGN KEY (followee_id) REFERENCES users(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='用户关注关系表';
+
+-- 通知表
+CREATE TABLE notifications (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '通知ID',
+    user_id INT NOT NULL COMMENT '接收用户ID',
+    type ENUM('like', 'comment', 'follow', 'system', 'audit') NOT NULL COMMENT '通知类型',
+    content JSON NOT NULL COMMENT '通知内容',
+    is_read BOOLEAN DEFAULT FALSE COMMENT '是否已读',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='用户通知表';
+
+-- 审核记录表
+CREATE TABLE audits (
+    id INT AUTO_INCREMENT PRIMARY KEY COMMENT '审核ID',
+    post_id INT NOT NULL COMMENT '帖子ID',
+    admin_id INT NOT NULL COMMENT '管理员ID',
+    result ENUM('approved', 'rejected') NOT NULL COMMENT '审核结果',
+    reason VARCHAR(255) COMMENT '审核原因',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '审核时间',
+    FOREIGN KEY (post_id) REFERENCES posts(id) ON DELETE CASCADE,
+    FOREIGN KEY (admin_id) REFERENCES users(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='内容审核记录表';
+
+-- 日志表
+CREATE TABLE logs (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY COMMENT '日志ID',
+    user_id INT DEFAULT NULL COMMENT '用户ID',
+    type ENUM('access', 'error', 'behavior', 'system') NOT NULL COMMENT '日志类型',
+    content TEXT NOT NULL COMMENT '日志内容',
+    ip VARCHAR(45) COMMENT 'IP地址',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '记录时间',
+    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
+) ENGINE=InnoDB COMMENT='系统日志表';
+
+-- 用户兴趣标签表(用户画像)
+CREATE TABLE user_tags (
+    user_id INT NOT NULL COMMENT '用户ID',
+    tag_id INT NOT NULL COMMENT '标签ID',
+    weight FLOAT DEFAULT 1.0 COMMENT '兴趣权重',
+    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
+    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
+    PRIMARY KEY (user_id, tag_id),
+    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
+    FOREIGN KEY (tag_id) REFERENCES tags(id) ON DELETE CASCADE
+) ENGINE=InnoDB COMMENT='用户兴趣标签表';
+
+-- 索引优化
+CREATE INDEX idx_posts_heat ON posts(heat);
+CREATE INDEX idx_behaviors_type ON behaviors(type);
+CREATE INDEX idx_notifications_read ON notifications(is_read);
+CREATE INDEX idx_logs_created ON logs(created_at);
+CREATE INDEX idx_comments_post ON comments(post_id);
\ No newline at end of file
diff --git a/API/API-TRM/xiaohongshu-upload-platform/README.md b/API/API-TRM/xiaohongshu-upload-platform/README.md
new file mode 100644
index 0000000..6f35930
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/README.md
@@ -0,0 +1,185 @@
+# 小红书内容创作平台
+
+这是一个基于 React + Vite 构建的小红书内容创作平台界面,完全复制了小红书官方创作服务平台的设计和功能。
+
+## 功能特性 ✨
+
+### 🎨 界面设计
+- **完全还原小红书官方设计**:精确复制了小红书创作服务平台的视觉风格
+- **响应式布局**:支持桌面端和移动端适配
+- **现代化UI**:使用 Lucide React 图标库,提供清晰美观的界面
+
+### 📤 上传功能
+- **双模式上传**:支持图片上传和视频上传两种模式
+- **拖拽上传**:支持文件拖拽到上传区域
+- **点击上传**:点击按钮选择文件上传
+- **文件验证**:
+  - 图片:支持 JPEG、JPG、PNG、WebP 格式,最大 32MB
+  - 视频:支持 MP4、MOV、AVI 格式,最大 2GB
+- **实时进度显示**:带有动画效果的上传进度条
+
+### 🖼️ 文件管理
+- **文件预览**:上传后实时显示文件缩略图
+- **文件信息**:显示文件名、大小等详细信息
+- **批量管理**:支持单个删除和批量清除
+- **文件计数**:实时显示已上传文件数量
+
+### 🎯 交互体验
+- **拖拽反馈**:拖拽时提供视觉反馈效果
+- **加载状态**:上传过程中的加载动画
+- **操作提示**:完成上传后的成功提示
+- **悬停效果**:按钮和文件项的悬停交互
+
+### 🗂️ 导航系统
+- **侧边栏导航**:完整的功能菜单
+- **可展开子菜单**:数据看板等功能的子选项
+- **活跃状态**:当前选中页面的高亮显示
+- **固定布局**:头部和侧边栏固定定位
+
+## 技术栈 🛠️
+
+- **前端框架**:React 19.1.0
+- **构建工具**:Vite 6.0.5
+- **图标库**:Lucide React 0.468.0
+- **样式**:纯 CSS(无预处理器)
+- **开发语言**:JavaScript + JSX
+
+## 安装运行 🚀
+
+1. **安装依赖**
+   ```bash
+   npm install
+   ```
+
+2. **启动开发服务器**
+   ```bash
+   npm run dev
+   ```
+
+3. **打开浏览器**
+   ```
+   http://localhost:5173
+   ```
+
+4. **构建生产版本**
+   ```bash
+   npm run build
+   ```
+
+## 项目结构 📁
+
+```
+发布页面/
+├── public/              # 静态资源
+│   └── vite.svg        # Vite 图标
+├── src/
+│   ├── App.jsx         # 主应用组件
+│   ├── App.css         # 主样式文件
+│   ├── index.css       # 全局样式
+│   └── main.jsx        # 应用入口
+├── index.html          # HTML 入口文件
+├── package.json        # 项目配置
+├── vite.config.js      # Vite 配置
+└── README.md          # 项目说明
+```
+
+## 核心功能实现 💡
+
+### 文件上传处理
+```javascript
+const handleFileUpload = () => {
+  const input = document.createElement('input')
+  input.type = 'file'
+  input.accept = activeTab === 'video' ? 'video/*' : 'image/*'
+  input.multiple = activeTab === 'image'
+  
+  input.onchange = (e) => {
+    const files = Array.from(e.target.files)
+    if (files.length > 0 && validateFiles(files)) {
+      simulateUpload(files)
+    }
+  }
+  
+  input.click()
+}
+```
+
+### 拖拽上传实现
+```javascript
+const handleDrop = (e) => {
+  e.preventDefault()
+  e.stopPropagation()
+  setIsDragOver(false)
+  
+  const files = Array.from(e.dataTransfer.files)
+  if (files.length > 0 && validateFiles(files)) {
+    simulateUpload(files)
+  }
+}
+```
+
+### 文件验证机制
+```javascript
+const validateFiles = (files) => {
+  const validImageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
+  const validVideoTypes = ['video/mp4', 'video/mov', 'video/avi']
+  
+  const validTypes = activeTab === 'video' ? validVideoTypes : validImageTypes
+  const maxSize = activeTab === 'video' ? 2 * 1024 * 1024 * 1024 : 32 * 1024 * 1024
+  
+  return files.every(file => 
+    validTypes.includes(file.type) && file.size <= maxSize
+  )
+}
+```
+
+## 样式特色 🎨
+
+### 响应式设计
+- 桌面端:固定侧边栏布局
+- 移动端:隐藏侧边栏,堆叠布局
+- 自适应文件网格:根据屏幕大小调整列数
+
+### 动画效果
+- 拖拽时的放大效果
+- 进度条的流光动画
+- 文件项的悬停过渡
+- 页面切换的淡入效果
+
+### 色彩方案
+- 主色调:#ff4757(小红书红)
+- 背景色:#f5f7fa(浅灰蓝)
+- 文字色:#333(深灰)
+- 边框色:#e8eaed(浅灰)
+
+## 待扩展功能 🔮
+
+- **后端集成**:连接真实的文件上传 API
+- **用户认证**:登录注册功能
+- **内容编辑**:笔记内容编辑器
+- **数据统计**:真实的数据看板功能
+- **社交功能**:评论、点赞等互动功能
+
+## 开发说明 📝
+
+这个项目完全基于前端实现,所有的上传功能都是模拟的。文件预览使用了 `URL.createObjectURL()` 来生成本地预览链接。在实际部署时,需要:
+
+1. 集成后端文件上传 API
+2. 实现用户认证系统
+3. 添加数据持久化
+4. 优化性能和安全性
+
+## 浏览器兼容性 🌐
+
+- Chrome 90+
+- Firefox 88+
+- Safari 14+
+- Edge 90+
+
+## 许可证 📄
+
+MIT License
+
+---
+
+**注意**:本项目仅用于学习和演示目的,请遵守相关法律法规和平台使用条款。
diff --git a/API/API-TRM/xiaohongshu-upload-platform/index.html b/API/API-TRM/xiaohongshu-upload-platform/index.html
new file mode 100644
index 0000000..b919940
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/index.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="zh-CN">
+  <head>
+    <meta charset="UTF-8" />
+    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>小红书创作服务平台</title>
+  </head>
+  <body>
+    <div id="root"></div>
+    <script type="module" src="/src/main.jsx"></script>
+  </body>
+</html>
diff --git a/API/API-TRM/xiaohongshu-upload-platform/package.json b/API/API-TRM/xiaohongshu-upload-platform/package.json
new file mode 100644
index 0000000..00a233f
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/package.json
@@ -0,0 +1,20 @@
+{
+  "name": "xiaohongshu-creator-platform",
+  "private": true,
+  "version": "0.0.0",
+  "type": "module",
+  "scripts": {
+    "dev": "vite",
+    "build": "vite build",
+    "preview": "vite preview"
+  },
+  "dependencies": {
+    "react": "^18.3.1",
+    "react-dom": "^18.3.1",
+    "lucide-react": "^0.468.0"
+  },
+  "devDependencies": {
+    "@vitejs/plugin-react": "^4.3.4",
+    "vite": "^6.0.5"
+  }
+}
diff --git a/API/API-TRM/xiaohongshu-upload-platform/public/vite.svg b/API/API-TRM/xiaohongshu-upload-platform/public/vite.svg
new file mode 100644
index 0000000..ee9fada
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/public/vite.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>
diff --git a/API/API-TRM/xiaohongshu-upload-platform/src/App.css b/API/API-TRM/xiaohongshu-upload-platform/src/App.css
new file mode 100644
index 0000000..00d10d6
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/src/App.css
@@ -0,0 +1,583 @@
+.app {
+  display: flex;
+  min-height: 100vh;
+  background-color: #f5f7fa;
+}
+
+/* Header */
+.header {
+  position: fixed;
+  top: 0;
+  left: 0;
+  right: 0;
+  height: 60px;
+  background: #fff;
+  border-bottom: 1px solid #e8eaed;
+  display: flex;
+  align-items: center;
+  padding: 0 20px;
+  z-index: 1000;
+  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
+}
+
+.header-left {
+  display: flex;
+  align-items: center;
+  gap: 12px;
+}
+
+.logo {
+  background: #ff4757;
+  color: white;
+  padding: 6px 12px;
+  border-radius: 6px;
+  font-size: 14px;
+  font-weight: bold;
+}
+
+.header-title {
+  font-size: 18px;
+  font-weight: 500;
+  color: #333;
+}
+
+.header-right {
+  margin-left: auto;
+  display: flex;
+  align-items: center;
+  gap: 12px;
+}
+
+.user-info {
+  display: flex;
+  align-items: center;
+  gap: 8px;
+  color: #666;
+  font-size: 14px;
+}
+
+/* Sidebar */
+.sidebar {
+  position: fixed;
+  left: 0;
+  top: 60px;
+  width: 200px;
+  height: calc(100vh - 60px);
+  background: #fff;
+  border-right: 1px solid #e8eaed;
+  overflow-y: auto;
+  z-index: 999;
+}
+
+.publish-btn {
+  margin: 16px;
+  background: #ff4757;
+  color: white;
+  padding: 10px 16px;
+  border-radius: 6px;
+  font-size: 14px;
+  font-weight: 500;
+  text-align: center;
+  transition: background 0.2s;
+}
+
+.publish-btn:hover {
+  background: #ff3742;
+}
+
+.nav-menu {
+  padding: 0;
+  list-style: none;
+}
+
+.nav-item {
+  border-bottom: 1px solid #f0f0f0;
+}
+
+.nav-link {
+  display: flex;
+  align-items: center;
+  padding: 12px 20px;
+  color: #333;
+  font-size: 14px;
+  transition: all 0.2s;
+  gap: 8px;
+}
+
+.nav-link:hover {
+  background: #f8f9fa;
+  color: #ff4757;
+}
+
+.nav-link.active {
+  background: linear-gradient(135deg, #ff4757, #ff6b7a);
+  color: white;
+  font-weight: 500;
+}
+
+.nav-link.active .lucide {
+  color: white;
+}
+
+.nav-submenu {
+  padding-left: 20px;
+  background: #fafafa;
+}
+
+.nav-submenu .nav-link {
+  padding: 8px 20px;
+  font-size: 13px;
+  color: #666;
+}
+
+.nav-submenu .nav-link:hover {
+  color: #ff4757;
+}
+
+/* Main Content */
+.main-content {
+  margin-left: 200px;
+  padding-top: 60px;
+  flex: 1;
+  min-height: 100vh;
+}
+
+.content-wrapper {
+  padding: 20px;
+  max-width: 1200px;
+  margin: 0 auto;
+}
+
+/* Upload Area */
+.upload-tabs {
+  display: flex;
+  gap: 20px;
+  margin-bottom: 30px;
+  border-bottom: 1px solid #e8eaed;
+}
+
+.upload-tab {
+  padding: 12px 0;
+  font-size: 16px;
+  color: #666;
+  cursor: pointer;
+  border-bottom: 2px solid transparent;
+  transition: all 0.2s;
+}
+
+.upload-tab.active {
+  color: #ff4757;
+  border-bottom-color: #ff4757;
+  font-weight: 500;
+}
+
+.upload-area {
+  background: #fff;
+  border-radius: 8px;
+  padding: 80px 40px;
+  text-align: center;
+  border: 2px dashed #ddd;
+  margin-bottom: 40px;
+  transition: all 0.2s;
+  min-height: 300px;
+  display: flex;
+  flex-direction: column;
+  justify-content: center;
+  align-items: center;
+  position: relative;
+}
+
+.upload-area:hover {
+  border-color: #ff4757;
+  background: #fff8f8;
+}
+
+.upload-area.drag-over {
+  border-color: #ff4757;
+  background: #fff0f0;
+  transform: scale(1.02);
+}
+
+.upload-icon {
+  width: 100px;
+  height: 100px;
+  margin: 0 auto 30px;
+  background: #f8f9fa;
+  border-radius: 50%;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  font-size: 40px;
+  color: #ccc;
+  transition: all 0.3s ease;
+}
+
+.upload-area:hover .upload-icon {
+  background: #ff475710;
+  color: #ff4757;
+  transform: scale(1.1);
+}
+
+.upload-area.drag-over .upload-icon {
+  background: #ff475720;
+  color: #ff4757;
+  transform: scale(1.2);
+}
+
+.upload-title {
+  font-size: 20px;
+  color: #333;
+  margin-bottom: 12px;
+  font-weight: 500;
+}
+
+.upload-subtitle {
+  font-size: 14px;
+  color: #999;
+  margin-bottom: 30px;
+}
+
+.upload-btn {
+  background: #ff4757;
+  color: white;
+  padding: 14px 28px;
+  border-radius: 6px;
+  font-size: 16px;
+  font-weight: 500;
+  transition: background 0.2s;
+  min-width: 120px;
+}
+
+.upload-btn:hover:not(:disabled) {
+  background: #ff3742;
+}
+
+.upload-btn:disabled {
+  background: #ccc;
+  cursor: not-allowed;
+}
+
+.upload-btn.uploading {
+  background: #ff4757;
+  opacity: 0.8;
+}
+
+/* File Preview */
+.file-preview-area {
+  background: #fff;
+  border-radius: 8px;
+  padding: 20px;
+  margin-bottom: 40px;
+  border: 1px solid #e8eaed;
+}
+
+/* Preview Header */
+.preview-header {
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  margin-bottom: 16px;
+}
+
+.preview-title {
+  font-size: 16px;
+  color: #333;
+  margin-bottom: 16px;
+  font-weight: 500;
+}
+
+.clear-files-btn {
+  background: #ff4757;
+  color: white;
+  padding: 6px 12px;
+  border-radius: 4px;
+  font-size: 12px;
+  transition: background 0.2s;
+}
+
+.clear-files-btn:hover {
+  background: #ff3742;
+}
+
+.file-grid {
+  display: grid;
+  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+  gap: 16px;
+}
+
+.file-item {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  padding: 12px;
+  border: 1px solid #f0f0f0;
+  border-radius: 6px;
+  transition: all 0.2s ease;
+  position: relative;
+}
+
+.file-item:hover {
+  border-color: #ff4757;
+  box-shadow: 0 2px 8px rgba(255, 71, 87, 0.1);
+}
+
+.file-item:hover .remove-file-btn {
+  opacity: 1;
+}
+
+.remove-file-btn {
+  position: absolute;
+  top: 4px;
+  right: 4px;
+  background: rgba(255, 71, 87, 0.8);
+  color: white;
+  border-radius: 50%;
+  width: 20px;
+  height: 20px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  font-size: 14px;
+  font-weight: bold;
+  opacity: 0;
+  transition: all 0.2s;
+}
+
+.file-thumbnail {
+  width: 80px;
+  height: 80px;
+  border-radius: 6px;
+  overflow: hidden;
+  margin-bottom: 8px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  background: #f8f9fa;
+}
+
+.file-thumbnail img {
+  width: 100%;
+  height: 100%;
+  object-fit: cover;
+}
+
+.video-thumbnail {
+  color: #666;
+}
+
+.file-info {
+  text-align: center;
+  width: 100%;
+}
+
+.file-name {
+  font-size: 12px;
+  color: #333;
+  margin-bottom: 4px;
+  font-weight: 500;
+}
+
+.file-size {
+  font-size: 11px;
+  color: #999;
+}
+
+/* Upload Progress */
+.progress-container {
+  margin-top: 20px;
+  width: 100%;
+  max-width: 400px;
+}
+
+.progress-bar {
+  width: 100%;
+  height: 8px;
+  background-color: #f0f0f0;
+  border-radius: 4px;
+  overflow: hidden;
+  margin-bottom: 8px;
+}
+
+.progress-fill {
+  height: 100%;
+  background: linear-gradient(90deg, #ff4757, #ff6b7a);
+  border-radius: 4px;
+  transition: width 0.3s ease;
+  position: relative;
+}
+
+.progress-fill::after {
+  content: '';
+  position: absolute;
+  top: 0;
+  left: 0;
+  right: 0;
+  bottom: 0;
+  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
+  animation: shimmer 1.5s infinite;
+}
+
+@keyframes shimmer {
+  0% { transform: translateX(-100%); }
+  100% { transform: translateX(100%); }
+}
+
+.progress-text {
+  text-align: center;
+  font-size: 12px;
+  color: #666;
+  font-weight: 500;
+}
+
+/* Upload Info */
+.upload-info {
+  display: flex;
+  gap: 60px;
+  justify-content: center;
+  margin-top: 40px;
+  padding: 20px;
+  opacity: 1;
+  transition: opacity 0.3s ease;
+}
+
+.upload-info.fade-in {
+  animation: fadeIn 0.3s ease-in-out;
+}
+
+@keyframes fadeIn {
+  from {
+    opacity: 0;
+    transform: translateY(10px);
+  }
+  to {
+    opacity: 1;
+    transform: translateY(0);
+  }
+}
+
+.info-item {
+  text-align: center;
+  flex: 1;
+  max-width: 300px;
+}
+
+.info-title {
+  font-size: 16px;
+  color: #333;
+  margin-bottom: 12px;
+  font-weight: 500;
+}
+
+.info-desc {
+  font-size: 13px;
+  color: #666;
+  line-height: 1.6;
+}
+
+/* Page Content Styles */
+.page-content {
+  padding: 40px;
+  background: white;
+  border-radius: 12px;
+  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
+  margin: 20px 0;
+  min-height: 500px;
+}
+
+.page-header {
+  margin-bottom: 40px;
+  padding-bottom: 20px;
+  border-bottom: 1px solid #e8eaed;
+}
+
+.page-title {
+  font-size: 24px;
+  font-weight: 600;
+  color: #333;
+  margin: 0;
+}
+
+.page-body {
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  min-height: 400px;
+}
+
+.placeholder-content {
+  text-align: center;
+  max-width: 400px;
+}
+
+.placeholder-icon {
+  color: #ff4757;
+  margin-bottom: 20px;
+  display: flex;
+  justify-content: center;
+}
+
+.placeholder-title {
+  font-size: 20px;
+  font-weight: 500;
+  color: #333;
+  margin: 0 0 15px 0;
+}
+
+.placeholder-desc {
+  font-size: 14px;
+  color: #666;
+  line-height: 1.6;
+  margin: 0;
+}
+
+/* Responsive */
+@media (max-width: 768px) {
+  .sidebar {
+    transform: translateX(-100%);
+    transition: transform 0.3s;
+  }
+  
+  .main-content {
+    margin-left: 0;
+  }
+  
+  .header-title {
+    display: none;
+  }
+  
+  .upload-area {
+    padding: 60px 20px;
+    margin: 0 10px 30px;
+  }
+  
+  .upload-info {
+    flex-direction: column;
+    gap: 30px;
+    padding: 10px;
+  }
+  
+  .content-wrapper {
+    padding: 15px;
+  }
+  
+  .upload-tabs {
+    gap: 15px;
+  }
+  
+  .page-content {
+    padding: 20px;
+    margin: 10px;
+  }
+  
+  .page-title {
+    font-size: 20px;
+  }
+  
+  .placeholder-title {
+    font-size: 18px;
+  }
+  
+  .placeholder-desc {
+    font-size: 13px;
+  }
+}
diff --git a/API/API-TRM/xiaohongshu-upload-platform/src/App.jsx b/API/API-TRM/xiaohongshu-upload-platform/src/App.jsx
new file mode 100644
index 0000000..8388b7b
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/src/App.jsx
@@ -0,0 +1,410 @@
+import React, { useState } from 'react'
+import { 
+  Home, 
+  Settings, 
+  BarChart3, 
+  PieChart, 
+  TrendingUp, 
+  Activity, 
+  BookOpen, 
+  Users, 
+  Upload, 
+  Image,
+  Video,
+  ChevronDown,
+  User
+} from 'lucide-react'
+import './App.css'
+
+function App() {
+  const [activeTab, setActiveTab] = useState('image')
+  const [expandedMenu, setExpandedMenu] = useState('dashboard')
+  const [activePage, setActivePage] = useState('dashboard') // 新增:当前激活的页面
+  const [isDragOver, setIsDragOver] = useState(false)
+  const [isUploading, setIsUploading] = useState(false)
+  const [uploadedFiles, setUploadedFiles] = useState([])
+  const [uploadProgress, setUploadProgress] = useState(0)
+
+  const validateFiles = (files) => {
+    const validImageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp']
+    const validVideoTypes = ['video/mp4', 'video/mov', 'video/avi']
+    
+    const validTypes = activeTab === 'video' ? validVideoTypes : validImageTypes
+    const maxSize = activeTab === 'video' ? 2 * 1024 * 1024 * 1024 : 32 * 1024 * 1024 // 2GB for video, 32MB for images
+    
+    const invalidFiles = files.filter(file => {
+      return !validTypes.includes(file.type) || file.size > maxSize
+    })
+    
+    if (invalidFiles.length > 0) {
+      alert(`发现 ${invalidFiles.length} 个无效文件,请检查文件格式和大小`)
+      return false
+    }
+    
+    return true
+  }
+
+  const simulateUpload = (files) => {
+    setIsUploading(true)
+    setUploadProgress(0)
+    setUploadedFiles(files)
+    
+    // 模拟上传进度
+    const interval = setInterval(() => {
+      setUploadProgress(prev => {
+        if (prev >= 100) {
+          clearInterval(interval)
+          setIsUploading(false)
+          alert(`成功上传了 ${files.length} 个文件`)
+          return 100
+        }
+        return prev + 10
+      })
+    }, 200)
+  }
+
+  const handleFileUpload = () => {
+    if (isUploading) return
+    
+    const input = document.createElement('input')
+    input.type = 'file'
+    input.accept = activeTab === 'video' ? 'video/*' : 'image/*'
+    input.multiple = activeTab === 'image'
+    input.onchange = (e) => {
+      const files = Array.from(e.target.files)
+      if (files.length > 0 && validateFiles(files)) {
+        simulateUpload(files)
+      }
+    }
+    input.click()
+  }
+
+  const handleDragOver = (e) => {
+    e.preventDefault()
+    e.stopPropagation()
+    setIsDragOver(true)
+  }
+
+  const handleDragLeave = (e) => {
+    e.preventDefault()
+    e.stopPropagation()
+    setIsDragOver(false)
+  }
+
+  const handleDrop = (e) => {
+    e.preventDefault()
+    e.stopPropagation()
+    setIsDragOver(false)
+    
+    if (isUploading) return
+    
+    const files = Array.from(e.dataTransfer.files)
+    if (files.length > 0 && validateFiles(files)) {
+      simulateUpload(files)
+    }
+  }
+
+  const clearUploadedFiles = () => {
+    setUploadedFiles([])
+  }
+
+  const removeFile = (indexToRemove) => {
+    setUploadedFiles(prev => prev.filter((_, index) => index !== indexToRemove))
+  }
+
+  const menuItems = [
+    { id: 'home', label: '首页', icon: Home },
+    { id: 'notebooks', label: '笔记管理', icon: BookOpen },
+    {
+      id: 'dashboard',
+      label: '数据看板',
+      icon: BarChart3,
+      submenu: [
+        { id: 'overview', label: '账号概况' },
+        { id: 'content', label: '内容分析' },
+        { id: 'fans', label: '粉丝数据' }
+      ]
+    },
+    { id: 'activity', label: '活动中心', icon: Activity },
+    { id: 'notes', label: '笔记灵感', icon: BookOpen },
+    { id: 'creator', label: '创作学院', icon: Users },
+    { id: 'journal', label: '创作日刊', icon: BookOpen }
+  ]
+  const toggleMenu = (menuId) => {
+    setExpandedMenu(expandedMenu === menuId ? null : menuId)
+  }
+
+  // 新增:处理页面切换的函数
+  const handlePageChange = (pageId) => {
+    setActivePage(pageId)
+    // 如果点击的是有子菜单的项目,也要展开子菜单
+    const menuItem = menuItems.find(item => item.id === pageId)
+    if (menuItem && menuItem.submenu) {
+      setExpandedMenu(pageId)
+    }
+  }
+
+  return (
+    <div className="app">
+      {/* Header */}
+      <header className="header">
+        <div className="header-left">
+          <div className="logo">小红书</div>
+          <h1 className="header-title">创作服务平台</h1>
+        </div>
+        <div className="header-right">
+          <div className="user-info">
+            <User size={16} />
+            <span>小红薯63081EA1</span>
+          </div>
+        </div>
+      </header>
+
+      {/* Sidebar */}
+      <aside className="sidebar">
+        <button className="publish-btn">发布笔记</button>
+          <nav className="nav-menu">
+          {menuItems.map((item) => (
+            <div key={item.id} className="nav-item">
+              <a
+                href="#"
+                className={`nav-link ${activePage === item.id ? 'active' : ''}`}
+                onClick={(e) => {
+                  e.preventDefault()
+                  if (item.submenu) {
+                    toggleMenu(item.id)
+                  } else {
+                    handlePageChange(item.id)
+                  }
+                }}
+              >
+                <item.icon size={16} />
+                <span>{item.label}</span>
+                {item.submenu && <ChevronDown size={16} style={{ marginLeft: 'auto', transform: expandedMenu === item.id ? 'rotate(180deg)' : 'rotate(0deg)', transition: 'transform 0.3s ease' }} />}
+              </a>
+              
+              {item.submenu && expandedMenu === item.id && (
+                <div className="nav-submenu">
+                  {item.submenu.map((subItem) => (
+                    <a 
+                      key={subItem.id} 
+                      href="#" 
+                      className={`nav-link ${activePage === subItem.id ? 'active' : ''}`}
+                      onClick={(e) => {
+                        e.preventDefault()
+                        handlePageChange(subItem.id)
+                      }}
+                    >
+                      {subItem.label}
+                    </a>
+                  ))}
+                </div>
+              )}
+            </div>
+          ))}
+        </nav>
+      </aside>      {/* Main Content */}
+      <main className="main-content">
+        <div className="content-wrapper">
+          {activePage === 'dashboard' || activePage === 'overview' || activePage === 'content' || activePage === 'fans' ? (
+            // 上传页面内容(数据看板相关页面显示上传功能)
+            <>
+              {/* Upload Tabs */}
+              <div className="upload-tabs">
+                <button
+                  className={`upload-tab ${activeTab === 'video' ? 'active' : ''}`}
+                  onClick={() => setActiveTab('video')}
+                >
+                  上传视频
+                </button>
+                <button
+                  className={`upload-tab ${activeTab === 'image' ? 'active' : ''}`}
+                  onClick={() => setActiveTab('image')}
+                >
+                  上传图文
+                </button>
+              </div>
+
+              {/* Upload Area */}
+              <div 
+                className={`upload-area ${isDragOver ? 'drag-over' : ''}`}
+                onDragOver={handleDragOver}
+                onDragLeave={handleDragLeave}
+                onDrop={handleDrop}
+              >
+                <div className="upload-icon">
+                  {activeTab === 'video' ? <Video /> : <Image />}
+                </div>
+                <h2 className="upload-title">
+                  {activeTab === 'video' ? '拖拽视频到此处或点击上传' : '拖拽图片到此处或点击上传'}
+                </h2>
+                <p className="upload-subtitle">
+                  {activeTab === 'video' ? '(需支持上传格式)' : '(需支持上传格式)'}
+                </p>
+                <button 
+                  className={`upload-btn ${isUploading ? 'uploading' : ''}`} 
+                  onClick={handleFileUpload}
+                  disabled={isUploading}
+                >
+                  {isUploading ? `上传中... ${uploadProgress}%` : (activeTab === 'video' ? '上传视频' : '上传图片')}
+                </button>
+                
+                {/* Upload Progress Bar */}
+                {isUploading && (
+                  <div className="progress-container">
+                    <div className="progress-bar">
+                      <div 
+                        className="progress-fill" 
+                        style={{ width: `${uploadProgress}%` }}
+                      ></div>
+                    </div>
+                    <div className="progress-text">{uploadProgress}%</div>
+                  </div>
+                )}
+              </div>
+
+              {/* File Preview Area */}
+              {uploadedFiles.length > 0 && (
+                <div className="file-preview-area">
+                  <div className="preview-header">
+                    <h3 className="preview-title">已上传文件 ({uploadedFiles.length})</h3>
+                    <button className="clear-files-btn" onClick={clearUploadedFiles}>
+                      清除所有
+                    </button>
+                  </div>
+                  <div className="file-grid">
+                    {uploadedFiles.map((file, index) => (
+                      <div key={index} className="file-item">
+                        <button 
+                          className="remove-file-btn"
+                          onClick={() => removeFile(index)}
+                          title="删除文件"
+                        >
+                          ×
+                        </button>
+                        {file.type?.startsWith('image/') ? (
+                          <div className="file-thumbnail">
+                            <img src={URL.createObjectURL(file)} alt={file.name} />
+                          </div>
+                        ) : (
+                          <div className="file-thumbnail video-thumbnail">
+                            <Video size={24} />
+                          </div>
+                        )}
+                        <div className="file-info">
+                          <div className="file-name" title={file.name}>
+                            {file.name.length > 20 ? file.name.substring(0, 17) + '...' : file.name}
+                          </div>
+                          <div className="file-size">
+                            {(file.size / 1024 / 1024).toFixed(2)} MB
+                          </div>
+                        </div>
+                      </div>
+                    ))}
+                  </div>
+                </div>
+              )}
+
+              {/* Upload Info */}
+              <div className="upload-info fade-in" key={activeTab}>
+                {activeTab === 'image' ? (
+                  <>
+                    <div className="info-item">
+                      <h3 className="info-title">图片大小</h3>
+                      <p className="info-desc">
+                        支持上传的图片大小,<br />
+                        最大32MB的图片文件
+                      </p>
+                    </div>
+                    <div className="info-item">
+                      <h3 className="info-title">图片格式</h3>
+                      <p className="info-desc">
+                        支持上传的图片格式:<br />
+                        推荐使用png、jpg、jpeg、webp,不支持gif、live及其他转化的动图
+                      </p>
+                    </div>
+                    <div className="info-item">
+                      <h3 className="info-title">图片分辨率</h3>
+                      <p className="info-desc">
+                        不要竖图片尺寸,推荐上传3:4尺寸之间,分辨率不低于720*960的图片,<br />
+                        超过17张的时候图片将自动压缩至相配尺寸
+                      </p>
+                    </div>
+                  </>
+                ) : (
+                  <>
+                    <div className="info-item">
+                      <h3 className="info-title">视频大小</h3>
+                      <p className="info-desc">
+                        支持种类5分钟内视频,<br />
+                        最大2GB的视频文件
+                      </p>
+                    </div>
+                    <div className="info-item">
+                      <h3 className="info-title">视频格式</h3>
+                      <p className="info-desc">
+                        支持常用视频格式:<br />
+                        推荐使用mp4、mov
+                      </p>
+                    </div>
+                    <div className="info-item">
+                      <h3 className="info-title">视频分辨率</h3>
+                      <p className="info-desc">
+                        推荐上传720P (1280*720) 及以上视频,<br />
+                        超过1080P的视频可能可能导致上传稍慢且消耗流量
+                      </p>
+                    </div>
+                  </>
+                )}
+              </div>
+            </>
+          ) : (
+            // 其他页面的内容
+            <div className="page-content">
+              <div className="page-header">
+                <h1 className="page-title">
+                  {activePage === 'home' && '首页'}
+                  {activePage === 'notebooks' && '笔记管理'}
+                  {activePage === 'activity' && '活动中心'}
+                  {activePage === 'notes' && '笔记灵感'}
+                  {activePage === 'creator' && '创作学院'}
+                  {activePage === 'journal' && '创作日刊'}
+                </h1>
+              </div>
+              <div className="page-body">
+                <div className="placeholder-content">
+                  <div className="placeholder-icon">
+                    {activePage === 'home' && <Home size={48} />}
+                    {activePage === 'notebooks' && <BookOpen size={48} />}
+                    {activePage === 'activity' && <Activity size={48} />}
+                    {activePage === 'notes' && <BookOpen size={48} />}
+                    {activePage === 'creator' && <Users size={48} />}
+                    {activePage === 'journal' && <BookOpen size={48} />}
+                  </div>
+                  <h3 className="placeholder-title">
+                    {activePage === 'home' && '欢迎来到小红书创作平台'}
+                    {activePage === 'notebooks' && '笔记管理功能开发中'}
+                    {activePage === 'activity' && '活动中心功能开发中'}
+                    {activePage === 'notes' && '笔记灵感功能开发中'}
+                    {activePage === 'creator' && '创作学院功能开发中'}
+                    {activePage === 'journal' && '创作日刊功能开发中'}
+                  </h3>
+                  <p className="placeholder-desc">
+                    {activePage === 'home' && '在这里您可以管理您的创作内容,查看数据分析,获取创作灵感。'}
+                    {activePage === 'notebooks' && '这里将显示您的所有笔记,支持编辑、删除、分类等操作。'}
+                    {activePage === 'activity' && '这里将展示最新的平台活动,让您参与更多有趣的创作活动。'}
+                    {activePage === 'notes' && '这里将为您提供创作灵感和写作建议,帮助您创作更好的内容。'}
+                    {activePage === 'creator' && '这里将提供创作技巧教学和平台规则说明,助您成为优秀创作者。'}
+                    {activePage === 'journal' && '这里将展示创作相关的最新资讯和平台动态。'}
+                  </p>
+                </div>
+              </div>
+            </div>
+          )}
+        </div>
+      </main>
+    </div>
+  )
+}
+
+export default App
diff --git a/API/API-TRM/xiaohongshu-upload-platform/src/index.css b/API/API-TRM/xiaohongshu-upload-platform/src/index.css
new file mode 100644
index 0000000..72c144a
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/src/index.css
@@ -0,0 +1,29 @@
+* {
+  margin: 0;
+  padding: 0;
+  box-sizing: border-box;
+}
+
+body {
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+  background-color: #f5f7fa;
+}
+
+button {
+  border: none;
+  background: none;
+  cursor: pointer;
+  font-family: inherit;
+}
+
+a {
+  text-decoration: none;
+  color: inherit;
+}
+
+#root {
+  width: 100%;
+  min-height: 100vh;
+}
diff --git a/API/API-TRM/xiaohongshu-upload-platform/src/main.jsx b/API/API-TRM/xiaohongshu-upload-platform/src/main.jsx
new file mode 100644
index 0000000..b9a1a6d
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/src/main.jsx
@@ -0,0 +1,10 @@
+import { StrictMode } from 'react'
+import { createRoot } from 'react-dom/client'
+import './index.css'
+import App from './App.jsx'
+
+createRoot(document.getElementById('root')).render(
+  <StrictMode>
+    <App />
+  </StrictMode>,
+)
diff --git a/API/API-TRM/xiaohongshu-upload-platform/vite.config.js b/API/API-TRM/xiaohongshu-upload-platform/vite.config.js
new file mode 100644
index 0000000..8b0f57b
--- /dev/null
+++ b/API/API-TRM/xiaohongshu-upload-platform/vite.config.js
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vite'
+import react from '@vitejs/plugin-react'
+
+// https://vite.dev/config/
+export default defineConfig({
+  plugins: [react()],
+})
diff --git "a/API/API-TRM/\351\241\271\347\233\256\346\201\242\345\244\215\346\212\245\345\221\212.md" "b/API/API-TRM/\351\241\271\347\233\256\346\201\242\345\244\215\346\212\245\345\221\212.md"
new file mode 100644
index 0000000..32a335b
--- /dev/null
+++ "b/API/API-TRM/\351\241\271\347\233\256\346\201\242\345\244\215\346\212\245\345\221\212.md"
@@ -0,0 +1,105 @@
+# 小红书创作平台 - 项目恢复完成 ✅
+
+## 恢复状态
+
+🎉 **项目已完全恢复!**所有代码和功能都已重新创建并正常工作。
+
+## 当前项目包含:
+
+### 📁 文件结构
+```
+e:\api大作业\发布页面/
+├── index.html              # HTML入口文件
+├── package.json            # 项目配置和依赖
+├── README.md              # 详细项目文档
+├── vite.config.js         # Vite构建配置
+├── public/
+│   └── vite.svg          # Vite图标
+└── src/
+    ├── App.css           # 主要样式文件
+    ├── App.jsx           # 主应用组件
+    ├── index.css         # 全局样式
+    └── main.jsx          # React应用入口
+```
+
+### 🚀 核心功能
+
+1. **完整的小红书创作平台界面**
+   - ✅ 头部导航栏(Logo + 用户信息)
+   - ✅ 侧边栏菜单(可展开子菜单)
+   - ✅ 上传区域(图片/视频切换)
+   - ✅ 文件预览网格
+   - ✅ 响应式设计
+
+2. **上传功能**
+   - ✅ 拖拽上传
+   - ✅ 点击上传
+   - ✅ 文件类型验证
+   - ✅ 文件大小限制
+   - ✅ 上传进度条
+   - ✅ 实时预览
+
+3. **文件管理**
+   - ✅ 文件缩略图显示
+   - ✅ 文件信息展示
+   - ✅ 单个文件删除
+   - ✅ 批量清除功能
+   - ✅ 文件计数
+
+4. **交互体验**
+   - ✅ 拖拽视觉反馈
+   - ✅ 悬停动画效果
+   - ✅ 加载状态显示
+   - ✅ 操作成功提示
+
+### 🛠️ 技术栈
+
+- **React 18.3.1** - 前端框架
+- **Vite 6.0.5** - 构建工具
+- **Lucide React 0.468.0** - 图标库
+- **纯CSS** - 样式设计
+
+### 📱 当前状态
+
+- ✅ 依赖安装完成
+- ✅ 开发服务器运行中
+- ✅ 浏览器已打开应用 (http://localhost:5173)
+- ✅ 所有功能正常工作
+- ✅ 无代码错误
+
+### 🎯 功能测试清单
+
+可以测试以下功能:
+
+1. **界面导航**
+   - [ ] 点击侧边栏菜单项
+   - [ ] 展开/收起数据看板子菜单
+   - [ ] 切换上传标签页(图片/视频)
+
+2. **文件上传**
+   - [ ] 点击上传按钮选择文件
+   - [ ] 拖拽文件到上传区域
+   - [ ] 观察上传进度条动画
+   - [ ] 查看文件预览效果
+
+3. **文件管理**
+   - [ ] 悬停文件项查看删除按钮
+   - [ ] 删除单个文件
+   - [ ] 清除所有文件
+
+4. **响应式测试**
+   - [ ] 调整浏览器窗口大小
+   - [ ] 测试移动端适配
+
+### 🔄 后续开发
+
+项目已为API集成做好准备:
+
+1. **替换模拟上传** → 真实API调用
+2. **添加用户认证** → 登录/注册功能
+3. **连接后端数据** → 真实数据存储
+4. **添加路由** → 页面导航功能
+
+---
+
+**🎊 恢复完成!项目已经可以正常使用了!**
diff --git a/JWLLL/main_online.py b/JWLLL/main_online.py
new file mode 100644
index 0000000..0c2dd7b
--- /dev/null
+++ b/JWLLL/main_online.py
@@ -0,0 +1,1017 @@
+# main_online.py
+# 搜索推荐算法服务的主入口
+
+import json
+import numpy as np
+import difflib
+from flask import Flask, request, jsonify, Response
+import pymysql
+import jieba
+from sklearn.feature_extraction.text import TfidfVectorizer
+from sklearn.metrics.pairwise import cosine_similarity
+import pypinyin
+from flask_cors import CORS
+import re
+import Levenshtein
+import os
+import logging
+
+# 设置日志
+logging.basicConfig(
+    level=logging.INFO,
+    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
+)
+logger = logging.getLogger("allpt-search")
+
+# 导入Word2Vec辅助模块
+try:
+    from word2vec_helper import get_word2vec_helper, expand_query, get_similar_words
+    WORD2VEC_ENABLED = True
+    logger.info("Word2Vec模块已加载")
+except ImportError as e:
+    logger.warning(f"Word2Vec模块加载失败: {e},将使用传统搜索")
+    WORD2VEC_ENABLED = False
+
+# 数据库配置
+DB_CONFIG = {
+    "host": "10.126.59.25",
+    "port": 3306,
+    "user": "root",
+    "password": "123456",
+    "database": "redbook",
+    "charset": "utf8mb4"
+}
+
+def get_db_conn():
+    return pymysql.connect(**DB_CONFIG)
+
+def get_pinyin(text):
+    # 返回字符串的全拼音(不带声调,全部小写),支持英文直接返回
+    if not text:
+        return ""
+    import re
+    # 如果全是英文,直接返回小写
+    if re.fullmatch(r'[a-zA-Z]+', text):
+        return text.lower()
+    return ''.join([p[0] for p in pypinyin.pinyin(text, style=pypinyin.NORMAL)])
+
+def get_pinyin_initials(text):
+    # 返回字符串的首字母拼音(全部小写),支持英文直接返回
+    if not text:
+        return ""
+    import re
+    if re.fullmatch(r'[a-zA-Z]+', text):
+        return text.lower()
+    return ''.join([p[0][0] for p in pypinyin.pinyin(text, style=pypinyin.NORMAL)])
+
+# 新增词语相似度计算函数
+def word_similarity(word1, word2):
+    """计算两个词的相似度,支持拼音匹配"""
+    # 直接匹配
+    if word1 == word2:
+        return 1.0
+    
+    # 拼音匹配
+    if get_pinyin(word1) == get_pinyin(word2):
+        return 0.9
+    
+    # 拼音首字母匹配
+    if get_pinyin_initials(word1) == get_pinyin_initials(word2):
+        return 0.7
+    
+    # 字符串相似度
+    return difflib.SequenceMatcher(None, word1, word2).ratio()
+
+def semantic_title_similarity(query, title):
+    """计算查询词与标题的语义相似度"""
+    # 分词
+    query_words = list(jieba.cut(query))
+    title_words = list(jieba.cut(title))
+    
+    if not query_words or not title_words:
+        return 0.0
+    
+    # 计算每个查询词与标题词的最大相似度
+    max_similarities = []
+    key_matches = 0  # 关键词精确匹配数量
+    
+    for q_word in query_words:
+        if len(q_word.strip()) <= 1:  # 忽略单字,减少噪音
+            continue
+            
+        word_sims = [word_similarity(q_word, t_word) for t_word in title_words]
+        if word_sims:
+            max_sim = max(word_sims)
+            max_similarities.append(max_sim)
+            if max_sim > 0.85:  # 认为是关键词匹配
+                key_matches += 1
+    
+    if not max_similarities:
+        return 0.0
+    
+    # 计算平均相似度
+    avg_sim = sum(max_similarities) / len(max_similarities)
+    
+    # 权重计算: 平均相似度占70%,关键词匹配率占30%
+    key_match_ratio = key_matches / len(query_words) if query_words else 0
+    
+    # 标题中包含完整查询短语时给予额外加分
+    exact_bonus = 0.3 if query in title else 0
+    
+    return 0.7 * avg_sim + 0.3 * key_match_ratio + exact_bonus
+
+# 添加语义关联词典,用于增强搜索能力
+def load_semantic_mappings():
+    """
+    加载语义关联映射表,用于增强搜索语义理解
+    返回包含语义映射关系的字典
+    """
+    # 初始化空字典,所有映射将从配置文件加载
+    mappings = {}
+    
+    # 从配置文件加载映射
+    try:
+        config_path = os.path.join(os.path.dirname(__file__), "semantic_config.json")
+        if os.path.exists(config_path):
+            with open(config_path, 'r', encoding='utf-8') as f:
+                mappings = json.load(f)
+            logger.info(f"已从配置文件加载 {len(mappings)} 个语义映射")
+        else:
+            logger.warning(f"语义配置文件不存在: {config_path}")
+    except Exception as e:
+        logger.error(f"加载语义配置文件失败: {e}")
+    
+    return mappings
+
+# 初始化语义映射
+SEMANTIC_MAPPINGS = load_semantic_mappings()
+
+def expand_search_keywords(keyword):
+    """
+    扩展搜索关键词,增加语义关联词
+    """
+    expanded = [keyword]
+    
+    # 分词处理
+    words = list(jieba.cut(keyword))
+    logger.info(f"关键词 '{keyword}' 分词结果: {words}")  # 记录分词结果
+    
+    # 分别对每个分词进行语义扩展
+    for word in words:
+        if word in SEMANTIC_MAPPINGS:
+            # 添加语义关联词
+            mapped_words = SEMANTIC_MAPPINGS[word]
+            expanded.extend(mapped_words)
+            logger.info(f"语义映射: '{word}' -> {mapped_words}")
+            
+            # 移除所有特殊处理部分
+            # 不再对任何特定关键词如"越狱"进行特殊处理
+    
+    # Word2Vec扩展 - 如果可用,对分词结果进行Word2Vec扩展
+    if WORD2VEC_ENABLED:
+        try:
+            # 使用单独的变量记录原始扩展结果,方便记录日志
+            original_expanded = set(expanded)
+            
+            # 首先尝试对整个关键词进行扩展
+            w2v_expanded = set()
+            similar_words = get_similar_words(keyword, topn=3, min_similarity=0.6)
+            w2v_expanded.update(similar_words)
+            
+            # 然后对较长的分词进行扩展
+            for word in words:
+                if len(word) > 1:  # 忽略单字
+                    similar_words = get_similar_words(word, topn=2, min_similarity=0.65)
+                    w2v_expanded.update(similar_words)
+            
+            # 合并结果
+            expanded.extend(w2v_expanded)
+            
+            # 记录日志
+            if w2v_expanded:
+                logger.info(f"Word2Vec扩展: {keyword} -> {list(w2v_expanded)}")
+        except Exception as e:
+            # 出错时记录但不中断搜索流程
+            logger.error(f"Word2Vec扩展失败: {e}")
+            logger.info("将仅使用配置文件中的语义映射")
+    
+    # 去重
+    return list(set(expanded))
+
+# 替换原有的calculate_keyword_relevance函数,采用更通用的相关性算法
+def calculate_keyword_relevance(keyword, item):
+    """计算搜索关键词与条目的相关性得分"""
+    title = item.get('title', '')
+    description = item.get('description', '') or ''
+    tags = item.get('tags', '') or ''
+    category = item.get('category', '') or ''  # 添加category字段
+    
+    # 初始化得分
+    score = 0
+    
+    # 1. 精确匹配(最高优先级)
+    if keyword.lower() == title.lower():
+        return 15.0  # 完全匹配给予最高分
+    
+    # 2. 标题中精确词匹配
+    title_words = re.findall(r'\b\w+\b', title.lower())
+    if keyword.lower() in title_words:
+        score += 10.0  # 作为独立词完全匹配
+    
+    # 3. 标题包含关键词(部分匹配)
+    elif keyword.lower() in title.lower():
+        # 计算关键词所占标题比例
+        match_ratio = len(keyword) / len(title)
+        if match_ratio > 0.5:  # 关键词占标题很大比例
+            score += 8.0
+        else:
+            score += 5.0
+    
+    # 4. 标题分词匹配
+    keyword_words = list(jieba.cut(keyword))
+    title_jieba_words = list(jieba.cut(title))
+    
+    matched_words = 0
+    for k_word in keyword_words:
+        if len(k_word) > 1:  # 忽略单字
+            if k_word in title_jieba_words:
+                matched_words += 1
+            else:
+                # 拼音匹配
+                k_pinyin = get_pinyin(k_word)
+                for t_word in title_jieba_words:
+                    if get_pinyin(t_word) == k_pinyin:
+                        matched_words += 0.8
+                        break
+    
+    if len(keyword_words) > 0:
+        word_match_ratio = matched_words / len(keyword_words)
+        score += 3.0 * word_match_ratio
+    
+    # 5. 拼音相似度
+    keyword_pinyin = get_pinyin(keyword)
+    title_pinyin = get_pinyin(title)
+    
+    if keyword_pinyin == title_pinyin:
+        score += 3.5
+    elif keyword_pinyin in title_pinyin:
+        # 计算拼音在标题中的位置影响
+        pos = title_pinyin.find(keyword_pinyin)
+        if pos == 0:  # 出现在开头
+            score += 3.0
+        else:
+            score += 2.0
+    
+    # 6. 编辑距离相似度
+    try:
+        edit_distance = Levenshtein.distance(keyword.lower(), title.lower())
+        max_len = max(len(keyword), len(title))
+        if max_len > 0:
+            similarity = 1 - (edit_distance / max_len)
+            if similarity > 0.7:
+                score += 1.5 * similarity
+    except:
+        similarity = difflib.SequenceMatcher(None, keyword.lower(), title.lower()).ratio()
+        if similarity > 0.7:
+            score += 1.5 * similarity
+    
+    # 7. 中文字符重叠检测 - 修改为仅当重叠2个以上汉字或占比超过40%时才计分
+    if re.search(r'[\u4e00-\u9fff]', keyword) and re.search(r'[\u4e00-\u9fff]', title):
+        cn_chars_keyword = set(re.findall(r'[\u4e00-\u9fff]', keyword))
+        cn_chars_title = set(re.findall(r'[\u4e00-\u9fff]', title))
+        
+        # 计算重叠的汉字集合
+        overlapped_chars = cn_chars_keyword & cn_chars_title
+        
+        # 仅当重叠汉字数量大于1且占比超过阈值时才计分
+        if len(overlapped_chars) > 1 and len(cn_chars_keyword) > 0:
+            overlap_ratio = len(overlapped_chars) / len(cn_chars_keyword)
+            # 增加重叠比例的阈值要求,防止单个汉字导致的误匹配
+            if overlap_ratio >= 0.4 or len(overlapped_chars) >= 3:
+                score += 2.0 * overlap_ratio
+            # 对于非常低的重叠度,不加分,避免无关内容干扰
+        
+        # 记录日志,帮助调试特定案例
+        if keyword == "明日方舟" and "白日梦想家" in title:
+            logger.info(f"'明日方舟'与'{title}'的汉字重叠: {overlapped_chars}, 重叠比例: {len(overlapped_chars)/len(cn_chars_keyword) if cn_chars_keyword else 0}")
+    
+    # 8. 序列资源检测(如"功夫熊猫2"是"功夫熊猫"的系列)
+    base_title_match = re.match(r'(.*?)([0-9]+|[一二三四五六七八九十]|:|\:|\s+[0-9]+)', title)
+    if base_title_match:
+        base_title = base_title_match.group(1).strip()
+        if keyword.lower() == base_title.lower():
+            score += 2.0
+    
+    # 9. 标签和描述匹配(增加权重)
+    if tags:
+        tags_list = tags.split(',')
+        if keyword in tags_list:
+            score += 1.5  # 提高标签匹配的权重
+        elif any(keyword.lower() in tag.lower() for tag in tags_list):
+            score += 1.0  # 提高部分匹配的权重
+    
+    # 描述匹配增强
+    if keyword.lower() in description.lower():
+        score += 1.5  # 提高描述匹配的权重
+        
+        # 检查关键词在描述中的位置和上下文
+        pos = description.lower().find(keyword.lower())
+        if pos >= 0 and pos < len(description) / 3:
+            # 关键词出现在描述前1/3部分,可能更重要
+            score += 0.5
+    
+    # 考虑分词匹配描述
+    keyword_words = list(jieba.cut(keyword))
+    description_words = list(jieba.cut(description))
+    matched_desc_words = 0
+    for k_word in keyword_words:
+        if len(k_word) > 1 and k_word in description_words:
+            matched_desc_words += 1
+    
+    if len(keyword_words) > 0:
+        desc_match_ratio = matched_desc_words / len(keyword_words)
+        score += 1.0 * desc_match_ratio
+    
+    # 分类匹配
+    if keyword.lower() in category.lower():
+        score += 1.0
+    
+    # 添加语义关联匹配得分
+    # 扩展关键词进行匹配
+    expanded_keywords = expand_search_keywords(keyword)
+    
+    # 检测标题是否包含语义相关词
+    for exp_keyword in expanded_keywords:
+        if exp_keyword != keyword and exp_keyword in title:  # 避免重复计算原关键词
+            # 根据关联词的匹配类型给予不同分数
+            if exp_keyword in ["国宝", "熊猫"] and "功夫熊猫" in title:
+                score += 3.0  # 高度相关的语义映射
+            elif exp_keyword in title:
+                score += 1.5  # 一般语义关联
+    
+    # 对于特殊组合查询,额外加分
+    if ("国宝" in keyword or "熊猫" in keyword) and "电影" in keyword and "功夫熊猫" in title:
+        score += 4.0  # 对"国宝电影"、"熊猫电影"搜"功夫熊猫"特别加分
+    
+    return score
+
+# 创建Flask应用
+app = Flask(__name__)
+CORS(app)  # 允许所有跨域请求
+
+# 添加init_word2vec函数
+def init_word2vec():
+    """初始化Word2Vec模型"""
+    try:
+        helper = get_word2vec_helper()
+        if helper.initialized:
+            logger.info(f"Word2Vec模型已成功加载,词汇量: {len(helper.model.index_to_key)}, 向量维度: {helper.model.vector_size}")
+        else:
+            if helper.load_model():
+                logger.info(f"Word2Vec模型加载成功,词汇量: {len(helper.model.index_to_key)}, 向量维度: {helper.model.vector_size}")
+            else:
+                logger.error("Word2Vec模型加载失败")
+    except Exception as e:
+        logger.error(f"初始化Word2Vec出错: {e}")
+
+# 新的初始化方式:
+def initialize_app():
+    """应用初始化函数,替代before_first_request装饰器"""
+    # 修正:使用正确的函数名
+    # 原代码: init_semantic_mapping()
+    # 修正为使用已定义的函数名
+    global SEMANTIC_MAPPINGS
+    SEMANTIC_MAPPINGS = load_semantic_mappings()  # 更新全局语义映射变量
+    
+    if WORD2VEC_ENABLED:
+        init_word2vec()  # 现在这个函数已经定义了
+
+# 在启动应用之前调用初始化函数
+initialize_app()
+
+# 搜索功能的API
+@app.route('/search', methods=['POST'])
+def search():
+    """
+    搜索功能API
+    请求格式:{
+        "keyword": "关键词",
+        "sort_by": "downloads" | "downloads_asc" | "newest" | "oldest" | "similarity" | "title_asc" | "title_desc",
+        "category": "可选,分类名",
+        "search_mode": "title" | "title_desc" | "tags" | "all"  # 可选,默认"title",
+        "tags": ["标签1", "标签2"]  # 可选,支持传递多个标签
+    }
+    """
+    if request.content_type != 'application/json':
+        return jsonify({"error": "Content-Type must be application/json"}), 415
+
+    data = request.get_json()
+    keyword = data.get("keyword", "").strip()
+    sort_by = data.get("sort_by", "similarity")  # 默认按相似度排序
+    category = data.get("category", None)
+    search_mode = data.get("search_mode", "title")
+    tags = data.get("tags", None)  # 支持传递多个标签
+
+    # 校验参数 - 不管什么模式都要求关键词
+    if not (1 <= len(keyword) <= 20):
+        return jsonify({"error": "请输入1-20个字符"}), 400
+
+    # 第一阶段:数据库查询获取候选集
+    results = []
+    conn = get_db_conn()
+    try:
+        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
+            # 首先尝试查询完全匹配的结果
+            exact_query = f"""
+                SELECT id, title, topic_id, heat, created_at, content
+                FROM posts
+                WHERE title = %s
+            """
+            cursor.execute(exact_query, (keyword,))
+            exact_matches = cursor.fetchall() or []  # 确保返回列表而非元组
+            
+            # 扩展关键词,增加语义关联词
+            expanded_keywords = expand_search_keywords(keyword)
+            logger.info(f"扩展后的关键词: {expanded_keywords}")  # 调试信息
+            
+            # 构建查询条件
+            conditions = []
+            params = []
+            
+            # 标题匹配 - 所有搜索模式都匹配title
+            conditions.append("title LIKE %s")
+            params.append(f"%{keyword}%")
+            
+            # 为扩展关键词添加标题匹配条件
+            for exp_keyword in expanded_keywords:
+                if exp_keyword != keyword:  # 避免重复原关键词
+                    conditions.append("title LIKE %s")
+                    params.append(f"%{exp_keyword}%")
+            
+            # 描述匹配
+            if search_mode in ["title_desc", "all"]:
+                # 原始关键词匹配描述
+                conditions.append("content LIKE %s")
+                params.append(f"%{keyword}%")
+                
+                # 扩展关键词匹配描述
+                for exp_keyword in expanded_keywords:
+                    if exp_keyword != keyword:
+                        conditions.append("content LIKE %s")
+                        params.append(f"%{exp_keyword}%")
+            
+            # 标签匹配
+            # 暂不处理,后续join实现
+            
+            # 分类匹配 - 仅在all模式下
+            if search_mode == "all":
+                # 原始关键词匹配分类
+                conditions.append("topic_id LIKE %s")
+                params.append(f"%{keyword}%")
+                
+                # 扩展关键词匹配分类
+                for exp_keyword in expanded_keywords:
+                    if exp_keyword != keyword:
+                        conditions.append("topic_id LIKE %s")
+                        params.append(f"%{exp_keyword}%")
+            
+            # 构建SQL查询
+            if conditions:
+                where_clause = " OR ".join(conditions)
+                logger.info(f"搜索条件: {where_clause}")
+                logger.info(f"参数列表: {params}")
+                
+                if category:
+                    where_clause = f"({where_clause}) AND topic_id=%s"
+                    params.append(category)
+                
+                sql = f"""
+                    SELECT p.id, p.title, tp.name as category, p.heat, p.created_at, p.content,
+                        GROUP_CONCAT(t.name) as tags
+                    FROM posts p
+                    LEFT JOIN post_tags pt ON p.id = pt.post_id
+                    LEFT JOIN tags t ON pt.tag_id = t.id
+                    LEFT JOIN topics tp ON p.topic_id = tp.id
+                    WHERE {where_clause}
+                    GROUP BY p.id
+                    LIMIT 500
+                """
+                
+                cursor.execute(sql, params)
+                expanded_results = cursor.fetchall()
+                logger.info(f"数据库返回记录数: {len(expanded_results) if expanded_results else 0}")
+            else:
+                expanded_results = []
+
+            # 如果扩展查询和精确匹配都没有结果,获取全部记录进行相关性计算
+            if not expanded_results and not exact_matches:
+                sql = "SELECT p.id, p.title, tp.name as category, p.heat, p.created_at, p.content, GROUP_CONCAT(t.name) as tags FROM posts p LEFT JOIN post_tags pt ON p.id = pt.post_id LEFT JOIN tags t ON pt.tag_id = t.id LEFT JOIN topics tp ON p.topic_id = tp.id"
+                if category:
+                    sql += " WHERE p.topic_id=%s"
+                    category_params = [category]
+                    cursor.execute(sql + " GROUP BY p.id", category_params)
+                else:
+                    cursor.execute(sql + " GROUP BY p.id")
+                
+                all_results = cursor.fetchall() or []  # 确保返回列表
+            else:
+                if isinstance(exact_matches, tuple):
+                    exact_matches = list(exact_matches)
+                if isinstance(expanded_results, tuple):
+                    expanded_results = list(expanded_results)
+                all_results = expanded_results + exact_matches
+            
+            # 对所有结果使用相关性计算规则
+            scored_results = []
+            for item in all_results:
+                # 计算相关性得分
+                relevance_score = calculate_keyword_relevance(keyword, item)
+                
+                # 降低相关性阈值,确保更多结果被保留 (从0.5改为0.1)
+                if relevance_score > 0.1:
+                    item['relevance_score'] = relevance_score
+                    scored_results.append(item)
+                    logger.info(f"匹配项: {item['title']}, 相关性得分: {relevance_score}")
+            
+            # 按相关性得分排序
+            scored_results.sort(key=lambda x: x.get('relevance_score', 0), reverse=True)
+            
+            # 确保精确匹配的结果置顶
+            if exact_matches:
+                for exact_match in exact_matches:
+                    exact_match['relevance_score'] = 20.0  # 超高分确保置顶
+                
+                # 移除scored_results中已经存在于exact_matches的项
+                exact_ids = {item['id'] for item in exact_matches}
+                scored_results = [item for item in scored_results if item['id'] not in exact_ids]
+                
+                # 合并两个结果集
+                results = exact_matches + scored_results
+            else:
+                results = scored_results
+            
+            # 限制返回结果数量
+            results = results[:50]
+            
+    except Exception as e:
+        logger.error(f"搜索出错: {e}")
+        import traceback
+        traceback.print_exc()
+        return jsonify({"error": "搜索系统异常,请稍后再试"}), 500
+    finally:
+        conn.close()
+    
+    # 第二阶段:根据指定方式排序
+    if results:
+        if sort_by == "similarity" or not sort_by:
+            # 保持按相关性得分排序,已经排好了
+            pass
+        elif sort_by == "downloads":
+            results.sort(key=lambda x: x.get("download_count", 0), reverse=True)
+        elif sort_by == "downloads_asc":
+            results.sort(key=lambda x: x.get("download_count", 0))
+        elif sort_by == "newest":
+            results.sort(key=lambda x: x.get("create_time", ""), reverse=True)
+        elif sort_by == "oldest":
+            results.sort(key=lambda x: x.get("create_time", ""))
+        elif sort_by == "title_asc":
+            results.sort(key=lambda x: x.get("title", ""))
+        elif sort_by == "title_desc":
+            results.sort(key=lambda x: x.get("title", ""), reverse=True)
+    
+    # 最终处理:清理不需要返回的字段
+    for item in results:
+        item.pop("description", None)
+        item.pop("tags", None)
+        item.pop("relevance_score", None)
+
+    return Response(json.dumps({"results": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+
+# 推荐功能的API
+@app.route('/recommend_tags', methods=['POST'])
+def recommend_tags():
+    """
+    推荐功能API
+    请求格式:{
+        "user_id": "user1",
+        "tags": ["标签1", "标签2"]  # 可为空
+    }
+    """
+    if request.content_type != 'application/json':
+        return jsonify({"error": "Content-Type must be application/json"}), 415
+
+    data = request.get_json()
+    user_id = data.get("user_id")
+    tags = set(data.get("tags", []))
+
+    # 查询用户已保存的兴趣标签
+    user_tags = set()
+    if user_id:
+        conn = get_db_conn()
+        try:
+            with conn.cursor() as cursor:
+                cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
+                user_tags = set(row[0] for row in cursor.fetchall())
+        finally:
+            conn.close()
+
+    # 合并前端传递的tags和用户兴趣标签
+    all_tags = list(tags | user_tags)
+
+    if not all_tags:
+        return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
+
+    conn = get_db_conn()
+    try:
+        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
+            # 优先用tags字段匹配
+            # 先查找所有tag_id
+            tag_ids = []
+            for tag in all_tags:
+                cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
+                row = cursor.fetchone()
+                if row:
+                    tag_ids.append(row['id'])
+            if not tag_ids:
+                return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
+            tag_placeholders = ','.join(['%s'] * len(tag_ids))
+            sql = f"""
+                SELECT p.id, p.title, tp.name as category, p.heat,
+                       GROUP_CONCAT(tg.name) as tags
+                FROM posts p
+                LEFT JOIN post_tags pt ON p.id = pt.post_id
+                LEFT JOIN tags tg ON pt.tag_id = tg.id
+                LEFT JOIN topics tp ON p.topic_id = tp.id
+                WHERE pt.tag_id IN ({tag_placeholders})
+                GROUP BY p.id
+                LIMIT 50
+            """
+            cursor.execute(sql, tuple(tag_ids))
+            results = cursor.fetchall()
+            # 若无结果,回退title/content模糊匹配
+            if not results:
+                or_conditions = []
+                params = []
+                for tag in all_tags:
+                    or_conditions.append("p.title LIKE %s OR p.content LIKE %s")
+                    params.extend(['%' + tag + '%', '%' + tag + '%'])
+                where_clause = ' OR '.join(or_conditions)
+                sql = f"""
+                    SELECT p.id, p.title, tp.name as category, p.heat,
+                           GROUP_CONCAT(tg.name) as tags
+                    FROM posts p
+                    LEFT JOIN post_tags pt ON p.id = pt.post_id
+                    LEFT JOIN tags tg ON pt.tag_id = tg.id
+                    LEFT JOIN topics tp ON p.topic_id = tp.id
+                    WHERE {where_clause}
+                    GROUP BY p.id
+                    LIMIT 50
+                """
+                cursor.execute(sql, tuple(params))
+                results = cursor.fetchall()
+    finally:
+        conn.close()
+
+    if not results:
+        return Response(json.dumps({"error": "暂无推荐结果"}, ensure_ascii=False), mimetype='application/json; charset=utf-8'), 200
+
+    return Response(json.dumps({"recommendations": results}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+
+# 用户兴趣标签管理API(可选)
+@app.route('/tags', methods=['POST', 'GET', 'DELETE'])
+def user_tags():
+    """
+    POST: 添加用户兴趣标签
+    GET: 查询用户兴趣标签
+    DELETE: 删除用户兴趣标签
+    """
+    if request.method == 'POST':
+        if request.content_type != 'application/json':
+            return jsonify({"error": "Content-Type must be application/json"}), 415
+        data = request.get_json()
+        user_id = data.get("user_id")
+        tags = data.get("tags", [])
+        
+        if not user_id:
+            return jsonify({"error": "用户ID不能为空"}), 400
+        
+        # 确保标签列表格式正确
+        if isinstance(tags, str):
+            tags = [tag.strip() for tag in tags.split(',') if tag.strip()]
+        
+        if not tags:
+            return jsonify({"error": "标签不能为空"}), 400
+        
+        conn = get_db_conn()
+        try:
+            with conn.cursor() as cursor:
+                # 添加用户标签
+                for tag in tags:
+                    # 先查找tag_id
+                    cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
+                    tag_row = cursor.fetchone()
+                    if tag_row:
+                        tag_id = tag_row[0]
+                        cursor.execute("REPLACE INTO user_tags (user_id, tag_id) VALUES (%s, %s)", (user_id, tag_id))
+                conn.commit()
+                # 返回更新后的标签列表
+                cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
+                updated_tags = [row[0] for row in cursor.fetchall()]
+        finally:
+            conn.close()
+        return Response(json.dumps({"msg": "添加成功", "tags": updated_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    elif request.method == 'DELETE':
+        if request.content_type != 'application/json':
+            return jsonify({"error": "Content-Type must be application/json"}), 415
+        data = request.get_json()
+        user_id = data.get("user_id")
+        tags = data.get("tags", [])
+        if not user_id:
+            return jsonify({"error": "用户ID不能为空"}), 400
+        if not tags:
+            return jsonify({"error": "标签不能为空"}), 400
+        
+        conn = get_db_conn()
+        try:
+            with conn.cursor() as cursor:
+                for tag in tags:
+                    cursor.execute("SELECT id FROM tags WHERE name=%s", (tag,))
+                    tag_row = cursor.fetchone()
+                    if tag_row:
+                        tag_id = tag_row[0]
+                        cursor.execute("DELETE FROM user_tags WHERE user_id=%s AND tag_id=%s", (user_id, tag_id))
+                conn.commit()
+                cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
+                remaining_tags = [row[0] for row in cursor.fetchall()]
+        finally:
+            conn.close()
+        return Response(json.dumps({"msg": "删除成功", "tags": remaining_tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    else:  # GET 请求
+        user_id = request.args.get("user_id")
+        if not user_id:
+            return jsonify({"error": "用户ID不能为空"}), 400
+        conn = get_db_conn()
+        try:
+            with conn.cursor() as cursor:
+                cursor.execute("SELECT t.name FROM user_tags ut JOIN tags t ON ut.tag_id = t.id WHERE ut.user_id=%s", (user_id,))
+                tags = [row[0] for row in cursor.fetchall()]
+        finally:
+            conn.close()
+        return Response(json.dumps({"tags": tags}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+
+# 添加/user_tags路由作为/tags的别名
+@app.route('/user_tags', methods=['POST', 'GET', 'DELETE'])
+def user_tags_alias():
+    """
+    /user_tags路由 - 作为/tags路由的别名
+    POST: 添加用户兴趣标签
+    GET: 查询用户兴趣标签
+    DELETE: 删除用户兴趣标签
+    """
+    return user_tags()
+
+# 基于用户的协同过滤推荐API
+@app.route('/user_based_recommend', methods=['POST'])
+def user_based_recommend():
+    """
+    基于用户的协同过滤推荐API
+    请求格式:{
+        "user_id": "user1",
+        "top_n": 5
+    }
+    """
+    if request.content_type != 'application/json':
+        return jsonify({"error": "Content-Type must be application/json"}), 415
+
+    data = request.get_json()
+    user_id = data.get("user_id")
+    top_n = int(data.get("top_n", 5))
+
+    if not user_id:
+        return jsonify({"error": "用户ID不能为空"}), 400
+    
+    conn = get_db_conn()
+    try:
+        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
+            # 1. 检查用户是否存在下载记录(收藏或浏览)
+            cursor.execute("""
+                SELECT COUNT(*) as count
+                FROM behaviors
+                WHERE user_id = %s AND type IN ('favorite', 'view')
+            """, (user_id,))
+            result = cursor.fetchone()
+            user_download_count = result['count'] if result else 0
+            
+            logger.info(f"用户 {user_id} 下载记录数: {user_download_count}")
+            
+            # 如果用户没有足够的行为数据,返回基于热度的推荐
+            if user_download_count < 3:
+                logger.info(f"用户 {user_id} 下载记录不足,返回热门推荐")
+                cursor.execute("""
+                    SELECT p.id, p.title, tp.name as category, p.heat
+                    FROM posts p
+                    LEFT JOIN topics tp ON p.topic_id = tp.id
+                    ORDER BY p.heat DESC
+                    LIMIT %s
+                """, (top_n,))
+                popular_seeds = cursor.fetchall()
+                return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+            
+            # 2. 获取用户已下载(收藏/浏览)的帖子
+            cursor.execute("""
+                SELECT post_id
+                FROM behaviors
+                WHERE user_id = %s AND type IN ('favorite', 'view')
+            """, (user_id,))
+            user_seeds = set(row['post_id'] for row in cursor.fetchall())
+            logger.info(f"用户 {user_id} 已下载种子: {user_seeds}")
+            
+            # 3. 获取所有用户-帖子下载(收藏/浏览)矩阵
+            cursor.execute("""
+                SELECT user_id, post_id
+                FROM behaviors
+                WHERE created_at > DATE_SUB(NOW(), INTERVAL 3 MONTH)
+                AND user_id <> %s AND type IN ('favorite', 'view')
+            """, (user_id,))
+            download_records = cursor.fetchall()
+            
+            if not download_records:
+                logger.info(f"没有其他用户的下载记录,返回热门推荐")
+                cursor.execute("""
+                    SELECT p.id, p.title, tp.name as category, p.heat
+                    FROM posts p
+                    LEFT JOIN topics tp ON p.topic_id = tp.id
+                    ORDER BY p.heat DESC
+                    LIMIT %s
+                """, (top_n,))
+                popular_seeds = cursor.fetchall()
+                return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+            
+            # 构建用户-物品矩阵
+            user_item_matrix = {}
+            for record in download_records:
+                uid = record['user_id']
+                sid = record['post_id']
+                if uid not in user_item_matrix:
+                    user_item_matrix[uid] = set()
+                user_item_matrix[uid].add(sid)
+            
+            # 4. 计算用户相似度
+            similar_users = []
+            for other_id, other_seeds in user_item_matrix.items():
+                if other_id == user_id:
+                    continue
+                intersection = len(user_seeds.intersection(other_seeds))
+                union = len(user_seeds.union(other_seeds))
+                if union > 0 and intersection > 0:
+                    similarity = intersection / union
+                    similar_users.append((other_id, similarity, other_seeds))
+            logger.info(f"找到 {len(similar_users)} 个相似用户")
+            similar_users.sort(key=lambda x: x[1], reverse=True)
+            similar_users = similar_users[:5]
+            # 5. 基于相似用户推荐帖子
+            candidate_seeds = {}
+            for similar_user, similarity, seeds in similar_users:
+                logger.info(f"相似用户 {similar_user}, 相似度 {similarity}")
+                for post_id in seeds:
+                    if post_id not in user_seeds:
+                        if post_id not in candidate_seeds:
+                            candidate_seeds[post_id] = 0
+                        candidate_seeds[post_id] += similarity
+            if not candidate_seeds:
+                logger.info(f"没有找到候选种子,返回热门推荐")
+                cursor.execute("""
+                    SELECT p.id, p.title, tp.name as category, p.heat
+                    FROM posts p
+                    LEFT JOIN topics tp ON p.topic_id = tp.id
+                    ORDER BY p.heat DESC
+                    LIMIT %s
+                """, (top_n,))
+                popular_seeds = cursor.fetchall()
+                return Response(json.dumps({"recommendations": popular_seeds, "type": "popular"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+            # 6. 获取推荐帖子的详细信息
+            recommended_seeds = sorted(candidate_seeds.items(), key=lambda x: x[1], reverse=True)[:top_n]
+            post_ids = [post_id for post_id, _ in recommended_seeds]
+            format_strings = ','.join(['%s'] * len(post_ids))
+            cursor.execute(f"""
+                SELECT p.id, p.title, tp.name as category, p.heat
+                FROM posts p
+                LEFT JOIN topics tp ON p.topic_id = tp.id
+                WHERE p.id IN ({format_strings})
+            """, tuple(post_ids))
+            result_seeds = cursor.fetchall()
+            seed_score_map = {post_id: score for post_id, score in recommended_seeds}
+            result_seeds.sort(key=lambda x: seed_score_map.get(x['id'], 0), reverse=True)
+            logger.info(f"返回 {len(result_seeds)} 个基于协同过滤的推荐")
+            return Response(json.dumps({"recommendations": result_seeds, "type": "collaborative"}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    except Exception as e:
+        logger.error(f"推荐系统错误: {e}")
+        import traceback
+        traceback.print_exc()
+        return Response(json.dumps({"error": "推荐系统异常,请稍后再试", "details": str(e)}, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    finally:
+        conn.close()
+@app.route('/word2vec_status', methods=['GET'])
+def word2vec_status():
+    """
+    检查Word2Vec模型状态
+    返回模型是否加载、词汇量等信息
+    """
+    if not WORD2VEC_ENABLED:
+        return Response(json.dumps({
+            "enabled": False,
+            "message": "Word2Vec功能未启用"
+        }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    try:
+        helper = get_word2vec_helper()
+        status = {
+            "enabled": WORD2VEC_ENABLED,
+            "initialized": helper.initialized,
+            "vocab_size": len(helper.model.index_to_key) if helper.model else 0,
+            "vector_size": helper.model.vector_size if helper.model else 0
+        }
+        
+        # 测试几个常用词的相似词,展示模型效果
+        test_results = {}
+        test_words = ["电影", "动作", "科幻", "动漫", "游戏"]
+        for word in test_words:
+            similar_words = helper.get_similar_words(word, topn=5)
+            test_results[word] = similar_words
+        
+        status["test_results"] = test_results
+        return Response(json.dumps(status, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    except Exception as e:
+        return Response(json.dumps({
+            "enabled": WORD2VEC_ENABLED,
+            "initialized": False,
+            "error": str(e)
+        }, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+
+# 添加一个临时诊断端点
+@app.route('/debug_search', methods=['POST'])
+def debug_search():
+    """临时的调试端点,用于检查数据库中的记录"""
+    if request.content_type != 'application/json':
+        return jsonify({"error": "Content-Type must be application/json"}), 415
+
+    data = request.get_json()
+    keyword = data.get("keyword", "").strip()
+    
+    conn = get_db_conn()
+    try:
+        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
+            # 尝试查询包含特定词的所有记录
+            queries = [
+                ("标题中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE title LIKE '%{keyword}%' LIMIT 10"),
+                ("描述中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE description LIKE '%{keyword}%' LIMIT 10"),
+                ("标签中包含关键词", f"SELECT seed_id, title, description, tags FROM pt_seed WHERE FIND_IN_SET('{keyword}', tags) LIMIT 10"),
+                ("肖申克的救赎", "SELECT seed_id, title, description, tags FROM pt_seed WHERE title = '肖申克的救赎'")
+            ]
+            
+            results = {}
+            for query_name, query in queries:
+                cursor.execute(query)
+                results[query_name] = cursor.fetchall()
+                
+            return Response(json.dumps(results, ensure_ascii=False), mimetype='application/json; charset=utf-8')
+    finally:
+        conn.close()
+
+"""
+接口本地测试方法(可直接运行main_online.py后用curl或Postman测试):
+
+1. 搜索接口
+curl -X POST http://127.0.0.1:5000/search -H "Content-Type: application/json" -d '{"keyword":"电影","sort_by":"downloads"}'
+
+2. 标签推荐接口
+curl -X POST http://127.0.0.1:5000/recommend_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
+
+3. 用户兴趣标签管理(添加标签)
+curl -X POST http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
+
+4. 用户兴趣标签管理(查询标签)
+curl "http://127.0.0.1:5000/user_tags?user_id=1"
+
+5. 用户兴趣标签管理(删除标签)
+curl -X DELETE http://127.0.0.1:5000/user_tags -H "Content-Type: application/json" -d '{"user_id":"1","tags":["动作","科幻"]}'
+
+6. 协同过滤推荐
+curl -X POST http://127.0.0.1:5000/user_based_recommend -H "Content-Type: application/json" -d '{"user_id":"user1","top_n":3}'
+
+7. Word2Vec状态检查
+curl "http://127.0.0.1:5000/word2vec_status"
+
+8. 调试接口(临时)
+curl -X POST http://127.0.0.1:5000/debug_search -H "Content-Type: application/json" -d '{"keyword":"电影"}'
+
+所有接口均可用Postman按上述参数测试。
+"""
+
+if __name__ == "__main__":
+    try:
+        logger.info("搜索推荐服务启动中...")
+        app.run(host="0.0.0.0", port=5000)
+    except Exception as e:
+        logger.error(f"启动异常: {e}")
+        import traceback
+        traceback.print_exc()
diff --git a/JWLLL/semantic_config.json b/JWLLL/semantic_config.json
new file mode 100644
index 0000000..9f54454
--- /dev/null
+++ b/JWLLL/semantic_config.json
@@ -0,0 +1,73 @@
+{
+  "国宝": ["熊猫", "大熊猫", "功夫熊猫", "四川", "成都", "保护动物"],
+  "熊猫": ["国宝", "大熊猫", "功夫熊猫", "竹子", "四川", "黑白"],
+  "功夫": ["武术", "格斗", "武打", "功夫熊猫", "李小龙", "成龙", "太极", "截拳道", "中国功夫"],
+  
+  "梦": ["梦想", "梦境", "白日梦", "白日梦想家", "潜意识", "睡眠", "做梦"],
+  "白日梦": ["梦想", "幻想", "白日梦想家", "想象", "憧憬"],
+  
+  "魔戒": ["指环王", "魔戒再现", "中土世界", "霍比特人", "精灵", "魔法", "奇幻"],
+  "指环": ["魔戒", "指环王", "戒指", "魔戒再现", "首饰"],
+  "中土世界": ["魔戒", "指环王", "霍比特人", "精灵", "矮人", "奇幻"],
+  
+  "漫威": ["复仇者", "钢铁侠", "蜘蛛侠", "美国队长", "雷神", "绿巨人", "黑寡妇", "惊奇队长", "超级英雄", "漫画"],
+  "钢铁侠": ["托尼斯塔克", "钢铁战衣", "贾维斯", "复仇者", "漫威", "超级英雄"],
+  "蜘蛛侠": ["彼得帕克", "蜘蛛", "纽约", "漫威", "超级英雄", "蜘蛛感应"],
+  
+  "DC": ["蝙蝠侠", "超人", "神奇女侠", "正义联盟", "闪电侠", "水行侠", "超级英雄", "漫画"],
+  "蝙蝠侠": ["布鲁斯韦恩", "高谭市", "小丑", "罗宾", "DC", "超级英雄"],
+  "超人": ["克拉克肯特", "氪星", "莱克斯卢瑟", "超能力", "DC", "超级英雄"],
+  
+  "星球大战": ["星战", "原力", "天行者", "达斯维达", "尤达", "绝地武士", "光剑", "帝国", "科幻"],
+  "原力": ["绝地武士", "星球大战", "天行者", "尤达", "光剑", "西斯", "科幻"],
+  
+  "哈利波特": ["魔法", "霍格沃茨", "魔杖", "魔法石", "伏地魔", "巫师", "奇幻", "魔幻"],
+  "魔法": ["巫师", "法术", "咒语", "哈利波特", "霍格沃茨", "魔杖", "奇幻", "魔幻"],
+  
+  "科幻": ["未来", "太空", "星际", "外星人", "人工智能", "机器人", "时空", "星球大战", "星际穿越"],
+  "太空": ["宇宙", "星球", "卫星", "宇航员", "航天", "科幻", "星际", "外太空"],
+  "人工智能": ["AI", "机器学习", "深度学习", "神经网络", "机器人", "算法", "科技", "科幻"],
+  
+  "动作": ["武打", "格斗", "功夫", "特技", "追逐", "冒险", "刺激", "爆破"],
+  "冒险": ["探险", "奇遇", "探索", "未知", "旅程", "冒险家", "刺激", "危险"],
+  "奇幻": ["魔法", "魔幻", "神话", "异世界", "精灵", "龙", "魔戒", "哈利波特"],
+  
+  "悬疑": ["推理", "谜题", "侦探", "神秘", "悬念", "惊悚", "犯罪", "悬疑片"],
+  "推理": ["侦探", "线索", "谜题", "破案", "悬疑", "逻辑", "智力", "悬疑片"],
+  
+  "恐怖": ["惊悚", "鬼怪", "恶魔", "惊吓", "血腥", "恐怖片", "心理恐惧", "超自然"],
+  "鬼怪": ["幽灵", "鬼魂", "妖怪", "超自然", "恐怖", "惊悚", "诡异", "恐怖片"],
+  
+  "喜剧": ["搞笑", "幽默", "欢乐", "笑声", "喜剧片", "滑稽", "逗乐", "喜剧演员"],
+  "搞笑": ["幽默", "笑话", "喜剧", "逗乐", "滑稽", "欢乐", "喜剧片", "喜剧演员"],
+  
+  "战争": ["军事", "战场", "士兵", "军队", "战役", "武器", "战争片", "历史战争"],
+  "军事": ["军队", "武器", "战争", "军人", "战略", "战术", "国防", "军事片"],
+  
+  "剧情": ["情节", "故事", "叙事", "人物", "感人", "真实", "戏剧性", "剧情片"],
+  "历史": ["古代", "历史事件", "历史人物", "朝代", "文明", "历史片", "传记", "纪实"],
+  
+  "纪录片": ["真实记录", "纪实", "历史", "自然", "科学", "社会", "文化", "探索"],
+  "动画": ["卡通", "动漫", "动画片", "动画电影", "CG", "3D动画", "手绘", "二次元"],
+  
+  "音乐": ["歌曲", "旋律", "节奏", "乐器", "演唱", "音乐家", "音乐剧", "音乐会"],
+  "歌曲": ["歌词", "唱歌", "歌手", "流行歌曲", "音乐", "专辑", "单曲", "MV"],
+  
+  "爱情": ["恋爱", "浪漫", "情侣", "爱情故事", "爱情片", "感情", "爱意", "约会"],
+  "浪漫": ["爱情", "情感", "温馨", "甜蜜", "爱意", "爱情片", "情侣", "表白"],
+  
+  "Netflix": ["网飞", "流媒体", "自制剧", "电视剧", "纸牌屋", "怪奇物语", "王冠", "订阅"],
+  "迪士尼": ["米老鼠", "唐老鸭", "公主", "动画", "迪士尼乐园", "皮克斯", "童话", "漫威"],
+  
+  "游戏": ["电子游戏", "游戏机", "主机游戏", "PC游戏", "手游", "网游", "单机", "多人游戏"],
+  "动漫": ["日本动画", "漫画", "二次元", "动画", "动画片", "ACGN", "宅文化", "御宅族"],
+  
+  "日本": ["东京", "京都", "大阪", "日本文化", "日本料理", "樱花", "动漫", "武士道"],
+  "美国": ["纽约", "洛杉矶", "华盛顿", "美国文化", "好莱坞", "自由女神像", "美式"],
+  
+  "教育": ["学习", "知识", "课程", "教学", "学校", "教科书", "老师", "学生"],
+  "技术": ["科技", "工程", "编程", "软件", "硬件", "开发", "技术革新", "IT"],
+  
+  "监狱": ["越狱", "囚犯", "牢房", "服刑", "狱警"],
+  "越狱": ["监狱", "囚犯", "逃狱", "越狱计划", "监狱逃脱"]
+}
diff --git a/JWLLL/word2vec_helper.py b/JWLLL/word2vec_helper.py
new file mode 100644
index 0000000..ecd1a72
--- /dev/null
+++ b/JWLLL/word2vec_helper.py
@@ -0,0 +1,279 @@
+# word2vec_helper.py
+# Word2Vec模型加载与使用的辅助模块
+
+import os
+import numpy as np
+from gensim.models import KeyedVectors, Word2Vec
+import jieba
+import logging
+import time
+
+# 设置日志
+logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
+
+class Word2VecHelper:
+    def __init__(self, model_path=None):
+        """
+        初始化Word2Vec辅助类
+        
+        参数:
+            model_path: 预训练模型路径,支持word2vec格式和二进制格式
+                        如果为None,将使用默认路径或尝试下载小型模型
+        """
+        self.model = None
+        
+        # 更改默认模型路径和备用选项
+        if model_path:
+            self.model_path = model_path
+        else:
+            # 首选路径 - 大型腾讯模型
+            primary_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 
+                                      "models", "chinese_word2vec.bin")
+            
+            # 备用路径 - 小型模型
+            backup_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 
+                                     "models", "chinese_word2vec_small.bin")
+            
+            if os.path.exists(primary_path):
+                self.model_path = primary_path
+            elif os.path.exists(backup_path):
+                self.model_path = backup_path
+            else:
+                # 如果都不存在,可以尝试自动下载小模型
+                self.model_path = primary_path
+                self._try_download_small_model()
+        
+        self.initialized = False
+        # 缓存查询结果,提高性能
+        self.similarity_cache = {}
+        self.similar_words_cache = {}
+    
+    def _try_download_small_model(self):
+        """尝试下载小型词向量模型作为备用选项"""
+        try:
+            import gensim.downloader as api
+            logging.info("尝试下载小型中文词向量模型...")
+            
+            # 创建模型目录
+            os.makedirs(os.path.dirname(self.model_path), exist_ok=True)
+            
+            # 尝试下载fastText的小型中文模型
+            small_model = api.load("fasttext-wiki-news-subwords-300")
+            small_model.save(self.model_path.replace(".bin", "_small.bin"))
+            logging.info(f"小型模型已下载并保存到 {self.model_path}")
+        except Exception as e:
+            logging.error(f"无法下载备用模型: {e}")
+
+    def load_model(self):
+        """加载Word2Vec模型"""
+        try:
+            start_time = time.time()
+            logging.info(f"开始加载Word2Vec模型: {self.model_path}")
+            
+            # 判断文件扩展名,选择合适的加载方式
+            if self.model_path.endswith('.bin'):
+                # 加载二进制格式的模型
+                self.model = KeyedVectors.load_word2vec_format(self.model_path, binary=True)
+            else:
+                # 加载文本格式的模型或gensim模型
+                self.model = Word2Vec.load(self.model_path).wv
+                
+            self.initialized = True
+            logging.info(f"Word2Vec模型加载完成,耗时 {time.time() - start_time:.2f} 秒")
+            logging.info(f"词向量维度: {self.model.vector_size}")
+            logging.info(f"词汇表大小: {len(self.model.index_to_key)}")
+            return True
+        except Exception as e:
+            logging.error(f"加载Word2Vec模型失败: {e}")
+            self.initialized = False
+            return False
+    
+    def ensure_initialized(self):
+        """确保模型已初始化"""
+        if not self.initialized:
+            return self.load_model()
+        return True
+    
+    def get_similar_words(self, word, topn=10, min_similarity=0.5):
+        """
+        获取与给定词语最相似的词语列表
+        
+        参数:
+            word: 输入词语
+            topn: 返回相似词的数量
+            min_similarity: 最小相似度阈值
+        返回:
+            相似词列表,如果词不存在或模型未加载则返回空列表
+        """
+        if not self.ensure_initialized():
+            return []
+            
+        # 检查缓存
+        cache_key = f"{word}_{topn}_{min_similarity}"
+        if cache_key in self.similar_words_cache:
+            return self.similar_words_cache[cache_key]
+        
+        try:
+            # 如果词不在词汇表中,进行分词处理
+            if word not in self.model.key_to_index:
+                # 对中文词进行分词,然后查找每个子词的相似词
+                word_parts = list(jieba.cut(word))
+                
+                if not word_parts:
+                    return []
+                
+                # 如果存在多个子词,找到存在于模型中的子词
+                valid_parts = [w for w in word_parts if w in self.model.key_to_index]
+                
+                if not valid_parts:
+                    return []
+                
+                # 使用最长的有效子词或第一个有效子词
+                valid_parts.sort(key=len, reverse=True)
+                word = valid_parts[0]
+                
+                # 如果替换后的词仍不在词汇表中,返回空列表
+                if word not in self.model.key_to_index:
+                    return []
+            
+            # 获取相似词
+            similar_words = self.model.most_similar(word, topn=topn*2)  # 多获取一些,后续过滤
+            
+            # 过滤低于阈值的结果,并只返回词语(不返回相似度)
+            filtered_words = [w for w, sim in similar_words if sim >= min_similarity][:topn]
+            
+            # 缓存结果
+            self.similar_words_cache[cache_key] = filtered_words
+            return filtered_words
+            
+        except Exception as e:
+            logging.error(f"获取相似词失败: {e}, 词语: {word}")
+            return []
+    
+    def calculate_similarity(self, word1, word2):
+        """
+        计算两个词的相似度
+        
+        参数:
+            word1, word2: 输入词语
+        返回:
+            相似度分数(0-1),如果任意词不存在则返回0
+        """
+        if not self.ensure_initialized():
+            return 0
+            
+        # 检查缓存
+        cache_key = f"{word1}_{word2}"
+        reverse_key = f"{word2}_{word1}"
+        
+        if cache_key in self.similarity_cache:
+            return self.similarity_cache[cache_key]
+        if reverse_key in self.similarity_cache:
+            return self.similarity_cache[reverse_key]
+        
+        try:
+            # 检查词是否在词汇表中
+            if word1 not in self.model.key_to_index or word2 not in self.model.key_to_index:
+                return 0
+            
+            similarity = self.model.similarity(word1, word2)
+            
+            # 缓存结果
+            self.similarity_cache[cache_key] = similarity
+            return similarity
+            
+        except Exception as e:
+            logging.error(f"计算相似度失败: {e}, 词语: {word1}, {word2}")
+            return 0
+    
+    def expand_query(self, query, topn=5, min_similarity=0.6):
+        """
+        扩展查询词,返回相关词汇
+        
+        参数:
+            query: 查询词
+            topn: 每个词扩展的相似词数量
+            min_similarity: 最小相似度阈值
+        返回:
+            扩展后的词语列表
+        """
+        if not self.ensure_initialized():
+            return [query]
+            
+        expanded_terms = [query]
+        
+        # 对查询进行分词
+        words = list(jieba.cut(query))
+        
+        # 为每个词找相似词
+        for word in words:
+            if len(word) <= 1:  # 忽略单字,减少噪音
+                continue
+                
+            similar_words = self.get_similar_words(word, topn=topn, min_similarity=min_similarity)
+            expanded_terms.extend(similar_words)
+        
+        # 确保唯一性
+        return list(set(expanded_terms))
+
+# 单例模式,全局使用一个模型实例
+_word2vec_helper = None
+
+def get_word2vec_helper(model_path=None):
+    """获取Word2Vec辅助类的全局单例"""
+    global _word2vec_helper
+    if _word2vec_helper is None:
+        _word2vec_helper = Word2VecHelper(model_path)
+        _word2vec_helper.ensure_initialized()
+    return _word2vec_helper
+
+# 便捷函数,方便直接调用
+def get_similar_words(word, topn=10, min_similarity=0.5):
+    """获取相似词的便捷函数"""
+    helper = get_word2vec_helper()
+    return helper.get_similar_words(word, topn, min_similarity)
+
+def calculate_similarity(word1, word2):
+    """计算相似度的便捷函数"""
+    helper = get_word2vec_helper()
+    return helper.calculate_similarity(word1, word2)
+
+def expand_query(query, topn=5, min_similarity=0.6):
+    """扩展查询的便捷函数"""
+    helper = get_word2vec_helper()
+    return helper.expand_query(query, topn, min_similarity)
+
+# 使用示例
+if __name__ == "__main__":
+    # 测试模型加载和词语相似度
+    helper = get_word2vec_helper()
+    
+    # 测试词
+    test_words = ["电影", "功夫", "熊猫", "科幻", "漫威"]
+    
+    for word in test_words:
+        print(f"\n{word} 的相似词:")
+        similar = helper.get_similar_words(word, topn=5)
+        for sim_word in similar:
+            print(f"  - {sim_word}")
+    
+    # 测试相似度计算
+    word_pairs = [
+        ("电影", "电视"),
+        ("功夫", "武术"),
+        ("科幻", "未来"),
+        ("漫威", "超级英雄")
+    ]
+    
+    print("\n词语相似度:")
+    for w1, w2 in word_pairs:
+        sim = helper.calculate_similarity(w1, w2)
+        print(f"  {w1} <-> {w2}: {sim:.4f}")
+    
+    # 测试查询扩展
+    test_queries = ["功夫熊猫", "科幻电影", "漫威英雄"]
+    
+    print("\n查询扩展:")
+    for query in test_queries:
+        expanded = helper.expand_query(query)
+        print(f"  {query} -> {expanded}")
diff --git "a/JWLLL/\346\216\245\345\217\243\346\265\213\350\257\225\350\257\264\346\230\216.md" "b/JWLLL/\346\216\245\345\217\243\346\265\213\350\257\225\350\257\264\346\230\216.md"
new file mode 100644
index 0000000..1537055
--- /dev/null
+++ "b/JWLLL/\346\216\245\345\217\243\346\265\213\350\257\225\350\257\264\346\230\216.md"
@@ -0,0 +1,186 @@
+# 接口说明文档
+
+本服务为资源搜索与推荐API,所有接口均支持Postman测试。每个接口均包含功能说明、请求方式、参数、返回值、详细Postman测试方法,并补充了核心逻辑和原理说明。
+
+---
+
+## 1. 搜索接口
+- **接口功能**:根据关键词、分类、标签等条件搜索资源。
+- **核心逻辑与原理**:
+  - 支持关键词分词、拼音、语义扩展(包括自定义语义映射和Word2Vec相似词扩展)。
+  - 支持多字段(标题、内容、分类、标签)模糊匹配。
+  - 相关性打分综合考虑精确匹配、分词、拼音、标签、描述、分类等多种因素。
+  - 支持多种排序方式(热度、时间、相似度等)。
+- **请求方式**:POST
+- **URL**:`/search`
+- **请求参数**:
+  | 参数名      | 类型    | 必填 | 说明                                   |
+  | ----------- | ------- | ---- | -------------------------------------- |
+  | keyword     | string  | 是   | 搜索关键词                             |
+  | sort_by     | string  | 否   | 排序方式(downloads、similarity等)    |
+  | category    | string  | 否   | 分类名                                 |
+  | search_mode | string  | 否   | 搜索模式(title、title_desc、all等)   |
+  | tags        | array   | 否   | 标签数组                               |
+- **返回说明**:
+  - results: 资源列表,每项包含id、title、category、heat、created_at等字段。
+
+**Postman测试方法:**
+1. 新建POST请求,URL填`http://127.0.0.1:5000/search`
+2. Body选择raw,类型JSON,内容示例:
+   ```json
+   {
+     "keyword": "电影",
+     "sort_by": "downloads"
+   }
+   ```
+3. 点击Send,查看返回结果。
+
+---
+
+## 2. 标签推荐接口
+- **接口功能**:根据用户兴趣标签推荐相关资源。
+- **核心逻辑与原理**:
+  - 首先根据用户兴趣标签(user_tags表+tags表)查找相关资源。
+  - 若无结果,则用标签名模糊匹配资源标题和内容。
+  - 推荐结果按相关性和热度排序。
+- **请求方式**:POST
+- **URL**:`/recommend_tags`
+- **请求参数**:
+  | 参数名   | 类型    | 必填 | 说明           |
+  | -------- | ------- | ---- | -------------- |
+  | user_id  | string  | 是   | 用户ID         |
+  | tags     | array   | 否   | 用户关注标签   |
+- **返回说明**:
+  - recommendations: 推荐资源列表。
+
+**Postman测试方法:**
+1. 新建POST请求,URL填`http://127.0.0.1:5000/recommend_tags`
+2. Body选择raw,类型JSON,内容示例:
+   ```json
+   {
+     "user_id": "1",
+     "tags": ["动作", "科幻"]
+   }
+   ```
+3. 点击Send,查看推荐结果。
+
+---
+
+## 3. 用户兴趣标签管理接口
+- **接口功能**:管理用户兴趣标签(增删查)。
+- **核心逻辑与原理**:
+  - 用户标签数据存储在 user_tags 表,通过 tag_id 关联 tags 表,所有操作均以标签名为主。
+  - 支持添加、删除、查询用户兴趣标签。
+- **请求方式**:POST/GET/DELETE
+- **URL**:`/user_tags` 或 `/tags`
+- **请求参数**:
+  - POST/DELETE:
+    | 参数名  | 类型    | 必填 | 说明     |
+    | ------- | ------- | ---- | -------- |
+    | user_id | string  | 是   | 用户ID   |
+    | tags    | array   | 是   | 标签数组 |
+  - GET:
+    | 参数名  | 类型    | 必填 | 说明     |
+    | ------- | ------- | ---- | -------- |
+    | user_id | string  | 是   | 用户ID   |
+- **返回说明**:
+  - tags: 用户当前兴趣标签列表。
+
+**Postman测试方法:**
+- 添加标签(POST):
+  1. 新建POST请求,URL填`http://127.0.0.1:5000/user_tags`
+  2. Body选择raw,类型JSON:
+     ```json
+     {
+       "user_id": "1",
+       "tags": ["动作", "科幻"]
+     }
+     ```
+  3. Send。
+- 查询标签(GET):
+  1. 新建GET请求,URL填`http://127.0.0.1:5000/user_tags?user_id=1`
+  2. Send。
+- 删除标签(DELETE):
+  1. 新建DELETE请求,URL填`http://127.0.0.1:5000/user_tags`
+  2. Body选择raw,类型JSON:
+     ```json
+     {
+       "user_id": "1",
+       "tags": ["动作", "科幻"]
+     }
+     ```
+  3. Send。
+
+---
+
+## 4. 协同过滤推荐接口
+- **接口功能**:基于用户行为的个性化推荐。
+- **核心逻辑与原理**:
+  - 基于 behaviors 表的用户行为(type='favorite' 或 'view')构建用户-物品矩阵。
+  - 计算用户与其他用户的兴趣重叠度(Jaccard相似度=交集/并集),找出最相似的用户。
+  - 推荐这些相似用户收藏/浏览过、但当前用户未看过的帖子。
+  - 若用户行为数据不足或无相似用户,则推荐全站热门资源。
+- **请求方式**:POST
+- **URL**:`/user_based_recommend`
+- **请求参数**:
+  | 参数名  | 类型    | 必填 | 说明         |
+  | ------- | ------- | ---- | ------------ |
+  | user_id | string  | 是   | 用户ID       |
+  | top_n   | int     | 否   | 推荐数量     |
+- **返回说明**:
+  - recommendations: 推荐资源列表。
+
+**Postman测试方法:**
+1. 新建POST请求,URL填`http://127.0.0.1:5000/user_based_recommend`
+2. Body选择raw,类型JSON:
+   ```json
+   {
+     "user_id": "1",
+     "top_n": 3
+   }
+   ```
+3. Send。
+
+---
+
+## 5. Word2Vec状态检查接口
+- **接口功能**:检查Word2Vec模型加载状态。
+- **核心逻辑与原理**:
+  - 检查Word2Vec模型是否加载成功,返回词汇量、向量维度、部分词的相似词等信息。
+- **请求方式**:GET
+- **URL**:`/word2vec_status`
+- **返回说明**:
+  - enabled, initialized, vocab_size, vector_size, test_results等。
+
+**Postman测试方法:**
+1. 新建GET请求,URL填`http://127.0.0.1:5000/word2vec_status`
+2. Send。
+
+---
+
+## 6. 调试接口
+- **接口功能**:数据库调试与数据检查。
+- **核心逻辑与原理**:
+  - 通过多种SQL查询,辅助开发者调试数据库内容和搜索命中情况。
+- **请求方式**:POST
+- **URL**:`/debug_search`
+- **请求参数**:
+  | 参数名  | 类型    | 必填 | 说明     |
+  | ------- | ------- | ---- | -------- |
+  | keyword | string  | 是   | 关键词   |
+- **返回说明**:
+  - 各类调试用的数据库查询结果。
+
+**Postman测试方法:**
+1. 新建POST请求,URL填`http://127.0.0.1:5000/debug_search`
+2. Body选择raw,类型JSON:
+   ```json
+   {
+     "keyword": "电影"
+   }
+   ```
+3. Send。
+
+---
+
+如需补充其它接口或参数说明,随时联系!