Skip to content

Commit 570a8a5

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 56dfc96 commit 570a8a5

27 files changed

Lines changed: 145 additions & 329 deletions

CogniwareIms/.pre-commit-config.yaml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# Copyright (C) 2026 Intel Corporation
2+
# SPDX-License-Identifier: Apache-2.0
3+
14
# Pre-commit hooks configuration for OPEA compliance
25
# See https://pre-commit.com for more information
36

CogniwareIms/README.md

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,4 +91,3 @@ Apache 2.0 - See [LICENSE](LICENSE) file for details.
9191
## Support
9292

9393
For issues and questions, please open an issue in the OPEA GenAIExamples repository.
94-

CogniwareIms/backend/Dockerfile

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
# Copyright (C) 2026 Intel Corporation
2+
# SPDX-License-Identifier: Apache-2.0
3+
14
# Multi-stage build for production optimization
25
FROM python:3.11-slim as builder
36

CogniwareIms/backend/app/core/config.py

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Copyright (C) 2024 Intel Corporation
22
# SPDX-License-Identifier: Apache-2.0
3-
43
"""Application configuration Centralized settings management following 12-factor app principles."""
54

65
import os
@@ -22,14 +21,10 @@ class Settings(BaseSettings):
2221

2322
# API Configuration
2423
API_V1_PREFIX: str = "/api"
25-
ALLOWED_ORIGINS: List[str] = os.getenv(
26-
"ALLOWED_ORIGINS", "http://localhost:3000,http://frontend:3000"
27-
).split(",")
24+
ALLOWED_ORIGINS: List[str] = os.getenv("ALLOWED_ORIGINS", "http://localhost:3000,http://frontend:3000").split(",")
2825

2926
# Security
30-
JWT_SECRET_KEY: str = os.getenv(
31-
"JWT_SECRET_KEY", "CHANGE_THIS_IN_PRODUCTION_USE_openssl_rand_hex_32"
32-
)
27+
JWT_SECRET_KEY: str = os.getenv("JWT_SECRET_KEY", "CHANGE_THIS_IN_PRODUCTION_USE_openssl_rand_hex_32")
3328
JWT_ALGORITHM: str = "HS256"
3429
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
3530
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
@@ -39,9 +34,7 @@ class Settings(BaseSettings):
3934
RATE_LIMIT_PER_MINUTE: int = int(os.getenv("RATE_LIMIT_PER_MINUTE", "60"))
4035

4136
# Database
42-
DATABASE_URL: str = os.getenv(
43-
"DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/opea_ims"
44-
)
37+
DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/opea_ims")
4538
DB_POOL_SIZE: int = 10
4639
DB_MAX_OVERFLOW: int = 20
4740

@@ -50,13 +43,9 @@ class Settings(BaseSettings):
5043
REDIS_MAX_CONNECTIONS: int = 50
5144

5245
# OPEA Services
53-
OPEA_EMBEDDING_URL: str = os.getenv(
54-
"OPEA_EMBEDDING_URL", "http://embedding-service:6000"
55-
)
46+
OPEA_EMBEDDING_URL: str = os.getenv("OPEA_EMBEDDING_URL", "http://embedding-service:6000")
5647
OPEA_LLM_URL: str = os.getenv("OPEA_LLM_URL", "http://llm-service:9000")
57-
OPEA_RETRIEVAL_URL: str = os.getenv(
58-
"OPEA_RETRIEVAL_URL", "http://retrieval-service:7000"
59-
)
48+
OPEA_RETRIEVAL_URL: str = os.getenv("OPEA_RETRIEVAL_URL", "http://retrieval-service:7000")
6049
OPEA_GATEWAY_URL: str = os.getenv("OPEA_GATEWAY_URL", "http://opea-gateway:8888")
6150

6251
# Models

CogniwareIms/backend/app/core/security.py

Lines changed: 5 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Copyright (C) 2024 Intel Corporation
22
# SPDX-License-Identifier: Apache-2.0
3-
43
"""
54
Security utilities - JWT, password hashing, authentication
65
Industry-standard security implementation
@@ -53,9 +52,7 @@ def get_password_hash(password: str) -> str:
5352
return pwd_context.hash(password)
5453

5554
@staticmethod
56-
def create_access_token(
57-
data: Dict[str, Any], expires_delta: Optional[timedelta] = None
58-
) -> str:
55+
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
5956
"""Create a JWT access token.
6057
6158
Args:
@@ -141,9 +138,7 @@ def protected_route(user: Dict = Depends(get_current_user)):
141138
# Extract user info from payload
142139
email = payload.get("sub")
143140
if email is None:
144-
raise HTTPException(
145-
status_code=401, detail="Invalid authentication credentials"
146-
)
141+
raise HTTPException(status_code=401, detail="Invalid authentication credentials")
147142

148143
return payload
149144

@@ -160,9 +155,7 @@ def admin_route(user: Dict = Depends(require_role("Super Admin"))):
160155
def role_checker(current_user: Dict = Depends(get_current_user)):
161156
user_role = current_user.get("role")
162157
if user_role != required_role:
163-
raise HTTPException(
164-
status_code=403, detail=f"Access denied. Required role: {required_role}"
165-
)
158+
raise HTTPException(status_code=403, detail=f"Access denied. Required role: {required_role}")
166159
return current_user
167160

168161
return role_checker
@@ -241,9 +234,7 @@ class RateLimiter:
241234
def __init__(self):
242235
self.requests = {}
243236

244-
def is_allowed(
245-
self, identifier: str, max_requests: int = 60, window_seconds: int = 60
246-
) -> bool:
237+
def is_allowed(self, identifier: str, max_requests: int = 60, window_seconds: int = 60) -> bool:
247238
"""Check if request is allowed under rate limit.
248239
249240
Args:
@@ -261,9 +252,7 @@ def is_allowed(
261252

262253
# Clean old requests
263254
cutoff = now - timedelta(seconds=window_seconds)
264-
self.requests[identifier] = [
265-
req_time for req_time in self.requests[identifier] if req_time > cutoff
266-
]
255+
self.requests[identifier] = [req_time for req_time in self.requests[identifier] if req_time > cutoff]
267256

268257
# Check limit
269258
if len(self.requests[identifier]) >= max_requests:

CogniwareIms/backend/app/init_knowledge_base.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Copyright (C) 2024 Intel Corporation
22
# SPDX-License-Identifier: Apache-2.0
3-
43
"""Knowledge Base Initialization Script Processes all CSV files and creates initial embeddings Run this after first
54
deployment to populate the knowledge base."""
65

@@ -19,9 +18,7 @@
1918
from app.services.knowledge_manager import knowledge_manager
2019
from app.services.retrieval_service import retrieval_service
2120

22-
logging.basicConfig(
23-
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
24-
)
21+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
2522
logger = logging.getLogger(__name__)
2623

2724

@@ -49,17 +46,13 @@ async def initialize_knowledge_base():
4946

5047
for i in range(0, len(documents), batch_size):
5148
batch = documents[i : i + batch_size]
52-
logger.info(
53-
f" Processing batch {i//batch_size + 1}/{(len(documents)-1)//batch_size + 1}..."
54-
)
49+
logger.info(f" Processing batch {i//batch_size + 1}/{(len(documents)-1)//batch_size + 1}...")
5550

5651
# Extract texts
5752
texts = [doc["text"] for doc in batch]
5853

5954
# Generate embeddings in batch
60-
embeddings = await embedding_service.embed_batch(
61-
texts, batch_size=batch_size
62-
)
55+
embeddings = await embedding_service.embed_batch(texts, batch_size=batch_size)
6356

6457
# Index each document
6558
for doc, embedding in zip(batch, embeddings):
@@ -97,11 +90,11 @@ async def initialize_knowledge_base():
9790
logger.info("\n" + "=" * 60)
9891
logger.info("🎉 Knowledge Base Initialization Complete!")
9992
logger.info("=" * 60)
100-
logger.info(f"\n📊 Summary:")
93+
logger.info("\n📊 Summary:")
10194
logger.info(f" CSV Files Processed: {len(dataframes)}")
10295
logger.info(f" Documents Indexed: {total_indexed}")
10396
logger.info(f" Vector Store Count: {doc_count}")
104-
logger.info(f"\n✅ System is ready for AI-powered queries!")
97+
logger.info("\n✅ System is ready for AI-powered queries!")
10598

10699
return {
107100
"success": True,
@@ -134,9 +127,7 @@ async def quick_test():
134127

135128
# Test knowledge manager
136129
stats = await knowledge_manager.get_knowledge_stats()
137-
logger.info(
138-
f"✅ Knowledge manager: OK ({stats.get('total_documents', 0)} documents)"
139-
)
130+
logger.info(f"✅ Knowledge manager: OK ({stats.get('total_documents', 0)} documents)")
140131

141132
logger.info("\n🎉 All systems operational!")
142133

CogniwareIms/backend/app/main.py

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Copyright (C) 2024 Intel Corporation
22
# SPDX-License-Identifier: Apache-2.0
3-
43
"""
54
OPEA Inventory Management System - Complete Backend API
65
Full integration with all OPEA GenAIComps microservices
@@ -160,9 +159,7 @@ async def health_check():
160159
db_health = await dbqna_service.health_check()
161160

