christopher commited on
Commit
1db196f
·
1 Parent(s): e00c07d

Added loggin info for each step

Browse files
Files changed (1) hide show
  1. app.py +50 -15
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  from fastapi import FastAPI, HTTPException, BackgroundTasks
2
  from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
@@ -12,6 +13,14 @@ from models.nlp import NLPModel
12
  from database.query import DatabaseService
13
  from database.query_processor import QueryProcessor
14
 
 
 
 
 
 
 
 
 
15
  # Initialize models
16
  embedding_model = None
17
  summarization_model = None
@@ -20,16 +29,30 @@ db_service = None
20
 
21
  @asynccontextmanager
22
  async def lifespan(app: FastAPI):
23
- # Load models when app starts
24
  global embedding_model, summarization_model, nlp_model, db_service
25
- embedding_model = EmbeddingModel()
26
- summarization_model = SummarizationModel()
27
- nlp_model = NLPModel()
28
- db_service = DatabaseService()
 
 
 
 
 
 
 
 
 
29
  yield
30
- # Clean up when app stops
 
 
31
  if db_service:
32
- await db_service.close()
 
 
 
 
33
 
34
  app = FastAPI(
35
  title="Kairos News API",
@@ -50,23 +73,24 @@ jobs_db: Dict[str, Dict] = {}
50
  class PostRequest(BaseModel):
51
  query: str
52
  topic: Optional[str] = None
53
- start_date: Optional[str] = None # Format: "YYYY-MM-DD"
54
- end_date: Optional[str] = None # Format: "YYYY-MM-DD"
55
 
56
  class JobStatus(BaseModel):
57
  id: str
58
- status: str # "processing", "completed", "failed"
59
  created_at: datetime
60
  completed_at: Optional[datetime] = None
61
  request: PostRequest
62
- result: Optional[Dict[str, Any]] = None # Flexible result structure
63
 
64
  @app.post("/index", response_model=JobStatus)
65
  async def create_job(request: PostRequest, background_tasks: BackgroundTasks):
66
  job_id = str(uuid.uuid4())
67
-
 
68
  jobs_db[job_id] = {
69
- "id": job_id, # Ensure `id` is included
70
  "status": "processing",
71
  "created_at": datetime.now(),
72
  "completed_at": None,
@@ -84,13 +108,17 @@ async def create_job(request: PostRequest, background_tasks: BackgroundTasks):
84
  db_service
85
  )
86
 
87
- return jobs_db[job_id] # Return the full job object
 
88
 
89
  @app.get("/loading", response_model=JobStatus)
90
  async def get_job_status(id: str):
 
91
  if id not in jobs_db:
 
92
  raise HTTPException(status_code=404, detail="Job not found")
93
 
 
94
  return jobs_db[id]
95
 
96
  async def process_job(
@@ -102,6 +130,8 @@ async def process_job(
102
  db_service: DatabaseService
103
  ):
104
  try:
 
 
105
  processor = QueryProcessor(
106
  embedding_model=embedding_model,
107
  summarization_model=summarization_model,
@@ -109,6 +139,7 @@ async def process_job(
109
  db_service=db_service
110
  )
111
 
 
112
  result = await processor.process(
113
  query=request.query,
114
  topic=request.topic,
@@ -121,9 +152,13 @@ async def process_job(
121
  "completed_at": datetime.now(),
122
  "result": result if result else {"message": "No results found"}
123
  })
 
 
124
  except Exception as e:
 
125
  jobs_db[job_id].update({
126
  "status": "failed",
127
  "completed_at": datetime.now(),
128
  "result": {"error": str(e)}
129
- })
 
 
1
+ import logging
2
  from fastapi import FastAPI, HTTPException, BackgroundTasks
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from pydantic import BaseModel
 
13
  from database.query import DatabaseService
14
  from database.query_processor import QueryProcessor
15
 
16
+ # Configure logging
17
+ logging.basicConfig(
18
+ level=logging.INFO,
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
26
  summarization_model = None
 
29
 
30
  @asynccontextmanager
31
  async def lifespan(app: FastAPI):
 
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",
 
73
  class PostRequest(BaseModel):
74
  query: str
75
  topic: Optional[str] = None
76
+ start_date: Optional[str] = None
77
+ end_date: Optional[str] = None
78
 
79
  class JobStatus(BaseModel):
80
  id: str
81
+ status: str
82
  created_at: datetime
83
  completed_at: Optional[datetime] = None
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",
95
  "created_at": datetime.now(),
96
  "completed_at": None,
 
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,
137
  summarization_model=summarization_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")