Rulga commited on
Commit
350af29
·
1 Parent(s): 84f1cd4

change python 3.11 slim and others

Browse files
Files changed (3) hide show
  1. Dockerfile +7 -11
  2. app.py +67 -33
  3. requirements.txt +1 -2
Dockerfile CHANGED
@@ -1,4 +1,4 @@
1
- FROM python:3.9-slim
2
 
3
  WORKDIR /app
4
 
@@ -10,34 +10,30 @@ RUN apt-get update && apt-get install -y \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Create directories and set permissions
13
- RUN mkdir -p /app/vector_store /app/chat_history /app/.cache && \
14
- chmod 777 /app/vector_store /app/chat_history /app/.cache
15
 
16
- # Set environment variables and cache directories
17
  ENV TRANSFORMERS_CACHE=/app/.cache/huggingface
18
  ENV HF_HOME=/app/.cache/huggingface
19
  ENV XDG_CACHE_HOME=/app/.cache
 
20
 
21
  # Create cache directories with proper permissions
22
  RUN mkdir -p /app/.cache/huggingface && \
23
  chmod -R 777 /app/.cache
24
 
25
- # Copy requirements first to leverage Docker cache
26
  COPY requirements.txt .
27
  RUN pip install --no-cache-dir -r requirements.txt
28
 
29
- # Copy the rest of the application
30
  COPY . .
31
 
32
- # Set permissions for the application directory
33
  RUN chown -R 1000:1000 /app && \
34
  chmod -R 755 /app
35
 
36
- # Make port 8000 available to the world outside this container
37
  EXPOSE 8000
38
 
39
- # Run the application as non-root user
40
  USER 1000
41
 
42
- # Run the application
43
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
 
1
+ FROM python:3.11-slim
2
 
3
  WORKDIR /app
4
 
 
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Create directories and set permissions
13
+ RUN mkdir -p /app/vector_store /app/chat_history /app/.cache /app/logs && \
14
+ chmod 777 /app/vector_store /app/chat_history /app/.cache /app/logs
15
 
16
+ # Set environment variables
17
  ENV TRANSFORMERS_CACHE=/app/.cache/huggingface
18
  ENV HF_HOME=/app/.cache/huggingface
19
  ENV XDG_CACHE_HOME=/app/.cache
20
+ ENV PYTHONUNBUFFERED=1
21
 
22
  # Create cache directories with proper permissions
23
  RUN mkdir -p /app/.cache/huggingface && \
24
  chmod -R 777 /app/.cache
25
 
 
26
  COPY requirements.txt .
27
  RUN pip install --no-cache-dir -r requirements.txt
28
 
 
29
  COPY . .
30
 
 
31
  RUN chown -R 1000:1000 /app && \
32
  chmod -R 755 /app
33
 
 
34
  EXPOSE 8000
35
 
 
36
  USER 1000
37
 
38
+ # Изменяем команду запуска для сохранения логов
39
+ CMD ["sh", "-c", "uvicorn app:app --host 0.0.0.0 --port 8000 --log-level debug 2>&1 | tee /app/logs/app.log"]
app.py CHANGED
@@ -28,32 +28,35 @@ from rich.table import Table
28
 
29
  console = Console()
30
 
 
 
 
 
 
 
 
31
  # Initialize environment variables
32
  load_dotenv()
 
33
 
34
  # Define constants for directory paths
35
- VECTOR_STORE_PATH = "vector_store"
36
- CHAT_HISTORY_PATH = "chat_history"
 
37
 
38
  def create_required_directories():
39
  """Create required directories if they don't exist"""
40
- directories = [VECTOR_STORE_PATH, CHAT_HISTORY_PATH]
41
- for directory in directories:
42
- try:
43
- if not os.path.exists(directory):
44
- os.makedirs(directory, exist_ok=True)
45
- print(f"Created directory: {directory}")
46
-
47
- # Create .gitkeep file to preserve empty directory
48
- gitkeep_path = os.path.join(directory, '.gitkeep')
49
  with open(gitkeep_path, 'w') as f:
50
  pass
51
- except Exception as e:
52
- print(f"Error creating directory {directory}: {str(e)}")
53
- raise HTTPException(
54
- status_code=500,
55
- detail=f"Failed to create required directory: {directory}"
56
- )
57
 
58
  # Create directories before initializing the app
59
  create_required_directories()
@@ -64,8 +67,43 @@ app.include_router(analysis_router)
64
  # Add startup event handler to ensure directories exist
65
  @app.on_event("startup")
66
  async def startup_event():
67
- """Ensure required directories exist on startup"""
68
- create_required_directories()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  # Add custom exception handlers
71
  @app.exception_handler(requests.exceptions.RequestException)
@@ -360,21 +398,17 @@ def print_startup_status():
360
  console.print(f"[bold red]Error printing status: {str(e)}[/bold red]")