162161
return {
163-
"status": (
164-
"healthy" if all([embedding_health, llm_health, db_health]) else "degraded"
165-
),
162+
"status": ("healthy" if all([embedding_health, llm_health, db_health]) else "degraded"),
166163
"timestamp": datetime.now().isoformat(),
167164
"services": {
168165
"api": "up",
@@ -325,9 +322,7 @@ async def upload_csv_knowledge(file: UploadFile = File(...)):
325322
content = await file.read()
326323

327324
# Process using file upload service
328-
result = await file_upload_service.upload_and_process(
329-
filename=file.filename, content=content
330-
)
325+
result = await file_upload_service.upload_and_process(filename=file.filename, content=content)
331326

332327
return result
333328

@@ -345,9 +340,7 @@ async def upload_knowledge_file(file: UploadFile = File(...)):
345340
content = await file.read()
346341

347342
# Process using file upload service
348-
result = await file_upload_service.upload_and_process(
349-
filename=file.filename, content=content
350-
)
343+
result = await file_upload_service.upload_and_process(filename=file.filename, content=content)
351344

352345
return result
353346

@@ -658,9 +651,7 @@ async def startup_event():
658651

659652
# Load knowledge base stats
660653
stats = await knowledge_manager.get_knowledge_stats()
661-
logger.info(
662-
f" Knowledge Base: {stats.get('total_documents', 0)} documents indexed"
663-
)
654+
logger.info(f" Knowledge Base: {stats.get('total_documents', 0)} documents indexed")
664655

665656
logger.info("✅ OPEA IMS Platform started successfully!")
666657

CogniwareIms/backend/app/services/csv_processor.py

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Copyright (C) 2024 Intel Corporation
22
# SPDX-License-Identifier: Apache-2.0
3-
43
"""CSV Data Processor Ingests CSV files and prepares them for OPEA knowledge base."""
54

65
import json
@@ -37,9 +36,7 @@ def load_all_csv_files(self) -> Dict[str, pd.DataFrame]:
3736

3837
return dataframes
3938

40-
def prepare_for_embedding(
41-
self, dataframes: Dict[str, pd.DataFrame]
42-
) -> List[Dict[str, Any]]:
39+
def prepare_for_embedding(self, dataframes: Dict[str, pd.DataFrame]) -> List[Dict[str, Any]]:
4340
"""Prepare data for OPEA embedding service."""
4441
documents = []
4542

@@ -66,9 +63,7 @@ def prepare_for_embedding(
6663
logger.info(f"Prepared {len(documents)} documents for embedding")
6764
return documents
6865

69-
def extract_inventory_data(
70-
self, dataframes: Dict[str, pd.DataFrame]
71-
) -> Dict[str, Any]:
66+
def extract_inventory_data(self, dataframes: Dict[str, pd.DataFrame]) -> Dict[str, Any]:
7267
"""Extract structured inventory data."""
7368
inventory_data = {
7469
"products": [],
@@ -117,9 +112,7 @@ def create_knowledge_base(self) -> Dict[str, Any]:
117112
with open(output_dir / "knowledge_base.json", "w") as f:
118113
json.dump(knowledge_base, f, indent=2, default=str)
119114

120-
logger.info(
121-
f"Knowledge base created with {len(knowledge_base['documents'])} documents"
122-
)
115+
logger.info(f"Knowledge base created with {len(knowledge_base['documents'])} documents")
123116

124117
return knowledge_base
125118

CogniwareIms/backend/app/services/dbqna_service.py

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
# Copyright (C) 2024 Intel Corporation
22
# SPDX-License-Identifier: Apache-2.0
3-
43
"""
54
OPEA DBQnA Service - Database Query & Answer
65
Converts natural language to SQL and executes against inventory database
@@ -22,9 +21,7 @@ class DBQnAService:
2221
"""Database Query & Answer service using OPEA LLM for SQL generation."""
2322

2423
def __init__(self):
25-
self.database_url = os.getenv(
26-
"DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/opea_ims"
27-
)
24+
self.database_url = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/opea_ims")
2825
self.engine = None
2926
self.schema_cache = None
3027

@@ -66,15 +63,9 @@ async def get_schema(self) -> Dict[str, Any]:
6663
ORDER BY ordinal_position
6764
"""
6865
)
69-
columns = conn.execute(
70-
columns_query, {"table_name": table_name}
71-
).fetchall()
72-
73-
schema["tables"][table_name] = {
74-
"columns": [
75-
{"name": col, "type": dtype} for col, dtype in columns
76-
]
77-
}
66+
columns = conn.execute(columns_query, {"table_name": table_name}).fetchall()
67+
68+
schema["tables"][table_name] = {"columns": [{"name": col, "type": dtype} for col, dtype in columns]}
7869

7970
self.schema_cache = schema
8071
return schema
@@ -83,9 +74,7 @@ async def get_schema(self) -> Dict[str, Any]:
8374
logger.error(f"Error getting schema: {e}")
8475
return {"tables": {}, "relationships": []}
8576

86-
async def natural_language_query(
87-
self, question: str, include_explanation: bool = True
88-
) -> Dict[str, Any]:
77+
async def natural_language_query(self, question: str, include_explanation: bool = True) -> Dict[str, Any]:
8978
"""Convert natural language question to SQL and execute.
9079
9180
Args:
@@ -112,9 +101,7 @@ async def natural_language_query(
112101
columns = result.keys()
113102

114103
# Convert to dict format
115-
data = [
116-
{col: value for col, value in zip(columns, row)} for row in rows
117-
]
104+
data = [{col: value for col, value in zip(columns, row)} for row in rows]
118105

119106
response = {
120107
"success": True,

0 commit comments

Comments
 (0)