# PhotoNote v1.0 Technology Stack Deep Analysis Report

> **Project Name**: PhotoNote - AI Smart Calorie Tracking Application
> **Version**: v1.0
> **Generation Date**: 2025-10-05
> **Architecture Pattern**: Frontend-Backend Separation + Microservices Architecture

---

## Table of Contents

1. [Project Overview](#1-project-overview)
2. [Frontend Technology Stack](#2-frontend-technology-stack)
3. [Backend Technology Stack](#3-backend-technology-stack)
4. [Database Technology](#4-database-technology)
5. [AI and Third-Party Services](#5-ai-and-third-party-services)
6. [DevOps and Deployment](#6-devops-and-deployment)
7. [Architecture Design](#7-architecture-design)
8. [Performance Optimization](#8-performance-optimization)
9. [Security Design](#9-security-design)
10. [Technical Highlights and Innovations](#10-technical-highlights-and-innovations)
11. [Learning Path Recommendations](#11-learning-path-recommendations)

---

## 1. Project Overview

### 1.1 Project Positioning
PhotoNote is an AI image recognition-based smart calorie tracking application that helps users manage their daily dietary calorie intake through photo capture or manual input.

### 1.2 Core Features
- 📸 **AI Image Recognition**: Automatically identify food and estimate calories by taking photos
- ✍️ **Manual Recording**: Support manual addition of food calories
- 📊 **Data Statistics**: View calorie intake statistics by date
- 💰 **Package Subscription**: Integrated RLF module providing packages and payment functions
- 👤 **User System**: Integrated RLF authentication and user management

### 1.3 Technology Selection Principles
- **Frontend**: Modern, component-based, performance-first
- **Backend**: Asynchronous high-performance, easy to maintain
- **Deployment**: Containerized, automated, highly available

---

## 2. Frontend Technology Stack

### 2.1 Core Framework

#### 2.1.1 React 18.2.0
- **Selection Reason**: Industry-leading UI framework with rich ecosystem and excellent performance
- **Core Feature Usage**:
  - **Concurrent Features**: Using Suspense to implement component lazy loading
  - **Hooks**: Functional component development for cleaner state management
  - **Virtual DOM**: Efficient UI update mechanism

**Key Code Example (App.tsx:1-126)**:
```tsx
// High-frequency pages loaded immediately, low-frequency pages lazy loaded
import Home from './pages/Home';
const Statistics = lazy(() => import('./pages/Statistics'));

// Suspense wrapper for graceful degradation
<Suspense fallback={<LoadingFallback />}>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/statistics" element={<Statistics />} />
  </Routes>
</Suspense>
```

#### 2.1.2 TypeScript ~5.8.3
- **Type Safety**: Compile-time error detection to reduce runtime bugs
- **Development Experience**: IDE intelligent suggestions, easier code maintenance
- **Configuration**: Strict mode (tsconfig.json) to ensure type completeness

**Technical Details**:
```typescript
// Type definition example (utils/auth.ts)
export const isLoggedIn = (): boolean => {
  const token = localStorage.getItem('rlf_token');
  return !!token;
};
```

### 2.2 UI Framework

#### 2.2.1 Ant Design Mobile 5.41.1
- **Mobile Optimization**: Component library designed specifically for mobile
- **Core Component Usage**:
  - `Toast`: Message notifications
  - `SpinLoading`: Loading animations
  - `Form`: Form processing
  - `List`: List display
  - `NavBar`: Navigation bar

**Advantages**:
- Out-of-the-box mobile UI components
- Strong theme customization capabilities
- Support for on-demand loading to reduce package size

### 2.3 Routing Management

#### 2.3.1 React Router DOM 7.9.3
- **Routing Configuration**: Declarative routing definition
- **Core Features**:
  - Nested routes
  - Route lazy loading
  - Route parameter passing
  - Redirect control

**Routing Architecture (App.tsx:104-121)**:
```tsx
<Routes>
  <Route path="/" element={<Home />} />
  <Route path="/camera" element={<Camera />} />
  <Route path="/daily/:date" element={<Daily />} />
  <Route path="/statistics" element={<Statistics />} />
  <Route path="*" element={<Navigate to="/" replace />} />
</Routes>
```

### 2.4 HTTP Requests

#### 2.4.1 Axios 1.12.2
- **Interceptors**: Unified request/response handling
- **Error Handling**: Global error capture
- **Token Management**: Automatic authentication token inclusion
- **Timeout Control**: Request timeout configuration

**Technical Implementation**:
```typescript
// Request interceptor - automatically add token
axios.interceptors.request.use(config => {
  const token = localStorage.getItem('rlf_token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});
```

### 2.5 Utility Libraries

#### 2.5.1 Day.js 1.11.18
- **Date Processing**: Lightweight date library (only 2KB)
- **Functions**: Date formatting, parsing, calculation
- **Advantages**: Much smaller than Moment.js with better performance

#### 2.5.2 Eruda 3.4.3
- **Mobile Debugging Tool**: Provides Chrome DevTools-like debugging functionality in mobile browsers
- **Functions**:
  - Console log viewing
  - Network request monitoring
  - DOM inspection
  - LocalStorage viewing

### 2.6 Build Tools

#### 2.6.1 Vite 4.5.0
- **Features**:
  - **Fast Cold Start**: ESM-based development server
  - **Hot Module Replacement (HMR)**: Millisecond-level module hot replacement
  - **Production Optimization**: Rollup-based production build
  - **Plugin Ecosystem**: Rich plugin support

**Configuration Example (vite.config.ts)**:
```typescript
export default defineConfig({
  plugins: [react()],
  server: {
    port: 3020,
    host: true,
    allowedHosts: ['test.viying.online']
  }
})
```

#### 2.6.2 @vitejs/plugin-react 4.2.1
- **React Support**: Vite's React plugin
- **Fast Refresh**: Hot update that maintains component state
- **JSX Transformation**: Automatic JSX syntax processing

### 2.7 Code Quality Tools

#### 2.7.1 ESLint 9.36.0
- **Code Standards**: Unified team code style
- **Plugins**:
  - `eslint-plugin-react-hooks`: React Hooks rule checking
  - `eslint-plugin-react-refresh`: Fast Refresh rules
  - `typescript-eslint`: TypeScript-specific rules

#### 2.7.2 Globals 16.4.0
- **Global Variable Definition**: Avoid ESLint false alarms for undefined global variables

### 2.8 Frontend Architecture Features

#### 2.8.1 Component Lazy Loading Strategy
```tsx
// High-frequency pages - loaded immediately
import Home from './pages/Home';
import Camera from './pages/Camera';

// Low-frequency pages - lazy loaded
const Statistics = lazy(() => import('./pages/Statistics'));
const Packages = lazy(() => import('./pages/Packages'));
```

**Advantages**:
- Reduced initial loading time
- On-demand loading, bandwidth saving
- Better user experience

#### 2.8.2 Authentication Flow Design
- **Token Storage**: LocalStorage
- **Login Callback**: Token passed via URL parameters
- **State Synchronization**: Custom event notifications
- **Local Data Synchronization**: Automatic sync of local records to server after login

**Implementation Details (utils/auth.ts:41-73)**:
```typescript
export const handleLoginCallback = () => {
  const params = new URLSearchParams(window.location.search);
  const token = params.get('token');

  if (token && userId) {
    // Save token
    localStorage.setItem('rlf_token', token);

    // Clear URL parameters
    window.history.replaceState({}, document.title, cleanUrl);

    // Trigger login event
    window.dispatchEvent(new Event('userLoggedIn'));
  }
};
```

#### 2.8.3 Local Data Persistence
- **LocalStorage**: Store user tokens and basic information
- **Offline Support**: Data stored locally when not logged in
- **Automatic Sync**: Automatic upload of local data after login

---

## 3. Backend Technology Stack

### 3.1 Core Framework

#### 3.1.1 FastAPI 0.109.0
- **Async-First**: Based on Python 3.11+ asynchronous features
- **Auto Documentation**: Automatic OpenAPI/Swagger generation
- **Type Checking**: Pydantic model validation
- **High Performance**: Performance comparable to Node.js and Go

**Core Advantages**:
- High development efficiency, clean code
- Automatic data validation and serialization
- Built-in API documentation (/docs)
- Asynchronous support for handling high concurrency

**Main Application Structure (app/main.py:1-63)**:
```python
app = FastAPI(
    title="PhotoNote",
    version="1.0.0",
    debug=settings.DEBUG,
    description="AI Smart Calorie Tracking Application API"
)

# CORS middleware
app.add_middleware(CORSMiddleware, ...)

# Route registration
app.include_router(records.router, prefix="/api/records")
```

#### 3.1.2 Uvicorn 0.27.0
- **ASGI Server**: Supports asynchronous Python applications
- **Standard Configuration**: uvicorn[standard] includes additional optimizations
- **Performance**: High-performance HTTP server

### 3.2 Database Technology

#### 3.2.1 SQLAlchemy 2.0.25
- **ORM Framework**: Python's most popular ORM
- **Core Features**:
  - Declarative model definition
  - Session management
  - Query builder
  - Relationship mapping

**Model Example (app/models/calorie_record.py:22-51)**:
```python
class CalorieRecord(Base):
    __tablename__ = "calorie_records"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(String(50), nullable=False, index=True)
    food_name = Column(String(200), nullable=False)
    calories = Column(Float, nullable=False)
    meal_type = Column(Enum(MealType), nullable=False)
    source = Column(Enum(RecordSource), nullable=False)
    record_date = Column(DateTime(timezone=True), index=True)
```

#### 3.2.2 Alembic 1.13.1
- **Database Migration**: SQLAlchemy's migration tool
- **Version Control**: Database schema version management
- **Automation**: Automatic migration script generation

#### 3.2.3 PostgreSQL (psycopg2-binary 2.9.9)
- **Relational Database**: Enterprise-level open-source database
- **Features**:
  - ACID transaction support
  - Complex query optimization
  - JSON support
  - Full-text search
  - Timezone support

**Connection Configuration**:
```python
DATABASE_URL = "postgresql://owner:owner123@host.docker.internal:5432/photonote"
```

### 3.3 Data Validation

#### 3.3.1 Pydantic 2.5.3
- **Data Models**: Type-hint based data validation
- **Automatic Validation**: Request/response automatic validation
- **Serialization**: Automatic data serialization/deserialization

#### 3.3.2 Pydantic Settings 2.1.0
- **Configuration Management**: Load configuration from environment variables
- **Type Safety**: Configuration item type checking
- **.env Support**: Automatic loading of .env files

**Configuration Example (app/core/config.py:5-58)**:
```python
class Settings(BaseSettings):
    APP_NAME: str = "PhotoNote"
    APP_VERSION: str = "1.0.0"
    DATABASE_URL: str
    ZHIPU_API_KEY: str

    class Config:
        env_file = ".env"
        case_sensitive = True
```

### 3.4 File Processing

#### 3.4.1 Python-Multipart 0.0.6
- **File Upload**: Handle multipart/form-data
- **Large File Support**: Stream processing of large files

#### 3.4.2 Pillow 10.2.0
- **Image Processing**: Python image library
- **Functions**:
  - Image format conversion
  - Image compression
  - Image cropping/scaling

### 3.5 Security Authentication

#### 3.5.1 Python-JOSE 3.3.0
- **JWT Processing**: JSON Web Token generation and validation
- **Encryption Support**: cryptography backend encryption

#### 3.5.2 Passlib 1.7.4
- **Password Hashing**: bcrypt algorithm password encryption
- **Security**: Industry-standard password storage

### 3.6 HTTP Client

#### 3.6.1 HTTPX 0.26.0
- **Asynchronous HTTP**: HTTP client supporting async/await
- **Purpose**: Call RLF authentication service API
- **Features**:
  - Connection pooling
  - Timeout control
  - Automatic retry

### 3.7 Testing Framework

#### 3.7.1 Pytest 7.4.4
- **Unit Testing**: Python standard testing framework
- **Features**:
  - Concise assertion syntax
  - Fixture mechanism
  - Rich plugin ecosystem

#### 3.7.2 Pytest-Asyncio 0.23.3
- **Asynchronous Testing**: Test asynchronous code
- **Integration**: Seamless integration with FastAPI testing

### 3.8 API Route Design

**RESTful API Structure**:
```python
# Calorie Record API (app/api/records.py)
POST   /api/records/upload-image    # Upload image for AI recognition
POST   /api/records/                # Create record
GET    /api/records/                # Get record list
GET    /api/records/daily/{date}    # Get daily statistics
GET    /api/records/{id}            # Get record details
PUT    /api/records/{id}            # Update record
DELETE /api/records/{id}            # Delete record
```

**Dependency Injection Pattern**:
```python
async def create_record(
    record: CalorieRecordCreate,
    current_user: dict = Depends(get_current_user_from_rlf),
    db: Session = Depends(get_db)
):
    # Automatically inject database connection and current user
    db_record = CalorieRecord(user_id=current_user["user_id"], ...)
```

---

## 4. Database Technology

### 4.1 Database Selection: PostgreSQL 15+

#### 4.1.1 Selection Reason
- **Mature and Stable**: 30+ years history, production environment verified
- **Powerful Features**: Supports complex queries, JSON, full-text search
- **Excellent Performance**: Powerful query optimizer
- **Open Source and Free**: MIT-like license

#### 4.1.2 Database Schema Design

**Core Table: calorie_records**
```sql
CREATE TABLE calorie_records (
    id SERIAL PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    food_name VARCHAR(200) NOT NULL,
    calories FLOAT NOT NULL,
    portion FLOAT DEFAULT 1.0,
    meal_type VARCHAR(20) NOT NULL,  -- breakfast/lunch/dinner/snack
    source VARCHAR(20) NOT NULL,      -- ai_recognition/manual
    image_url VARCHAR(500),
    description TEXT,
    ai_confidence FLOAT,
    record_date TIMESTAMP WITH TIME ZONE NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE,
    INDEX idx_user_id (user_id),
    INDEX idx_record_date (record_date)
);
```

**Index Strategy**:
- `user_id`: Fast query of user records
- `record_date`: Date query optimization

### 4.2 ORM Layer Design

#### 4.2.1 Model Definition
```python
class CalorieRecord(Base):
    # Enum types
    class MealType(str, enum.Enum):
        BREAKFAST = "breakfast"
        LUNCH = "lunch"
        DINNER = "dinner"
        SNACK = "snack"

    class RecordSource(str, enum.Enum):
        AI_RECOGNITION = "ai_recognition"
        MANUAL = "manual"
```

#### 4.2.2 Timezone Handling
```python
# All time fields use timezone-aware datetime
record_date = Column(DateTime(timezone=True), nullable=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
```

### 4.3 Database Connection Management

#### 4.3.1 Connection Pool Configuration
```python
# app/core/database.py
engine = create_engine(
    settings.DATABASE_URL,
    pool_size=5,        # Connection pool size
    max_overflow=10,    # Maximum overflow connections
    pool_timeout=30,    # Connection timeout
    pool_recycle=3600   # Connection recycling time
)
```

#### 4.3.2 Session Management
```python
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
```

---

## 5. AI and Third-Party Services

### 5.1 Zhipu AI (GLM-4V)

#### 5.1.1 ZAI SDK 0.0.3.3
- **Official SDK**: Zhipu AI Python SDK
- **Model**: GLM-4V (Vision Language Model)
- **Capabilities**: Image understanding, text generation

#### 5.1.2 AI Recognition Service Implementation

**Core Process (app/services/ai_recognition.py:17-121)**:
```python
class AIRecognitionService:
    def __init__(self):
        self.client = ZhipuAiClient(api_key=settings.ZHIPU_API_KEY)
        self.model = "glm-4v"

    async def recognize_food(self, image_path):
        # 1. Read image and convert to base64
        with open(image_path, "rb") as f:
            image_data = base64.b64encode(f.read()).decode("utf-8")

        # 2. Call Zhipu AI
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[{
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": image_input},
                    {"type": "text", "text": prompt}
                ]
            }],
            temperature=0.5,
            timeout=90
        )

        # 3. Parse JSON result
        result_text = response.choices[0].message.content
        json_match = re.search(r'\{[^}]+\}', result_text)
        result_json = json.loads(json_match.group())

        return AIRecognitionResponse(
            food_name=result_json.get("food_name"),
            calories=float(result_json.get("calories")),
            confidence=float(result_json.get("confidence")),
            description=result_json.get("description")
        )
```

#### 5.1.3 Prompt Engineering

**Carefully Designed Prompt**:
```python
prompt = """Please identify the food in the image and return in the following JSON format:
{
    "food_name": "Food name (Chinese)",
    "calories": Estimated calorie value (unit: kcal, number),
    "confidence": Recognition confidence (decimal between 0-1),
    "description": "Brief description, including food type, approximate portion, etc."
}

Notes:
1. calories must be a number, do not include units
2. If there are multiple foods in the image, please select the main food
3. Calorie estimation should be as accurate as possible, based on common portions
4. Only return JSON, no other text"""
```

**Technical Highlights**:
- Clear JSON format requirements
- Data type constraints
- Business logic guidance
- Improve parseability of returned results

#### 5.1.4 Error Handling
```python
# Regular expression to extract JSON, tolerate extra text from AI
json_match = re.search(r'\{[^}]+\}', result_text, re.DOTALL)

# Calorie value extraction, handle returns like "about 500kcal"
if isinstance(calories_value, str):
    number_match = re.search(r'\d+\.?\d*', calories_value)
    calories_value = float(number_match.group())
```

### 5.2 RLF Authentication Service Integration

#### 5.2.1 Service Architecture
- **RLF Module**: Independent user, package, order, payment service
- **Ports**: 8010 (backend API), 3010 (frontend login page)
- **Communication Method**: HTTP RESTful API

#### 5.2.2 Authentication Flow
```
1. User clicks login → Redirect to RLF login page (3010)
2. User enters account password
3. RLF verification successful → Callback to PhotoNote
4. PhotoNote saves token and user information
5. Subsequent requests carry token to access API
```

#### 5.2.3 Token Verification (app/core/rlf_client.py)
```python
async def get_current_user_from_rlf(
    authorization: str = Header(...),
    db: Session = Depends(get_db)
):
    # Extract token from Header
    token = authorization.replace("Bearer ", "")

    # Call RLF to verify token
    response = await client.get(
        f"{settings.RLF_AUTH_URL}/api/v1/user/profile",
        headers={"Authorization": f"Bearer {token}"}
    )

    if response.status_code != 200:
        raise HTTPException(401, "Token invalid or expired")

    return response.json()
```

#### 5.2.4 CORS Configuration
```python
# Allow multiple frontend domains
CORS_ORIGINS = [
    "http://localhost:3020",
    "https://test.viying.online",
    "https://test.viying.work",
]
```

---

## 6. DevOps and Deployment

### 6.1 Containerization Technology

#### 6.1.1 Docker
**Backend Dockerfile (backend/Dockerfile:1-29)**:
```dockerfile
FROM python:3.11-slim

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    postgresql-client \
    curl

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY . .

# Create upload directory
RUN mkdir -p /app/uploads

EXPOSE 8020

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8020"]
```

**Frontend Dockerfile (frontend/Dockerfile:1-47)**:
```dockerfile
# Multi-stage build
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .

# Build arguments - support environment variable injection
ARG VITE_API_BASE_URL=https://test.viying.online
ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}
RUN npm run build

# Production image
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 3020
CMD ["nginx", "-g", "daemon off;"]
```

**Technical Highlights**:
- **Multi-stage Build**: Reduce final image size
- **Build Arguments**: Support different environment configurations
- **Alpine Image**: Small size, high security

#### 6.1.2 Docker Compose
**Orchestration Configuration (docker-compose.yml:1-43)**:
```yaml
version: '3.8'

services:
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    container_name: photonote_backend
    environment:
      DATABASE_URL: postgresql://owner:owner123@host.docker.internal:5432/photonote
      RLF_AUTH_URL: http://host.docker.internal:8010
      ZHIPU_API_KEY: ${ZHIPU_API_KEY}
      DEBUG: "False"
    ports:
      - "8020:8020"
    volumes:
      - ./backend/uploads:/app/uploads
    extra_hosts:
      - "host.docker.internal:host-gateway"
    restart: unless-stopped

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
      args:
        VITE_API_BASE_URL: https://test.viying.online
        VITE_RLF_BASE_URL: https://test.viying.work
        VITE_RLF_LOGIN_URL: https://test.viying.work
    container_name: photonote_frontend
    ports:
      - "3020:3020"
    restart: unless-stopped
```

**Architecture Features**:
- **Service Isolation**: Frontend and backend independent containers
- **Data Persistence**: File upload directory mounting
- **Network Interoperability**: host.docker.internal access to host services
- **Automatic Restart**: Container automatic recovery on exception

### 6.2 Reverse Proxy

#### 6.2.1 Nginx Configuration
**Dual Domain Architecture**:
- `test.viying.online`: PhotoNote frontend + API
- `test.viying.work`: RLF service

**Core Configuration**:
```nginx
server {
    listen 443 ssl http2;
    server_name test.viying.online;

    # SSL certificate
    ssl_certificate /etc/nginx/ssl/test.viying.online.pem;
    ssl_certificate_key /etc/nginx/ssl/test.viying.online.key;

    # Backend API proxy
    location /api {
        proxy_pass http://10.8.0.5:8020;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_http_version 1.1;
    }

    # Frontend proxy
    location / {
        proxy_pass http://10.8.0.5:3020;
    }
}
```

**Technical Points**:
- **HTTP/2**: Improve transmission efficiency
- **SSL/TLS**: HTTPS encrypted transmission
- **Header Forwarding**: Preserve original IP and Host
- **Timeout Configuration**: 60s timeout, adapt to AI recognition scenarios

### 6.3 Deployment Architecture

#### 6.3.1 Server Architecture
```
┌─────────────────────────────────────────┐
│          Nginx (Reverse Proxy)          │
│     test.viying.online:443 (HTTPS)      │
└───────────┬─────────────────────────────┘
            │
    ┌───────┴──────┬──────────────┐
    │              │              │
┌───▼───┐    ┌────▼────┐    ┌───▼────┐
│ React │    │ FastAPI │    │  RLF   │
│ :3020 │    │  :8020  │    │ :8010  │
└───────┘    └─────────┘    └────────┘
                  │
            ┌─────▼─────┐
            │PostgreSQL │
            │   :5432   │
            └───────────┘
```

#### 6.3.2 Network Topology
- **External Network**: HTTPS through Nginx
- **Internal Network**: Container communication through Docker network
- **Host Access**: host.docker.internal

### 6.4 Environment Management

#### 6.4.1 Environment Variables
```bash
# .env file
ZHIPU_API_KEY=your_api_key
DATABASE_URL=postgresql://user:pass@host:5432/db
RLF_AUTH_URL=http://localhost:8010
DEBUG=False
```

#### 6.4.2 Multi-environment Configuration
- **Local Development**: docker-compose.local.yml
- **Test Environment**: docker-compose.test.yml
- **Production Environment**: docker-compose.yml

### 6.5 Monitoring and Logging

#### 6.5.1 Health Check
```python
@app.get("/health")
async def health_check():
    return {"status": "healthy"}
```

#### 6.5.2 Log Management
```bash
# View container logs
docker logs photonote_backend --tail 100
docker logs photonote_frontend --tail 100
```

---

## 7. Architecture Design

### 7.1 Overall Architecture

#### 7.1.1 Layered Architecture
```
┌─────────────────────────────────────────┐
│          Presentation Layer             │
│         (React + Ant Design)            │
└───────────────┬─────────────────────────┘
                │ HTTP/HTTPS
┌───────────────▼─────────────────────────┐
│          API Gateway Layer              │
│         (Nginx Reverse Proxy)           │
└───────────┬─────────────────┬───────────┘
            │                 │
┌───────────▼──────┐   ┌─────▼──────────┐
│  PhotoNote API   │   │   RLF Service  │
│    (FastAPI)     │   │   (User/Payment)│
└─────┬─────┬──────┘   └────────────────┘
      │     │
      │     └──────────┐
┌─────▼──────┐   ┌─────▼──────────┐
│ PostgreSQL │   │  Zhipu AI GLM-4V│
│  Database  │   │  (Image Recognition)│
└────────────┘   └────────────────┘
```

#### 7.1.2 Microservices Design
- **PhotoNote**: Core business (calorie tracking, AI recognition)
- **RLF**: Basic services (user, packages, orders, payments)
- **Decoupling**: Services communicate via API
- **Independent Deployment**: Each service can be scaled independently

### 7.2 Data Flow Design

#### 7.2.1 AI Recognition Process
```
User takes photo → Upload image → Save locally → Base64 encoding
→ Call Zhipu AI → Parse results → Return to frontend
→ User confirmation → Create record → Save to database
```

#### 7.2.2 Authentication Process
```
User access → Check token → Token expired
→ Redirect to RLF login → User login → Callback with token
→ Save token → Access API → Verify token
→ Get user info → Return data
```

### 7.3 Caching Strategy

#### 7.3.1 Frontend Caching
- **LocalStorage**: Token, user info, local records
- **Memory Cache**: Component state, route cache
- **Browser Cache**: Static resources (CSS/JS/images)

#### 7.3.2 Backend Caching
- **Database Connection Pool**: Reuse database connections
- **Static Files**: Nginx cache for image resources

---

## 8. Performance Optimization

### 8.1 Frontend Optimization

#### 8.1.1 Code Splitting
```tsx
// Route-level lazy loading
const Statistics = lazy(() => import('./pages/Statistics'));
const Packages = lazy(() => import('./pages/Packages'));

// Advantage: Reduce initial loading time by 50%+
```

#### 8.1.2 Resource Optimization
- **Tree Shaking**: Vite automatically removes unused code
- **Code Compression**: Terser compresses JS
- **CSS Optimization**: PostCSS optimizes styles
- **Image Compression**: Pillow compresses uploaded images on backend

#### 8.1.3 Loading Experience
```tsx
// Elegant loading placeholder
const LoadingFallback = () => (
  <div style={{ animation: 'fadeIn 2s ease-in' }}>
    <SpinLoading />
    <img src={pegeeAvatar} alt="Loading" />
  </div>
);
```

### 8.2 Backend Optimization

#### 8.2.1 Asynchronous Processing
```python
# All APIs use async/await
async def create_record(record: CalorieRecordCreate):
    # Asynchronous database operations
    db.add(db_record)
    await db.commit()
```

#### 8.2.2 Database Optimization
```python
# Index optimization
user_id = Column(String(50), index=True)
record_date = Column(DateTime, index=True)

# Query optimization
query.order_by(CalorieRecord.record_date.desc()).all()
```

#### 8.2.3 Concurrency Handling
- **Uvicorn**: Multi-worker processes
- **Connection Pool**: Database connection reuse
- **Asynchronous IO**: Non-blocking network requests

### 8.3 Network Optimization

#### 8.3.1 HTTP/2
- **Multiplexing**: Multiple requests on single connection
- **Header Compression**: HPACK compression
- **Server Push**: Preload resources

#### 8.3.2 Gzip Compression
```nginx
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
```

#### 8.3.3 CDN Strategy
- **Static Resources**: Can be deployed to CDN
- **Images**: Support OSS storage

---

## 9. Security Design

### 9.1 Authentication and Authorization

#### 9.1.1 Token Mechanism
- **JWT**: JSON Web Token standard
- **Bearer Authentication**: HTTP Authorization Header
- **Expiration Mechanism**: 30-minute expiration time

#### 9.1.2 Password Security
```python
# Bcrypt hash - industry standard
from passlib.context import CryptContext
pwd_context = CryptContext(schemes=["bcrypt"])
hashed = pwd_context.hash(password)
```

### 9.2 API Security

#### 9.2.1 CORS Configuration
```python
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "https://test.viying.online",  # Whitelist
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
```

#### 9.2.2 Input Validation
```python
# Pydantic automatic validation
class CalorieRecordCreate(BaseModel):
    food_name: str = Field(..., min_length=1, max_length=200)
    calories: float = Field(..., gt=0)
    portion: float = Field(default=1.0, gt=0)
```

#### 9.2.3 File Upload Security
```python
# File type validation
if not file.content_type.startswith("image/"):
    raise HTTPException(400, "Only image files supported")

# File size limit
if len(image_data) > settings.MAX_UPLOAD_SIZE:
    raise HTTPException(413, "File too large")

# Safe filename
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_filename = f"{timestamp}_{filename}"
```

### 9.3 Transmission Security

#### 9.3.1 HTTPS/TLS
```nginx
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:...;
ssl_prefer_server_ciphers off;
```

#### 9.3.2 Security Headers
```nginx
add_header Strict-Transport-Security "max-age=31536000" always;
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
add_header X-XSS-Protection "1; mode=block" always;
```

### 9.4 Data Security

#### 9.4.1 SQL Injection Protection
```python
# ORM automatic protection
db.query(CalorieRecord).filter(
    CalorieRecord.user_id == user_id  # Parameterized query
)
```

#### 9.4.2 Sensitive Information Protection
```python
# Environment variable storage
ZHIPU_API_KEY: str  # Not hardcoded in code
SECRET_KEY: str
```

---

## 10. Technical Highlights and Innovations

### 10.1 AI Integration Innovation

#### 10.1.1 Intelligent Prompt Design
- **Structured Output**: Enforce JSON format return
- **Error Handling**: Regular expression extraction, compatible with various AI return formats
- **Business Optimization**: Calorie value number extraction, remove "about" and other interfering text

#### 10.1.2 User Experience Optimization
- **90-second Timeout**: Give AI sufficient processing time
- **Confidence Feedback**: Display recognition confidence
- **Editable Results**: Users can correct AI recognition errors

### 10.2 Architecture Design Highlights

#### 10.2.1 Microservices Decoupling
- **PhotoNote**: Focus on core business
- **RLF**: Reuse basic services
- **Benefits**: Code reuse, independent scaling, reduced coupling

#### 10.2.2 Offline-First Design
```typescript
// Can record without login, automatically sync after login
const localRecords = getLocalRecords();
if (isLoggedIn()) {
  await syncLocalDataToServer();
}
```

#### 10.2.3 Dual Domain Solution
- **test.viying.online**: PhotoNote
- **test.viying.work**: RLF
- **Advantages**: Service isolation, independent scaling, clear responsibilities

### 10.3 Performance Optimization Innovation

#### 10.3.1 Progressive Loading
```tsx
// High-frequency pages loaded immediately, low-frequency pages lazy loaded
import Home from './pages/Home';  // Immediate
const Settings = lazy(() => import('./pages/Settings'));  // Lazy loading
```

#### 10.3.2 Multi-stage Docker Build
```dockerfile
# Build stage - large image
FROM node:18-alpine AS builder
RUN npm run build

# Production stage - small image
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
# Final image only 20MB+
```

### 10.4 Development Experience Optimization

#### 10.4.1 Automatic API Documentation
- **FastAPI**: Visit /docs to view interactive API documentation
- **Zero Cost**: No additional documentation writing required
- **Real-time Synchronization**: Code as documentation

#### 10.4.2 Type Safety
- **Frontend TypeScript**: Compile-time type checking
- **Backend Pydantic**: Runtime data validation
- **Benefits**: Reduce 90%+ type-related bugs

---

## 11. Learning Path Recommendations

### 11.1 Frontend Technology Learning

#### 11.1.1 Basics (1-2 months)
1. **JavaScript ES6+**: Arrow functions, destructuring, Promise, async/await
2. **React Basics**: Components, Hooks, state management
3. **TypeScript**: Type system, interfaces, generics
4. **CSS**: Flexbox, Grid, responsive design

**Recommended Resources**:
- React official documentation: https://react.dev
- TypeScript handbook: https://www.typescriptlang.org/docs/

#### 11.1.2 Advanced (2-3 months)
1. **React Router**: Route management, lazy loading
2. **State Management**: Context API, Redux (optional)
3. **HTTP Requests**: Axios, error handling
4. **Build Tools**: Vite, Webpack principles

**Practice Projects**:
- Clone PhotoNote to build a similar application
- Integrate third-party APIs (weather, news)

#### 11.1.3 Expert (3-6 months)
1. **Performance Optimization**: Lazy loading, code splitting, caching strategies
2. **PWA**: Service Worker, offline support
3. **Testing**: Jest, React Testing Library
4. **CI/CD**: GitHub Actions automated deployment

### 11.2 Backend Technology Learning

#### 11.2.1 Basics (1-2 months)
1. **Python Basics**: Syntax, object-oriented, asynchronous programming
2. **FastAPI**: Routes, request handling, response
3. **Database**: SQL basics, PostgreSQL
4. **ORM**: SQLAlchemy model definition, queries

**Recommended Resources**:
- FastAPI official tutorial: https://fastapi.tiangolo.com
- SQLAlchemy documentation: https://docs.sqlalchemy.org

#### 11.2.2 Advanced (2-3 months)
1. **RESTful API Design**: Resource design, HTTP methods
2. **Authentication and Authorization**: JWT, OAuth2
3. **Data Validation**: Pydantic, custom validators
4. **Error Handling**: Exception catching, custom errors

**Practice Projects**:
- Build a blog API
- Implement user registration and login system

#### 11.2.3 Expert (3-6 months)
1. **Asynchronous Programming**: asyncio, concurrent processing
2. **Database Optimization**: Indexing, query optimization, transactions
3. **Caching**: Redis integration
4. **Testing**: Pytest, asynchronous testing

### 11.3 DevOps Learning

#### 11.3.1 Basics (1 month)
1. **Docker**: Images, containers, Dockerfile
2. **Docker Compose**: Multi-container orchestration
3. **Linux Basics**: Command line, file system, permissions

#### 11.3.2 Advanced (2 months)
1. **Nginx**: Reverse proxy, load balancing, SSL configuration
2. **CI/CD**: GitHub Actions, automated deployment
3. **Monitoring**: Log management, performance monitoring

### 11.4 AI Technology Learning

#### 11.4.1 Basics (1 month)
1. **API Calls**: HTTP requests, authentication
2. **Prompt Engineering**: How to design effective prompts
3. **Result Parsing**: JSON processing, error handling

#### 11.4.2 Advanced (2-3 months)
1. **Multimodal Models**: Image + text understanding
2. **Token Optimization**: Reduce API call costs
3. **Streaming Output**: Improve user experience

### 11.5 Comprehensive Project Practice

#### 11.5.1 Project Suggestions
1. **Clone PhotoNote**: Build a similar project from scratch
2. **Feature Extensions**:
   - Add nutrition analysis
   - Implement exercise calorie consumption tracking
   - Add community sharing features
3. **Deployment**: Purchase server, configure domain, HTTPS

#### 11.5.2 Learning Methods
1. **Read Source Code**: Understand PhotoNote implementation details
2. **Modify Code**: Change features, observe effects
3. **Write Documentation**: Record learning process, deepen understanding
4. **Share Knowledge**: Teaching others is the best way to learn

---

## 12. Summary

### 12.1 Technology Stack Overview

| Technology Category | Core Technology | Version | Purpose |
|---------------------|----------------|---------|---------|
| **Frontend Framework** | React | 18.2.0 | UI Framework |
| | TypeScript | 5.8.3 | Type Safety |
| | Vite | 4.5.0 | Build Tool |
| **UI Components** | Ant Design Mobile | 5.41.1 | Mobile UI |
| **Routing** | React Router DOM | 7.9.3 | Route Management |
| **HTTP** | Axios | 1.12.2 | Network Requests |
| **Backend Framework** | FastAPI | 0.109.0 | API Framework |
| | Uvicorn | 0.27.0 | ASGI Server |
| **ORM** | SQLAlchemy | 2.0.25 | Database ORM |
| **Database** | PostgreSQL | 15+ | Relational Database |
| **Data Validation** | Pydantic | 2.5.3 | Data Validation |
| **AI Service** | Zhipu AI GLM-4V | - | Image Recognition |
| | ZAI SDK | 0.0.3.3 | AI Interface |
| **Containerization** | Docker | - | Container Technology |
| | Docker Compose | - | Orchestration Tool |
| **Reverse Proxy** | Nginx | - | Web Server |
| **Testing** | Pytest | 7.4.4 | Backend Testing |
| **Utility Libraries** | Day.js | 1.11.18 | Date Processing |
| | Pillow | 10.2.0 | Image Processing |

### 12.2 Technical Highlights

1. **Full-stack TypeScript**: Frontend and backend type safety
2. **Deep AI Integration**: Intelligent Prompt + Error Handling
3. **Microservices Architecture**: PhotoNote + RLF decoupled design
4. **Performance Priority**: Lazy loading, asynchronous, caching strategies
5. **Complete DevOps**: Docker + Nginx + HTTPS
6. **Offline Support**: LocalStorage + Automatic Sync

### 12.3 Project Value

#### 12.3.1 Technical Value
- Master modern web full-stack development
- Learn AI application integration
- Understand microservices architecture
- Practice DevOps processes

#### 12.3.2 Business Value
- Solve real health management needs
- Commercial potential (package subscription)
- Strong scalability (nutrition analysis, exercise, etc.)

#### 12.3.3 Learning Value
- Complete project practice
- Covers frontend, backend, AI, deployment
- Can be used as interview project showcase
- Large space for secondary development

---

## Appendix

### A. Technical Documentation Links
- FastAPI: https://fastapi.tiangolo.com
- React: https://react.dev
- TypeScript: https://www.typescriptlang.org
- Ant Design Mobile: https://mobile.ant.design
- SQLAlchemy: https://docs.sqlalchemy.org
- Docker: https://docs.docker.com
- Zhipu AI: https://open.bigmodel.cn

### B. Project Structure
```
photo-note/
├── backend/
│   ├── app/
│   │   ├── api/          # API routes
│   │   │   └── records.py
│   │   ├── core/         # Core configuration
│   │   │   ├── config.py
│   │   │   ├── database.py
│   │   │   └── rlf_client.py
│   │   ├── models/       # Data models
│   │   │   └── calorie_record.py
│   │   ├── schemas/      # Pydantic models
│   │   │   └── calorie_record.py
│   │   ├── services/     # Business logic
│   │   │   └── ai_recognition.py
│   │   └── main.py       # Main application
│   ├── Dockerfile
│   └── requirements.txt
├── frontend/
│   ├── src/
│   │   ├── pages/        # Page components
│   │   ├── utils/        # Utility functions
│   │   ├── App.tsx       # Main application
│   │   └── main.tsx      # Entry file
│   ├── Dockerfile
│   ├── nginx.conf
│   ├── package.json
│   └── vite.config.ts
├── docker-compose.yml
└── docs/
    └── report/
        └── technology-stack-analysis.md
```

### C. Port Planning
- 3020: PhotoNote frontend
- 8020: PhotoNote backend API
- 3010: RLF frontend
- 8010: RLF backend API
- 5432: PostgreSQL database

---

**End of Report**

This report provides a detailed analysis of all technical aspects of the PhotoNote v1.0 project, covering frontend, backend, database, AI, DevOps, and more. It is hoped that this will help team members deeply understand the project technology stack and provide reference for future learning and secondary development.

If you have any questions or need additional content, please feel free to contact us.