361
 
362
  if __name__ == "__main__":
 
 
 
 
 
363
  config = uvicorn.Config(
364
- "app:app",
365
  host="0.0.0.0",
366
- port=8000,
367
- log_level="info",
368
- reload=True
369
  )
370
- server = uvicorn.Server(config)
371
 
372
- try:
373
- # Start the server
374
- console.print("[bold yellow]Starting Status Law Assistant API...[/bold yellow]")
375
- server.run()
376
- except Exception as e:
377
- console.print(f"[bold red]Server failed to start: {str(e)}[/bold red]")
378
- finally:
379
- # Print startup status after uvicorn starts
380
- print_startup_status()
 
28
 
29
  console = Console()
30
 
31
+ # Настройка логирования
32
+ logging.basicConfig(
33
+ level=logging.DEBUG,
34
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
35
+ )
36
+ logger = logging.getLogger(__name__)
37
+
38
  # Initialize environment variables
39
  load_dotenv()
40
+ logger.debug("Environment variables loaded")
41
 
42
  # Define constants for directory paths
43
+ VECTOR_STORE_PATH = os.path.join(os.getcwd(), "vector_store")
44
+ CHAT_HISTORY_PATH = os.path.join(os.getcwd(), "chat_history")
45
+ logger.debug(f"Paths initialized: VECTOR_STORE_PATH={VECTOR_STORE_PATH}, CHAT_HISTORY_PATH={CHAT_HISTORY_PATH}")
46
 
47
  def create_required_directories():
48
  """Create required directories if they don't exist"""
49
+ try:
50
+ for directory in [VECTOR_STORE_PATH, CHAT_HISTORY_PATH]:
51
+ os.makedirs(directory, exist_ok=True)
52
+ gitkeep_path = os.path.join(directory, '.gitkeep')
53
+ if not os.path.exists(gitkeep_path):
 
 
 
 
54
  with open(gitkeep_path, 'w') as f:
55
  pass
56
+ logger.debug(f"Directory created/verified: {directory}")
57
+ except Exception as e:
58
+ logger.error(f"Error creating directories: {str(e)}")
59
+ raise
 
 
60
 
61
  # Create directories before initializing the app
62
  create_required_directories()
 
67
  # Add startup event handler to ensure directories exist
68
  @app.on_event("startup")
69
  async def startup_event():
70
+ """Startup event handler"""
71
+ try:
72
+ logger.info("Starting application...")
73
+ # Проверяем наличие необходимых переменных окружения
74
+ if not os.getenv("GROQ_API_KEY"):
75
+ logger.error("GROQ_API_KEY not found in environment variables")
76
+ raise ValueError("GROQ_API_KEY is required")
77
+
78
+ # Проверяем доступность директорий
79
+ for directory in [VECTOR_STORE_PATH, CHAT_HISTORY_PATH]:
80
+ if not os.path.exists(directory):
81
+ logger.error(f"Required directory not found: {directory}")
82
+ raise ValueError(f"Required directory not found: {directory}")
83
+
84
+ logger.info("Application startup completed successfully")
85
+ except Exception as e:
86
+ logger.error(f"Startup failed: {str(e)}")
87
+ raise
88
+
89
+ @app.on_event("shutdown")
90
+ async def shutdown_event():
91
+ """Shutdown event handler"""
92
+ logger.info("Application shutting down...")
93
+
94
+ # Базовый маршрут для проверки
95
+ @app.get("/")
96
+ async def root():
97
+ logger.debug("Root endpoint called")
98
+ return {
99
+ "status": "ok",
100
+ "message": "Status Law Assistant API is running",
101
+ "environment": {
102
+ "GROQ_API_KEY": "configured" if os.getenv("GROQ_API_KEY") else "missing",
103
+ "vector_store": os.path.exists(VECTOR_STORE_PATH),
104
+ "chat_history": os.path.exists(CHAT_HISTORY_PATH)
105
+ }
106
+ }
107
 
108
  # Add custom exception handlers
109
  @app.exception_handler(requests.exceptions.RequestException)
 
398
  console.print(f"[bold red]Error printing status: {str(e)}[/bold red]")
399
 
400
  if __name__ == "__main__":
401
+ import uvicorn
402
+
403
+ port = int(os.getenv("PORT", 8000))
404
+ logger.info(f"Starting server on port {port}")
405
+
406
  config = uvicorn.Config(
407
+ app,
408
  host="0.0.0.0",
409
+ port=port,
410
+ log_level="debug"
 
411
  )
 
412
 
413
+ server = uvicorn.Server(config)
414
+ server.run()
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -21,5 +21,4 @@ pytest-asyncio
21
  aiohttp
22
  requests
23
  tenacity
24
- rich>=10.0.0
25
-
 
21
  aiohttp
22
  requests
23
  tenacity
24
+ rich>=10.0.0