Commit 50eeb101 authored by insun park's avatar insun park
Browse files

refactor: 프로젝트 구조 개편 및 문서 업데이트

parent 00587836
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual Environment
venv/
env/
ENV/
env.bak/
venv.bak/
# IDE
.vscode/
.idea/
*.swp
*.swo
*~
# Logs
logs/
*.log
# Database
*.db
*.sqlite3
# Cache
.pytest_cache/
.cache/
# Chrome/Selenium
chromedriver
*.deb
# OS
.DS_Store
Thumbs.db
# Docker
.dockerignore
# Temporary files
tmp/
temp/
*.tmp
# Jupyter Notebooks
.ipynb_checkpoints
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Backup files
backup_*/
*.backup
\ No newline at end of file
FROM ubuntu:22.04
# 관련 패키지 설치
RUN apt-get update && apt-get install -y mecab libmecab-dev mecab-ipadic-utf8 vim gcc g++ python3.10 python3-pip locales
RUN localedef -f UTF-8 -i ko_KR ko_KR.UTF-8
ENV LC_ALL ko_KR.UTF-8
ENV PYTHONIOENCODING=utf-8
# jdk 설치
RUN apt-get install -y openjdk-8-jdk
# eunjeon 패키지 따로 설치
RUN pip install eunjeon
# jdk 설정
RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64" >> /etc/profile && \
echo "export CLASSPATH=.:$JAVA_HOME/jre/lib/ext:$JAVA_HOME/lib/tools.jar:$CATALINA_HOME/lib/jsp-api.jar:$CATALINA_HOME/lib/servlet-api.jar" >> /etc/profile && \
echo "export LANG=ko_KR.UTF-8" >> /etc/profile
WORKDIR /fastapi
# 이미지 내부에 필요한 파일을 복사
COPY ./fastapi .
RUN apt-get update && \
apt-get install -y \
wget \
curl \
gnupg \
unzip \
jq \
libu2f-udev \
libappindicator3-1 \
libasound2 \
libatk-bridge2.0-0 \
libatk1.0-0 \
libcups2 \
libdbus-1-3 \
libgtk-3-0 \
libnspr4 \
libnss3 \
libx11-xcb1 \
libxcomposite1 \
libxcursor1 \
libxdamage1 \
libxfixes3 \
libxi6 \
libxrandr2 \
libxss1 \
libxtst6 \
xdg-utils \
fonts-liberation \
libgbm1 \
libvulkan1 \
&& apt-get clean
# Chrome과 Chromedriver 최신 안정 버전 설치
RUN LATEST_STABLE_JSON=$(wget -qO- https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions-with-downloads.json) && \
CHROME_URL=$(echo $LATEST_STABLE_JSON | jq -r '.channels.Stable.downloads.chrome[] | select(.platform=="linux64") | .url') && \
DRIVER_URL=$(echo $LATEST_STABLE_JSON | jq -r '.channels.Stable.downloads.chromedriver[] | select(.platform=="linux64") | .url') && \
wget -O chrome-linux64.zip $CHROME_URL && \
wget -O chromedriver-linux64.zip $DRIVER_URL && \
unzip chrome-linux64.zip && \
unzip chromedriver-linux64.zip && \
apt-get update && \
while read pkg; do apt-get satisfy -y --no-install-recommends "${pkg}"; done < chrome-linux64/deb.deps && \
mv chrome-linux64/chrome /usr/local/bin/google-chrome && \
mv chromedriver-linux64/chromedriver /usr/local/bin/chromedriver && \
chmod +x /usr/local/bin/google-chrome && \
chmod +x /usr/local/bin/chromedriver && \
rm chrome-linux64.zip chromedriver-linux64.zip && \
rm -rf chrome-linux64 chromedriver-linux64
# 크롬 실행 확인
RUN google-chrome --version
RUN chromedriver --version
RUN mkdir -p /dev/shm && chmod 1777 /dev/shm
RUN pip install --no-cache-dir -r requirements.txt
#CMD
CMD ["uvicorn", "app.server:app", "--host", "0.0.0.0", "--port", "8000", "--log-level", "trace"]
# RECLAR (SABG) 크롤링 & 감성분석 시스템 🚀
## 📋 프로젝트 개요
RECLAR은 제품별 마케팅 전략 데이터 확보 및 상품개선을 위한 AI 감성분석 시스템입니다. 스마트스토어와 쿠팡에서 상품 정보와 리뷰를 수집하고, 이를 분석하여 마케팅 인사이트를 제공합니다.
### 🎯 주요 기능
- **🔄 동적 마켓 크롤링**: 확장 가능한 아키텍처로 새로운 마켓을 쉽게 추가
- **📊 실시간 성능 모니터링**: 크롤링 성능을 실시간으로 추적 및 분석
- **🤖 AI 감성 분석**: 수집된 리뷰 데이터의 감성 분석
- **📝 구조화된 로깅**: 마켓별 분리된 로그 관리 및 메트릭 수집
- **🔗 연관 분석**: 상품 및 리뷰 데이터의 연관성 분석
---
## 🏗 프로젝트 구조 (정리됨)
```
docker_fastapi/
├── 📁 fastapi/ # 메인 FastAPI 애플리케이션
│ ├── 📁 app/ # 애플리케이션 진입점
│ ├── 📁 api/ # API 라우터
│ │ ├── 📁 analysis/ # 데이터 분석 API
│ │ ├── 📁 auth/ # 인증 API
│ │ ├── 📁 crawling/ # 크롤링 API
│ │ └── 📁 monitoring/ # 모니터링 API
│ ├── 📁 core/ # 핵심 비즈니스 로직
│ │ ├── 📄 crawler_base.py # 공통 크롤링 베이스 클래스
│ │ ├── 📄 crawler_factory.py # 크롤러 팩토리 패턴
│ │ ├── 📁 crawlers/ # 마켓별 크롤러
│ │ ├── 📁 exceptions/ # 예외 처리
│ │ ├── 📁 middleware/ # 미들웨어
│ │ └── 📁 utils/ # 유틸리티
│ ├── 📁 config/ # 설정 파일
│ │ └── 📁 parsing_rules/ # 파싱 규칙
│ ├── 📁 databases/ # 데이터베이스 관련
│ ├── 📁 ml/ # 머신러닝 모델
│ │ └── 📁 sentiment/ # 감성 분석
│ ├── 📁 tests/ # 테스트 파일 (정리됨)
│ │ ├── 📁 integration/ # 통합 테스트
│ │ └── 📁 manual/ # 수동 테스트
│ ├── 📁 logs/ # 로그 파일 (새로 생성)
│ │ ├── 📁 smartstore/ # 스마트스토어 로그
│ │ ├── 📁 coupang/ # 쿠팡 로그
│ │ └── 📁 metrics/ # 성능 메트릭
│ └── 📁 docs/ # 문서
├── 📁 assets/ # 바이너리 파일 (새로 생성)
│ └── 📁 chrome/ # Chrome 관련 파일
│ ├── 📄 chromedriver # 이동됨
│ └── 📄 google-chrome...deb # 이동됨
├── 📁 scripts/ # 개발 스크립트 (새로 생성)
│ └── 📄 rebuild.sh # 이동됨
├── 📁 backup_monitoring/ # 백업된 모니터링 폴더
├── 📁 venv/ # 파이썬 가상환경
├── 📄 docker-compose.yml # Docker 설정
├── 📄 Dockerfile # Docker 이미지 설정 (업데이트됨)
└── 📄 README.md # 프로젝트 문서 (업데이트됨)
```
### 🔄 정리된 내용
1. **테스트 파일 정리**:
- 루트에 산재되어 있던 테스트 파일들을 `fastapi/tests/` 하위로 이동
- `integration/` (통합 테스트)와 `manual/` (수동 테스트)로 분류
2. **바이너리 파일 정리**:
- Chrome 설치 파일과 chromedriver를 `assets/chrome/`으로 이동
- Dockerfile에서 경로 업데이트
3. **스크립트 정리**:
- 개발 스크립트들을 `scripts/` 디렉토리로 이동
4. **로그 디렉토리 생성**:
- 마켓별 로그 관리를 위한 구조 생성
5. **중복 폴더 정리**:
- 루트의 `monitoring/` 폴더를 `backup_monitoring/`으로 백업
---
## 🚀 빠른 시작
### 1. 환경 설정
```bash
# 저장소 클론
git clone <repository-url>
cd docker_fastapi
# 가상환경 활성화
source venv/bin/activate
# FastAPI 의존성 설치
cd fastapi
pip install -r requirements.txt
```
### 2. 서버 실행
```bash
# Docker Compose 사용 (권장)
docker-compose up -d
# 또는 직접 실행
cd fastapi
python main.py
# 또는 uvicorn으로 실행
uvicorn app.server:app --host 0.0.0.0 --port 8000 --reload
```
### 3. API 문서 확인
- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
---
## 📚 API 사용 가이드
### 🔄 동적 크롤링 API
#### 지원 마켓 조회
```bash
GET /crawling/markets
```
#### 상품 정보 크롤링
```bash
GET /crawling/{market}/product?url={상품URL}
# 예시
GET /crawling/smartstore/product?url=https://smartstore.naver.com/...
GET /crawling/coupang/product?url=https://www.coupang.com/vp/products/...
```
#### 리뷰 정보 크롤링
```bash
GET /crawling/{market}/reviews?url={상품URL}
```
### 📊 성능 모니터링 API
#### 성능 요약
```bash
GET /monitoring/performance/summary?market=smartstore
```
#### 종합 대시보드
```bash
GET /monitoring/performance/dashboard?market=smartstore
```
#### 시스템 헬스 체크
```bash
GET /monitoring/performance/health
```
---
## 🧪 테스트
### 테스트 실행
```bash
cd fastapi
# 모든 테스트 실행
pytest
# 통합 테스트만 실행
pytest tests/integration/
# 수동 테스트 (개별 실행)
python tests/manual/test_simple_manual.py
# 특정 마커별 테스트 실행
pytest -m unit # 유닛 테스트만
pytest -m integration # 통합 테스트만
pytest -m manual # 수동 테스트만
# 커버리지 포함 실행
pytest --cov=core --cov-report=html
```
### 테스트 구조
```
📁 fastapi/tests/
├── 📁 integration/ # 통합 테스트
│ ├── 📄 test_system.py
│ ├── 📄 test_monitoring_system.py
│ └── 📄 test_updated_crawler.py
├── 📁 manual/ # 수동 테스트
│ ├── 📄 test_simple_manual.py
│ ├── 📄 test_korean_sentiment.py
│ ├── 📄 test_navigate_to_url.py
│ └── 📄 test_coupang_manual.py
├── 📄 test_crawler_base.py # 유닛 테스트
├── 📄 test_rule_loader.py
├── 📄 test_crawler_factory.py
└── 📄 test_integration.py
```
---
## 📊 로깅 및 모니터링
### 로그 파일 구조
```
📁 fastapi/logs/
├── 📁 smartstore/
│ ├── 📄 crawler.log # 일반 로그
│ └── 📄 error.log # 에러 로그
├── 📁 coupang/
│ ├── 📄 crawler.log
│ └── 📄 error.log
└── 📁 metrics/
├── 📄 metrics_2024-01-15.jsonl # 일반 메트릭
└── 📄 performance_2024-01-15.jsonl # 성능 메트릭
```
### 로그 특징
- **마켓별 분리**: 각 마켓의 로그를 독립적으로 관리
- **로그 회전**: 10MB 파일 크기 제한, 5개 백업 파일 유지
- **구조화된 로깅**: JSON 형태로 분석 용이성 향상
- **성능 메트릭**: 자동 수집 및 저장
---
## 🔧 개발 가이드
### 새로운 마켓 크롤러 추가
1. `fastapi/core/crawlers/` 디렉토리에 새 크롤러 파일 생성
2. `BaseCrawler`를 상속받아 구현
3. `fastapi/config/parsing_rules/`에 파싱 규칙 추가
4. 자동으로 크롤러 팩토리에 등록됨
### 스크립트 실행
```bash
# 프로젝트 재빌드
./scripts/rebuild.sh
# 코드베이스 정리 (이미 실행됨)
./organize_structure.sh
```
---
## 🤝 기여하기
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
---
## 📄 라이선스
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
---
## ⚠️ 주의사항
- Chrome과 chromedriver는 호환되는 버전을 사용해야 합니다
- 크롤링 시 해당 사이트의 robots.txt와 이용약관을 준수해야 합니다
- 과도한 요청으로 인한 서버 부하를 방지하기 위해 적절한 딜레이를 설정하세요
version: '3'
services:
server:
build:
context: .
dockerfile: Dockerfile
container_name: fastapi_server
network_mode: bridge
ports:
- "8000:8000"
volumes:
- ./fastapi:/fastapi
tty: true
stdin_open: true
restart: always
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual Environment
venv/
env/
ENV/
# IDE
.idea/
.vscode/
*.swp
*.swo
# Docker
.docker/
# Logs
*.log
# Local development
.env
.env.local
.env.*.local
# System Files
.DS_Store
Thumbs.db
# Project specific
*.deb
chromedriver
*.zip
# Model files
*.h5
*.h5.bak
*.pickle
*.pickle.bak
*.pkl
*.pt
*.onnx
*.bin
\ No newline at end of file
FROM ubuntu:22.04
# 관련 패키지 설치
RUN apt-get update && apt-get install -y mecab libmecab-dev mecab-ipadic-utf8 vim gcc g++ python3.10 python3-pip locales
RUN localedef -f UTF-8 -i ko_KR ko_KR.UTF-8
ENV LC_ALL ko_KR.UTF-8
ENV PYTHONIOENCODING=utf-8
# jdk 설치
RUN apt-get install -y openjdk-8-jdk
# eunjeon 패키지 따로 설치
RUN pip install eunjeon
# jdk 설정
RUN echo "export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64" >> /etc/profile && \
echo "export CLASSPATH=.:$JAVA_HOME/jre/lib/ext:$JAVA_HOME/lib/tools.jar:$CATALINA_HOME/lib/jsp-api.jar:$CATALINA_HOME/lib/servlet-api.jar" >> /etc/profile && \
echo "export LANG=ko_KR.UTF-8" >> /etc/profile
WORKDIR /fastapi_new
# 이미지 내부에 필요한 파일을 복사
COPY ./fastapi_new .
RUN apt-get update && \
apt-get install -y \
wget \
curl \
gnupg \
jq \
unzip \
libu2f-udev \
libappindicator3-1 \
libasound2 \
libatk-bridge2.0-0 \
libatk1.0-0 \
libcups2 \
libdbus-1-3 \
libgtk-3-0 \
libnspr4 \
libnss3 \
libx11-xcb1 \
libxcomposite1 \
libxcursor1 \
libxdamage1 \
libxfixes3 \
libxi6 \
libxrandr2 \
libxss1 \
libxtst6 \
xdg-utils \
fonts-liberation \
libgbm1 \
libvulkan1 \
&& apt-get clean
# 크롬 자동 설치
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google-chrome.list
RUN apt-get update && apt-get install -y google-chrome-stable
# 크롬 실행 확인
RUN google-chrome --version
RUN mkdir -p /dev/shm && chmod 1777 /dev/shm
RUN pip install --no-cache-dir -r requirements.txt
#CMD
CMD ["python3","main.py"]
# AI 감성 분석 및 크롤링 시스템
본 프로젝트는 마케팅 전략 수립 및 상품 개선을 위한 데이터 수집 및 AI 감성 분석 시스템입니다. Docker를 기반으로 패키징되어 있으며, FastAPI를 통해 API를 제공합니다.
## 기술 아키텍처
시스템은 크게 데이터 수집(Crawling), 데이터 분석(Analysis), API 제공(Serving)의 3가지 핵심 기능으로 구성됩니다.
- **`Dockerfile`**: `ubuntu:22.04`를 기반으로 하며, 애플리케이션 실행에 필요한 복잡한 환경을 구성합니다.
- **핵심 의존성**: Python 3.10, Java 8 JDK, Mecab (한국어 형태소 분석기), Google Chrome.
- Java JDK는 한국어 형태소 분석기 라이브러리인 `Eunjeon`의 의존성 해결을 위해 설치됩니다.
- Google Chrome과 관련 라이브러리(`lib*`) 및 `webdriver``Selenium`을 사용한 웹 크롤링 기능을 위해 설치됩니다.
- **`docker-compose.yml`**:
- `fastapi_new_server`라는 이름의 단일 서비스를 실행합니다.
- `shm_size: 2g`: Selenium으로 Chrome을 실행할 때 발생할 수 있는 크래시를 방지하기 위해 컨테이너의 공유 메모리 크기를 2GB로 설정합니다.
- 호스트의 8001 포트를 컨테이너의 8001 포트와 매핑합니다.
### 워크플로우
1. **데이터 수집 (Crawling)**:
- `api/crawling/` 디렉토리의 `smartstore.py`, `coupang.py` 모듈이 크롤링 로직을 담당합니다.
- `Selenium`, `BeautifulSoup`, `undetected-chromedriver`를 사용하여 스마트스토어, 쿠팡과 같은 이커머스 사이트에서 상품 리뷰 등의 데이터를 동적으로 수집합니다.
2. **데이터 분석 (Analysis)**:
- **전처리**: `KoNLPy`, `Mecab`, `Eunjeon` 등의 라이브러리를 사용하여 수집된 한글 텍스트 데이터를 형태소 단위로 분석하고 정제합니다.
- **AI 분석**: `api/analysis/` 디렉토리의 `sentiment.py`(감성 분석), `associate.py`(연관 분석) 모듈이 분석 로직을 담당합니다.
- `TensorFlow``Keras`로 구축된 딥러닝 모델을 사용하여 텍스트의 긍/부정 뉘앙스를 판단하는 감성 분석을 수행합니다.
3. **API 제공 (Serving)**:
- `FastAPI`를 사용하여 분석 기능을 REST API 형태로 제공합니다.
- `app/server.py`에서 라우터를 관리하며, 인증(`auth`), 크롤링, 분석 등 기능별로 엔드포인트를 모듈화하여 관리합니다.
- `core/middleware/token_validator.py`를 통해 API 요청에 대한 토큰 기반 인증을 수행하여 허가된 사용자만 접근할 수 있도록 합니다.
## 기술 스택
- **백엔드**: FastAPI, Uvicorn, Gunicorn
- **웹 크롤링**: Selenium, BeautifulSoup4, undetected-chromedriver
- **자연어 처리**: KoNLPy, Mecab, Eunjeon
- **AI/머신러닝**: TensorFlow, Keras, Scikit-learn
- **데이터베이스**: (Dockerfile 및 requirements.txt에 명시적인 DB 드라이버가 없어, 파일 기반 또는 외부 DB 연결로 추정됨)
- **오케스트레이션**: Docker, Docker Compose
## 실행 방법
### 사전 요구사항
- Docker 및 Docker Compose
### 설정
프로젝트에 필요한 환경 변수(예: DB 정보, 외부 API 키 등)는 `core/config.py` 또는 시스템 환경 변수를 통해 설정해야 합니다. (관련 설정 파일 확인 필요)
### 실행
1. **Docker 이미지 빌드 및 컨테이너 실행**:
```bash
# (선택) 기존 컨테이너 및 이미지 재빌드를 위한 스크립트
./rebuild.sh
# 또는 docker-compose 직접 실행
docker-compose up --build -d
```
2. **애플리케이션 접근**:
- **API 문서 (Swagger UI)**: 컨테이너 실행 후, 브라우저에서 `http://localhost:8001/docs`로 접속하여 API 명세를 확인할 수 있습니다.
### 중지
```bash
docker-compose down
```
\ No newline at end of file
version: '3'
services:
server:
build:
context: .
dockerfile: Dockerfile
container_name: fastapi_new_server
shm_size: 2g # 공유메모리 크기 설정(crome 크래시 방지)
network_mode: bridge
ports:
- "8001:8001"
tty: true
stdin_open: true
restart: always
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment