christopher
commited on
Commit
·
21f3f8a
1
Parent(s):
c708265
Removed App changes
Browse files
app.py
CHANGED
@@ -1,13 +1,12 @@
|
|
1 |
import logging
|
2 |
-
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
3 |
from fastapi.middleware.cors import CORSMiddleware
|
4 |
-
from fastapi.responses import JSONResponse
|
5 |
from pydantic import BaseModel
|
6 |
from typing import Dict, Optional, List, Any
|
7 |
import uuid
|
8 |
from datetime import datetime
|
9 |
from contextlib import asynccontextmanager
|
10 |
-
|
11 |
from models.embedding import EmbeddingModel
|
12 |
from models.summarization import SummarizationModel
|
13 |
from models.nlp import NLPModel
|
@@ -20,6 +19,7 @@ logging.basicConfig(
|
|
20 |
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
21 |
handlers=[logging.StreamHandler()]
|
22 |
)
|
|
|
23 |
|
24 |
# Initialize models
|
25 |
embedding_model = None
|
@@ -32,27 +32,27 @@ async def lifespan(app: FastAPI):
|
|
32 |
global embedding_model, summarization_model, nlp_model, db_service
|
33 |
|
34 |
# Model initialization
|
35 |
-
|
36 |
try:
|
37 |
embedding_model = EmbeddingModel()
|
38 |
summarization_model = SummarizationModel()
|
39 |
nlp_model = NLPModel()
|
40 |
db_service = DatabaseService()
|
41 |
-
|
42 |
except Exception as e:
|
43 |
-
|
44 |
raise
|
45 |
|
46 |
yield
|
47 |
|
48 |
# Cleanup
|
49 |
-
|
50 |
if db_service:
|
51 |
try:
|
52 |
await db_service.close()
|
53 |
-
|
54 |
except Exception as e:
|
55 |
-
|
56 |
|
57 |
app = FastAPI(
|
58 |
title="Kairos News API",
|
@@ -84,51 +84,11 @@ class JobStatus(BaseModel):
|
|
84 |
request: PostRequest
|
85 |
result: Optional[Dict[str, Any]] = None
|
86 |
|
87 |
-
@app.get("/")
|
88 |
-
async def root(request: Request):
|
89 |
-
"""Root endpoint with API information"""
|
90 |
-
logging.info(f"Root access from {request.client.host}")
|
91 |
-
return {
|
92 |
-
"message": "Kairos News API is running",
|
93 |
-
"endpoints": {
|
94 |
-
"create_job": {"method": "POST", "path": "/index"},
|
95 |
-
"check_status": {"method": "GET", "path": "/loading"},
|
96 |
-
"get_logs": {"method": "GET", "path": "/logs"}
|
97 |
-
}
|
98 |
-
}
|
99 |
-
|
100 |
-
@app.get("/logs")
|
101 |
-
async def get_logs(log_type: str = None):
|
102 |
-
"""Endpoint for log retrieval"""
|
103 |
-
if log_type == "container":
|
104 |
-
return {"message": "Container logs endpoint", "status": "Not implemented"}
|
105 |
-
return {
|
106 |
-
"message": "Available log types: container",
|
107 |
-
"usage": "/logs?log_type=container"
|
108 |
-
}
|
109 |
-
|
110 |
-
@app.exception_handler(404)
|
111 |
-
async def not_found_exception_handler(request: Request, exc: HTTPException):
|
112 |
-
"""Custom 404 handler"""
|
113 |
-
logging.warning(f"404 Not Found: {request.url}")
|
114 |
-
return JSONResponse(
|
115 |
-
status_code=404,
|
116 |
-
content={
|
117 |
-
"message": "Endpoint not found",
|
118 |
-
"available_endpoints": [
|
119 |
-
{"path": "/", "method": "GET"},
|
120 |
-
{"path": "/index", "method": "POST"},
|
121 |
-
{"path": "/loading", "method": "GET"},
|
122 |
-
{"path": "/logs", "method": "GET"}
|
123 |
-
]
|
124 |
-
},
|
125 |
-
)
|
126 |
-
|
127 |
@app.post("/index", response_model=JobStatus)
|
128 |
async def create_job(request: PostRequest, background_tasks: BackgroundTasks):
|
129 |
job_id = str(uuid.uuid4())
|
130 |
-
|
131 |
-
|
132 |
jobs_db[job_id] = {
|
133 |
"id": job_id,
|
134 |
"status": "processing",
|
@@ -148,17 +108,17 @@ async def create_job(request: PostRequest, background_tasks: BackgroundTasks):
|
|
148 |
db_service
|
149 |
)
|
150 |
|
151 |
-
|
152 |
return jobs_db[job_id]
|
153 |
|
154 |
@app.get("/loading", response_model=JobStatus)
|
155 |
async def get_job_status(id: str):
|
156 |
-
|
157 |
if id not in jobs_db:
|
158 |
-
|
159 |
raise HTTPException(status_code=404, detail="Job not found")
|
160 |
|
161 |
-
|
162 |
return jobs_db[id]
|
163 |
|
164 |
async def process_job(
|
@@ -170,7 +130,7 @@ async def process_job(
|
|
170 |
db_service: DatabaseService
|
171 |
):
|
172 |
try:
|
173 |
-
|
174 |
|
175 |
processor = QueryProcessor(
|
176 |
embedding_model=embedding_model,
|
@@ -179,7 +139,7 @@ async def process_job(
|
|
179 |
db_service=db_service
|
180 |
)
|
181 |
|
182 |
-
|
183 |
result = await processor.process(
|
184 |
query=request.query,
|
185 |
topic=request.topic,
|
@@ -192,13 +152,13 @@ async def process_job(
|
|
192 |
"completed_at": datetime.now(),
|
193 |
"result": result if result else {"message": "No results found"}
|
194 |
})
|
195 |
-
|
196 |
|
197 |
except Exception as e:
|
198 |
-
|
199 |
jobs_db[job_id].update({
|
200 |
"status": "failed",
|
201 |
"completed_at": datetime.now(),
|
202 |
"result": {"error": str(e)}
|
203 |
})
|
204 |
-
|
|
|
1 |
import logging
|
2 |
+
from fastapi import FastAPI, HTTPException, BackgroundTasks
|
3 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
4 |
from pydantic import BaseModel
|
5 |
from typing import Dict, Optional, List, Any
|
6 |
import uuid
|
7 |
from datetime import datetime
|
8 |
from contextlib import asynccontextmanager
|
9 |
+
|
10 |
from models.embedding import EmbeddingModel
|
11 |
from models.summarization import SummarizationModel
|
12 |
from models.nlp import NLPModel
|
|
|
19 |
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
|
20 |
handlers=[logging.StreamHandler()]
|
21 |
)
|
22 |
+
logger = logging.getLogger(__name__)
|
23 |
|
24 |
# Initialize models
|
25 |
embedding_model = None
|
|
|
32 |
global embedding_model, summarization_model, nlp_model, db_service
|
33 |
|
34 |
# Model initialization
|
35 |
+
logger.info("Initializing models...")
|
36 |
try:
|
37 |
embedding_model = EmbeddingModel()
|
38 |
summarization_model = SummarizationModel()
|
39 |
nlp_model = NLPModel()
|
40 |
db_service = DatabaseService()
|
41 |
+
logger.info("All models initialized successfully")
|
42 |
except Exception as e:
|
43 |
+
logger.error(f"Model initialization failed: {str(e)}")
|
44 |
raise
|
45 |
|
46 |
yield
|
47 |
|
48 |
# Cleanup
|
49 |
+
logger.info("Shutting down application...")
|
50 |
if db_service:
|
51 |
try:
|
52 |
await db_service.close()
|
53 |
+
logger.info("Database connection closed successfully")
|
54 |
except Exception as e:
|
55 |
+
logger.error(f"Error closing database connection: {str(e)}")
|
56 |
|
57 |
app = FastAPI(
|
58 |
title="Kairos News API",
|
|
|
84 |
request: PostRequest
|
85 |
result: Optional[Dict[str, Any]] = None
|
86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
@app.post("/index", response_model=JobStatus)
|
88 |
async def create_job(request: PostRequest, background_tasks: BackgroundTasks):
|
89 |
job_id = str(uuid.uuid4())
|
90 |
+
logger.info(f"Creating new job {job_id} with request: {request.dict()}")
|
91 |
+
|
92 |
jobs_db[job_id] = {
|
93 |
"id": job_id,
|
94 |
"status": "processing",
|
|
|
108 |
db_service
|
109 |
)
|
110 |
|
111 |
+
logger.info(f"Job {job_id} created and processing started")
|
112 |
return jobs_db[job_id]
|
113 |
|
114 |
@app.get("/loading", response_model=JobStatus)
|
115 |
async def get_job_status(id: str):
|
116 |
+
logger.info(f"Checking status for job {id}")
|
117 |
if id not in jobs_db:
|
118 |
+
logger.warning(f"Job {id} not found")
|
119 |
raise HTTPException(status_code=404, detail="Job not found")
|
120 |
|
121 |
+
logger.info(f"Returning status for job {id}: {jobs_db[id]['status']}")
|
122 |
return jobs_db[id]
|
123 |
|
124 |
async def process_job(
|
|
|
130 |
db_service: DatabaseService
|
131 |
):
|
132 |
try:
|
133 |
+
logger.info(f"Starting processing for job {job_id}")
|
134 |
|
135 |
processor = QueryProcessor(
|
136 |
embedding_model=embedding_model,
|
|
|
139 |
db_service=db_service
|
140 |
)
|
141 |
|
142 |
+
logger.debug(f"Processing query: {request.query}")
|
143 |
result = await processor.process(
|
144 |
query=request.query,
|
145 |
topic=request.topic,
|
|
|
152 |
"completed_at": datetime.now(),
|
153 |
"result": result if result else {"message": "No results found"}
|
154 |
})
|
155 |
+
logger.info(f"Job {job_id} completed successfully")
|
156 |
|
157 |
except Exception as e:
|
158 |
+
logger.error(f"Error processing job {job_id}: {str(e)}", exc_info=True)
|
159 |
jobs_db[job_id].update({
|
160 |
"status": "failed",
|
161 |
"completed_at": datetime.now(),
|
162 |
"result": {"error": str(e)}
|
163 |
})
|
164 |
+
logger.info(f"Job {job_id} marked as failed")
|