Emmanuel Frimpong Asante commited on
Commit
7f34162
·
1 Parent(s): c514c85

"Update space"

Browse files

Signed-off-by: Emmanuel Frimpong Asante <[email protected]>

app.py CHANGED
@@ -5,10 +5,8 @@ import tensorflow as tf
5
  from pymongo import MongoClient
6
  from flask import Flask, request, jsonify, render_template
7
  from huggingface_hub import login
8
- import threading
9
  from services.disease_detection import PoultryFarmBot
10
  from services.llama_service import llama2_response
11
- from config.db import db
12
 
13
  # Initialize Flask application
14
  app = Flask(__name__, template_folder="templates", static_folder="static")
 
5
  from pymongo import MongoClient
6
  from flask import Flask, request, jsonify, render_template
7
  from huggingface_hub import login
 
8
  from services.disease_detection import PoultryFarmBot
9
  from services.llama_service import llama2_response
 
10
 
11
  # Initialize Flask application
12
  app = Flask(__name__, template_folder="templates", static_folder="static")
data/logs/daily_logs.py CHANGED
@@ -3,9 +3,7 @@
3
  from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
6
-
7
- # MongoDB connection (import from your db configuration)
8
- from config.db import db
9
 
10
  # Define the daily logs collection
11
  daily_logs_collection = db.daily_logs # Collection to store daily logs
@@ -134,26 +132,3 @@ def delete_daily_log(log_id):
134
  """
135
  result = daily_logs_collection.delete_one({"_id": ObjectId(log_id)})
136
  return result.deleted_count > 0
137
-
138
-
139
- # Example function to create a sample daily log
140
- if __name__ == "__main__":
141
- # Insert a test daily log
142
- test_user_id = "610c5e8a85f0b2a4e0b8b918" # Replace with a valid user ObjectId
143
- test_date = "2024-10-07"
144
- test_health_status = "All poultry are healthy, no signs of disease."
145
- test_feed_consumption = 500 # In kilograms
146
- test_mortality_rate = 0.0 # No deaths today
147
- test_inventory_levels = {"Feed": 1000, "Antibiotics": 50} # Inventory in kilograms and units
148
-
149
- log_id = create_daily_log(
150
- user_id=test_user_id,
151
- date=test_date,
152
- health_status=test_health_status,
153
- feed_consumption=test_feed_consumption,
154
- mortality_rate=test_mortality_rate,
155
- inventory_levels=test_inventory_levels,
156
- notes="Everything ran smoothly today."
157
- )
158
-
159
- print(f"Daily log created with ID: {log_id}")
 
3
  from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
6
+ from config.db import db # MongoDB connection from config
 
 
7
 
8
  # Define the daily logs collection
9
  daily_logs_collection = db.daily_logs # Collection to store daily logs
 
132
  """
133
  result = daily_logs_collection.delete_one({"_id": ObjectId(log_id)})
134
  return result.deleted_count > 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
data/logs/user_usage.py CHANGED
@@ -3,9 +3,7 @@
3
  from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
6
-
7
- # MongoDB connection (import from your db configuration)
8
- from config.db import db
9
 
10
  # Define the user usage logs collection
11
  user_usage_collection = db.user_usage # Collection to store assistant usage logs
@@ -113,21 +111,3 @@ def delete_usage_log(log_id):
113
  """
114
  result = user_usage_collection.delete_one({"_id": ObjectId(log_id)})
115
  return result.deleted_count > 0
116
-
117
-
118
- # Example function to create a sample user usage log
119
- if __name__ == "__main__":
120
- # Insert a test user usage log
121
- test_user_id = "610c5e8a85f0b2a4e0b8b918" # Replace with a valid user ObjectId
122
- test_manager_id = "610c5e8a85f0b2a4e0b8b919" # Replace with a valid manager ObjectId
123
- test_interaction_type = "disease_detection"
124
- test_metadata = {"disease_name": "Coccidiosis", "detected": True}
125
-
126
- log_id = create_user_usage_log(
127
- user_id=test_user_id,
128
- manager_id=test_manager_id,
129
- interaction_type=test_interaction_type,
130
- metadata=test_metadata
131
- )
132
-
133
- print(f"User usage log created with ID: {log_id}")
 
3
  from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
6
+ from config.db import db # MongoDB connection from configuration
 
 
7
 
8
  # Define the user usage logs collection
9
  user_usage_collection = db.user_usage # Collection to store assistant usage logs
 
111
  """
112
  result = user_usage_collection.delete_one({"_id": ObjectId(log_id)})
113
  return result.deleted_count > 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/schemas/health_schema.py CHANGED
@@ -1,11 +1,8 @@
1
  # models/schemas/health_schema.py
2
 
3
- from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
6
-
7
- # MongoDB connection (move to config/db.py and import here)
8
- from config.db import db
9
 
10
  # Define the health collection
11
  health_collection = db.health # Collection to store poultry health records
@@ -118,23 +115,3 @@ def delete_health_record(record_id):
118
  """
119
  result = health_collection.delete_one({"_id": ObjectId(record_id)})
120
  return result.deleted_count > 0
121
-
122
-
123
- # Example function to create a sample health record
124
- if __name__ == "__main__":
125
- # Insert a test health record
126
- test_user_id = "610c5e8a85f0b2a4e0b8b918" # Replace with a valid user ObjectId
127
- test_poultry_id = "poultry123"
128
- test_disease_name = "Coccidiosis"
129
- test_status = "Critical"
130
- test_recommendation = "Panadol"
131
-
132
- record_id = create_health_record(
133
- user_id=test_user_id,
134
- poultry_id=test_poultry_id,
135
- disease_name=test_disease_name,
136
- status=test_status,
137
- recommendation=test_recommendation
138
- )
139
-
140
- print(f"Health record created with ID: {record_id}")
 
1
  # models/schemas/health_schema.py
2
 
 
3
  from bson.objectid import ObjectId
4
  import datetime
5
+ from config.db import db # MongoDB connection from configuration
 
 
6
 
7
  # Define the health collection
8
  health_collection = db.health # Collection to store poultry health records
 
115
  """
116
  result = health_collection.delete_one({"_id": ObjectId(record_id)})
117
  return result.deleted_count > 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/schemas/inventory_schema.py CHANGED
@@ -1,12 +1,9 @@
1
  # models/schemas/inventory_schema.py
2
 
3
 
4
- from pymongo import MongoClient
5
  from bson.objectid import ObjectId
6
  import datetime
7
-
8
- # MongoDB connection (move to config/db.py and import here)
9
- from config.db import db
10
 
11
  # Define the inventory collection
12
  inventory_collection = db.inventory # Collection to store inventory items
@@ -126,24 +123,3 @@ def delete_inventory_item(item_id):
126
  """
127
  result = inventory_collection.delete_one({"_id": ObjectId(item_id)})
128
  return result.deleted_count > 0
129
-
130
-
131
- # Example function to create a sample inventory item
132
- if __name__ == "__main__":
133
- # Insert a test inventory item
134
- test_item_name = "Chicken Feed"
135
- test_category = "Feed"
136
- test_quantity = 1000 # 1000 kg
137
- test_unit = "kg"
138
- test_added_by = "610c5e8a85f0b2a4e0b8b918" # Replace with a valid user ObjectId
139
-
140
- item_id = create_inventory_item(
141
- item_name=test_item_name,
142
- category=test_category,
143
- quantity=test_quantity,
144
- unit=test_unit,
145
- added_by=test_added_by,
146
- description="Premium feed for broiler chickens"
147
- )
148
-
149
- print(f"Inventory item created with ID: {item_id}")
 
1
  # models/schemas/inventory_schema.py
2
 
3
 
 
4
  from bson.objectid import ObjectId
5
  import datetime
6
+ from config.db import db # MongoDB connection from configuration
 
 
7
 
8
  # Define the inventory collection
9
  inventory_collection = db.inventory # Collection to store inventory items
 
123
  """
124
  result = inventory_collection.delete_one({"_id": ObjectId(item_id)})
125
  return result.deleted_count > 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/schemas/log_schema.py CHANGED
@@ -1,17 +1,15 @@
1
  # models/schemas/log_schema.py
2
 
3
 
4
- from pymongo import MongoClient, IndexModel, ASCENDING
5
  from bson.objectid import ObjectId
6
  import datetime
7
-
8
- # MongoDB connection (move to config/db.py and import here)
9
- from config.db import db
10
 
11
  # Define the logs collection
12
  logs_collection = db.logs # Collection to store system logs
13
 
14
- # TTL index to expire documents after 30 days
15
  logs_collection.create_index([("timestamp", ASCENDING)], expireAfterSeconds=30 * 24 * 60 * 60)
16
 
17
 
@@ -110,23 +108,3 @@ def delete_old_logs():
110
  """
111
  # No manual deletion needed as MongoDB TTL will automatically handle the deletion.
112
  pass
113
-
114
-
115
- # Example function to create a sample log
116
- if __name__ == "__main__":
117
- # Insert a test log record
118
- test_level = "ERROR"
119
- test_message = "An error occurred in the system."
120
- test_metadata = {"stack_trace": "Traceback (most recent call last): ..."}
121
- test_ip_address = "192.168.1.1"
122
- test_user_id = "610c5e8a85f0b2a4e0b8b918" # Replace with a valid user ObjectId
123
-
124
- log_id = create_log(
125
- level=test_level,
126
- message=test_message,
127
- metadata=test_metadata,
128
- ip_address=test_ip_address,
129
- user_id=test_user_id
130
- )
131
-
132
- print(f"Log record created with ID: {log_id}")
 
1
  # models/schemas/log_schema.py
2
 
3
 
 
4
  from bson.objectid import ObjectId
5
  import datetime
6
+ from pymongo import ASCENDING
7
+ from config.db import db # Import MongoDB connection from config
 
8
 
9
  # Define the logs collection
10
  logs_collection = db.logs # Collection to store system logs
11
 
12
+ # Create a TTL index to expire documents after 30 days
13
  logs_collection.create_index([("timestamp", ASCENDING)], expireAfterSeconds=30 * 24 * 60 * 60)
14
 
15
 
 
108
  """
109
  # No manual deletion needed as MongoDB TTL will automatically handle the deletion.
110
  pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
models/schemas/usage_schema.py CHANGED
@@ -1,12 +1,9 @@
1
  # models/schemas/usage_schema.py
2
 
3
 
4
- from pymongo import MongoClient
5
  from bson.objectid import ObjectId
6
  import datetime
7
-
8
- # MongoDB connection (move to config/db.py and import here)
9
- from config.db import db
10
 
11
  # Define the usage collection
12
  usage_collection = db.usage # Collection to store assistant usage records
@@ -104,21 +101,3 @@ def delete_usage_record(record_id):
104
  """
105
  result = usage_collection.delete_one({"_id": ObjectId(record_id)})
106
  return result.deleted_count > 0
107
-
108
-
109
- # Example function to create a sample usage record
110
- if __name__ == "__main__":
111
- # Insert a test usage record
112
- test_user_id = "610c5e8a85f0b2a4e0b8b918" # Replace with a valid user ObjectId
113
- test_manager_id = "610c5e8a85f0b2a4e0b8b919" # Replace with a valid manager ObjectId
114
- test_interaction_type = "disease_detection"
115
- test_metadata = {"disease_name": "Coccidiosis", "detected": True}
116
-
117
- record_id = create_usage_record(
118
- user_id=test_user_id,
119
- manager_id=test_manager_id,
120
- interaction_type=test_interaction_type,
121
- metadata=test_metadata
122
- )
123
-
124
- print(f"Usage record created with ID: {record_id}")
 
1
  # models/schemas/usage_schema.py
2
 
3
 
 
4
  from bson.objectid import ObjectId
5
  import datetime
6
+ from config.db import db # Import MongoDB connection from config
 
 
7
 
8
  # Define the usage collection
9
  usage_collection = db.usage # Collection to store assistant usage records
 
101
  """
102
  result = usage_collection.delete_one({"_id": ObjectId(record_id)})
103
  return result.deleted_count > 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
routes/api.py CHANGED
@@ -10,153 +10,58 @@ from controllers.data_logging import log_user_action
10
  # Create a Blueprint for the API routes
11
  api_bp = Blueprint('api', __name__)
12
 
13
-
14
  # Health Management Routes
15
  @api_bp.route('/detect-disease', methods=['POST'])
16
  def detect_disease_route():
17
- """
18
- Route for detecting a disease and logging the health record.
19
- Expects a POST request with:
20
- - user_id: ID of the user.
21
- - poultry_id: ID of the poultry.
22
- - image: The image of poultry feces for disease detection.
23
-
24
- Returns: JSON response with disease detection results and log status.
25
- """
26
  return detect_and_log_disease()
27
 
28
-
29
  @api_bp.route('/health-record/<record_id>', methods=['GET'])
30
  def get_health_record_route(record_id):
31
- """
32
- Route for retrieving a health record by its ID.
33
-
34
- Returns: JSON response with the health record details.
35
- """
36
  return get_health_record(record_id)
37
 
38
-
39
  @api_bp.route('/health-records/<user_id>', methods=['GET'])
40
  def get_health_records_for_user_route(user_id):
41
- """
42
- Route for retrieving all health records for a specific user.
43
-
44
- Returns: JSON response with the list of health records.
45
- """
46
  return get_health_records_for_user(user_id)
47
 
48
-
49
  # Inventory Management Routes
50
  @api_bp.route('/add-inventory-item', methods=['POST'])
51
  def add_inventory_item_route():
52
- """
53
- Route for adding a new inventory item.
54
- Expects a POST request with:
55
- - user_id: ID of the user.
56
- - item_name: Name of the item.
57
- - category: Category of the item.
58
- - quantity: Quantity of the item.
59
- - unit: Unit of measurement.
60
-
61
- Returns: JSON response with the item addition status.
62
- """
63
  return add_inventory_item()
64
 
65
-
66
  @api_bp.route('/update-inventory-item', methods=['PUT'])
67
  def update_inventory_item_route():
68
- """
69
- Route for updating an inventory item.
70
- Expects a PUT request with:
71
- - user_id: ID of the user.
72
- - item_id: ID of the inventory item to update.
73
- - updated_fields: Fields to update (e.g., quantity, used_quantity).
74
-
75
- Returns: JSON response with the item update status.
76
- """
77
  return update_inventory_item_by_id()
78
 
79
-
80
  @api_bp.route('/inventory-item/<item_id>', methods=['GET'])
81
  def get_inventory_item_route(item_id):
82
- """
83
- Route for retrieving an inventory item by its ID.
84
-
85
- Returns: JSON response with the inventory item details.
86
- """
87
  return get_inventory_by_id(item_id)
88
 
89
-
90
  @api_bp.route('/inventory', methods=['GET'])
91
  def get_all_inventory_route():
92
- """
93
- Route for retrieving all inventory items.
94
-
95
- Returns: JSON response with the list of all inventory items.
96
- """
97
  return get_all_inventory()
98
 
99
-
100
  # Assistant Usage Tracking Routes
101
  @api_bp.route('/log-usage', methods=['POST'])
102
  def log_usage_route():
103
- """
104
- Route for logging the usage of the assistant by a user.
105
- Expects a POST request with:
106
- - user_id: ID of the user.
107
- - manager_id: ID of the manager.
108
- - interaction_type: The type of interaction.
109
-
110
- Returns: JSON response with the log status.
111
- """
112
  return log_usage()
113
 
114
-
115
  @api_bp.route('/usage/<user_id>', methods=['GET'])
116
  def get_usage_for_user_route(user_id):
117
- """
118
- Route for retrieving all usage logs for a specific user.
119
-
120
- Returns: JSON response with the list of usage logs for the user.
121
- """
122
  return get_usage_for_user(user_id)
123
 
124
-
125
  @api_bp.route('/manager-usage/<manager_id>', methods=['GET'])
126
  def get_usage_for_manager_route(manager_id):
127
- """
128
- Route for retrieving all usage logs for users managed by a specific manager.
129
-
130
- Returns: JSON response with the list of usage logs for the manager's users.
131
- """
132
  return get_usage_for_manager(manager_id)
133
 
134
-
135
  @api_bp.route('/usage-type/<interaction_type>', methods=['GET'])
136
  def get_usage_by_type_route(interaction_type):
137
- """
138
- Route for retrieving all usage logs for a specific interaction type.
139
-
140
- Returns: JSON response with the list of usage logs for the interaction type.
141
- """
142
  return get_usage_by_type(interaction_type)
143
 
144
-
145
  # User Action Logging Route
146
  @api_bp.route('/log-user-action', methods=['POST'])
147
  def log_user_action_route():
148
- """
149
- Route for logging general user actions.
150
- Expects a POST request with:
151
- - user_id: ID of the user performing the action.
152
- - message: Description of the action.
153
- - level: Logging level (default is "INFO").
154
-
155
- Returns: JSON response with the log status.
156
- """
157
  user_id = request.json.get('user_id')
158
  message = request.json.get('message')
159
  level = request.json.get('level', 'INFO')
160
  metadata = request.json.get('metadata', {})
161
-
162
  return log_user_action(user_id, message, level, metadata)
 
10
  # Create a Blueprint for the API routes
11
  api_bp = Blueprint('api', __name__)
12
 
 
13
  # Health Management Routes
14
  @api_bp.route('/detect-disease', methods=['POST'])
15
  def detect_disease_route():
 
 
 
 
 
 
 
 
 
16
  return detect_and_log_disease()
17
 
 
18
  @api_bp.route('/health-record/<record_id>', methods=['GET'])
19
  def get_health_record_route(record_id):
 
 
 
 
 
20
  return get_health_record(record_id)
21
 
 
22
  @api_bp.route('/health-records/<user_id>', methods=['GET'])
23
  def get_health_records_for_user_route(user_id):
 
 
 
 
 
24
  return get_health_records_for_user(user_id)
25
 
 
26
  # Inventory Management Routes
27
  @api_bp.route('/add-inventory-item', methods=['POST'])
28
  def add_inventory_item_route():
 
 
 
 
 
 
 
 
 
 
 
29
  return add_inventory_item()
30
 
 
31
  @api_bp.route('/update-inventory-item', methods=['PUT'])
32
  def update_inventory_item_route():
 
 
 
 
 
 
 
 
 
33
  return update_inventory_item_by_id()
34
 
 
35
  @api_bp.route('/inventory-item/<item_id>', methods=['GET'])
36
  def get_inventory_item_route(item_id):
 
 
 
 
 
37
  return get_inventory_by_id(item_id)
38
 
 
39
  @api_bp.route('/inventory', methods=['GET'])
40
  def get_all_inventory_route():
 
 
 
 
 
41
  return get_all_inventory()
42
 
 
43
  # Assistant Usage Tracking Routes
44
  @api_bp.route('/log-usage', methods=['POST'])
45
  def log_usage_route():
 
 
 
 
 
 
 
 
 
46
  return log_usage()
47
 
 
48
  @api_bp.route('/usage/<user_id>', methods=['GET'])
49
  def get_usage_for_user_route(user_id):
 
 
 
 
 
50
  return get_usage_for_user(user_id)
51
 
 
52
  @api_bp.route('/manager-usage/<manager_id>', methods=['GET'])
53
  def get_usage_for_manager_route(manager_id):
 
 
 
 
 
54
  return get_usage_for_manager(manager_id)
55
 
 
56
  @api_bp.route('/usage-type/<interaction_type>', methods=['GET'])
57
  def get_usage_by_type_route(interaction_type):
 
 
 
 
 
58
  return get_usage_by_type(interaction_type)
59
 
 
60
  # User Action Logging Route
61
  @api_bp.route('/log-user-action', methods=['POST'])
62
  def log_user_action_route():
 
 
 
 
 
 
 
 
 
63
  user_id = request.json.get('user_id')
64
  message = request.json.get('message')
65
  level = request.json.get('level', 'INFO')
66
  metadata = request.json.get('metadata', {})
 
67
  return log_user_action(user_id, message, level, metadata)
routes/data_logging_routes.py CHANGED
@@ -2,27 +2,20 @@
2
 
3
 
4
  from flask import Blueprint, request, jsonify
5
- from controllers.data_logging import log_user_action, log_health_record, log_inventory_addition, log_inventory_update, \
 
 
 
 
6
  log_assistant_usage
 
7
 
8
  # Create a Blueprint for the data logging routes
9
  data_logging_bp = Blueprint('data_logging', __name__)
10
 
11
-
12
  # Route to log user actions
13
  @data_logging_bp.route('/log-user-action', methods=['POST'])
14
  def log_user_action_route():
15
- """
16
- Logs a general user action.
17
-
18
- Expects a POST request with:
19
- - user_id: ID of the user performing the action.
20
- - message: Description of the action.
21
- - level: Logging level (default is "INFO").
22
- - metadata: Optional. Additional metadata related to the action.
23
-
24
- Returns: JSON response indicating success or failure.
25
- """
26
  try:
27
  user_id = request.json.get('user_id')
28
  message = request.json.get('message')
@@ -33,7 +26,6 @@ def log_user_action_route():
33
  return jsonify({"error": "Missing required fields"}), 400
34
 
35
  return log_user_action(user_id, message, level, metadata)
36
-
37
  except Exception as e:
38
  return jsonify({"error": str(e)}), 500
39
 
@@ -41,19 +33,6 @@ def log_user_action_route():
41
  # Route to log a health record
42
  @data_logging_bp.route('/log-health-record', methods=['POST'])
43
  def log_health_record_route():
44
- """
45
- Logs a health record for poultry.
46
-
47
- Expects a POST request with:
48
- - user_id: ID of the user submitting the record.
49
- - poultry_id: The ID of the poultry.
50
- - disease_name: Name of the detected disease.
51
- - status: The health status of the poultry.
52
- - recommendation: Recommended treatment.
53
- - image_path: Optional. Path to an image related to the health record.
54
-
55
- Returns: JSON response indicating success or failure.
56
- """
57
  try:
58
  user_id = request.json.get('user_id')
59
  poultry_id = request.json.get('poultry_id')
@@ -62,11 +41,10 @@ def log_health_record_route():
62
  recommendation = request.json.get('recommendation')
63
  image_path = request.json.get('image_path')
64
 
65
- if not user_id or not poultry_id or not disease_name or not status or not recommendation:
66
  return jsonify({"error": "Missing required fields"}), 400
67
 
68
  return log_health_record(user_id, poultry_id, disease_name, status, recommendation, image_path)
69
-
70
  except Exception as e:
71
  return jsonify({"error": str(e)}), 500
72
 
@@ -74,19 +52,6 @@ def log_health_record_route():
74
  # Route to log inventory addition
75
  @data_logging_bp.route('/log-inventory-addition', methods=['POST'])
76
  def log_inventory_addition_route():
77
- """
78
- Logs the addition of an inventory item.
79
-
80
- Expects a POST request with:
81
- - user_id: ID of the user adding the item.
82
- - item_name: Name of the inventory item.
83
- - category: Category of the item (e.g., "Feed", "Medicine").
84
- - quantity: Total quantity added.
85
- - unit: Unit of measurement (e.g., "kg", "liters").
86
- - description: Optional. Additional description or notes.
87
-
88
- Returns: JSON response indicating success or failure.
89
- """
90
  try:
91
  user_id = request.json.get('user_id')
92
  item_name = request.json.get('item_name')
@@ -95,11 +60,10 @@ def log_inventory_addition_route():
95
  unit = request.json.get('unit')
96
  description = request.json.get('description')
97
 
98
- if not user_id or not item_name or not category or not quantity or not unit:
99
  return jsonify({"error": "Missing required fields"}), 400
100
 
101
  return log_inventory_addition(user_id, item_name, category, quantity, unit, description)
102
-
103
  except Exception as e:
104
  return jsonify({"error": str(e)}), 500
105
 
@@ -107,26 +71,15 @@ def log_inventory_addition_route():
107
  # Route to log inventory update
108
  @data_logging_bp.route('/log-inventory-update', methods=['PUT'])
109
  def log_inventory_update_route():
110
- """
111
- Logs an update to an existing inventory item.
112
-
113
- Expects a PUT request with:
114
- - user_id: ID of the user updating the item.
115
- - item_id: ID of the inventory item being updated.
116
- - updated_fields: Fields being updated (e.g., "quantity", "used_quantity").
117
-
118
- Returns: JSON response indicating success or failure.
119
- """
120
  try:
121
  user_id = request.json.get('user_id')
122
  item_id = request.json.get('item_id')
123
  updated_fields = request.json.get('updated_fields')
124
 
125
- if not user_id or not item_id or not updated_fields:
126
  return jsonify({"error": "Missing required fields"}), 400
127
 
128
  return log_inventory_update(user_id, item_id, updated_fields)
129
-
130
  except Exception as e:
131
  return jsonify({"error": str(e)}), 500
132
 
@@ -134,27 +87,15 @@ def log_inventory_update_route():
134
  # Route to log assistant usage
135
  @data_logging_bp.route('/log-assistant-usage', methods=['POST'])
136
  def log_assistant_usage_route():
137
- """
138
- Logs the usage of the assistant by a user.
139
-
140
- Expects a POST request with:
141
- - user_id: ID of the user.
142
- - manager_id: ID of the manager overseeing the user.
143
- - interaction_type: The type of interaction (e.g., "disease_detection", "inventory_management").
144
- - metadata: Optional. Additional details about the interaction.
145
-
146
- Returns: JSON response indicating success or failure.
147
- """
148
  try:
149
  user_id = request.json.get('user_id')
150
  manager_id = request.json.get('manager_id')
151
  interaction_type = request.json.get('interaction_type')
152
  metadata = request.json.get('metadata')
153
 
154
- if not user_id or not manager_id or not interaction_type:
155
  return jsonify({"error": "Missing required fields"}), 400
156
 
157
  return log_assistant_usage(user_id, manager_id, interaction_type, metadata)
158
-
159
  except Exception as e:
160
  return jsonify({"error": str(e)}), 500
 
2
 
3
 
4
  from flask import Blueprint, request, jsonify
5
+ from controllers.data_logging import (
6
+ log_user_action,
7
+ log_health_record,
8
+ log_inventory_addition,
9
+ log_inventory_update,
10
  log_assistant_usage
11
+ )
12
 
13
  # Create a Blueprint for the data logging routes
14
  data_logging_bp = Blueprint('data_logging', __name__)
15
 
 
16
  # Route to log user actions
17
  @data_logging_bp.route('/log-user-action', methods=['POST'])
18
  def log_user_action_route():
 
 
 
 
 
 
 
 
 
 
 
19
  try:
20
  user_id = request.json.get('user_id')
21
  message = request.json.get('message')
 
26
  return jsonify({"error": "Missing required fields"}), 400
27
 
28
  return log_user_action(user_id, message, level, metadata)
 
29
  except Exception as e:
30
  return jsonify({"error": str(e)}), 500
31
 
 
33
  # Route to log a health record
34
  @data_logging_bp.route('/log-health-record', methods=['POST'])
35
  def log_health_record_route():
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  try:
37
  user_id = request.json.get('user_id')
38
  poultry_id = request.json.get('poultry_id')
 
41
  recommendation = request.json.get('recommendation')
42
  image_path = request.json.get('image_path')
43
 
44
+ if not all([user_id, poultry_id, disease_name, status, recommendation]):
45
  return jsonify({"error": "Missing required fields"}), 400
46
 
47
  return log_health_record(user_id, poultry_id, disease_name, status, recommendation, image_path)
 
48
  except Exception as e:
49
  return jsonify({"error": str(e)}), 500
50
 
 
52
  # Route to log inventory addition
53
  @data_logging_bp.route('/log-inventory-addition', methods=['POST'])
54
  def log_inventory_addition_route():
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  try:
56
  user_id = request.json.get('user_id')
57
  item_name = request.json.get('item_name')
 
60
  unit = request.json.get('unit')
61
  description = request.json.get('description')
62
 
63
+ if not all([user_id, item_name, category, quantity, unit]):
64
  return jsonify({"error": "Missing required fields"}), 400
65
 
66
  return log_inventory_addition(user_id, item_name, category, quantity, unit, description)
 
67
  except Exception as e:
68
  return jsonify({"error": str(e)}), 500
69
 
 
71
  # Route to log inventory update
72
  @data_logging_bp.route('/log-inventory-update', methods=['PUT'])
73
  def log_inventory_update_route():
 
 
 
 
 
 
 
 
 
 
74
  try:
75
  user_id = request.json.get('user_id')
76
  item_id = request.json.get('item_id')
77
  updated_fields = request.json.get('updated_fields')
78
 
79
+ if not all([user_id, item_id, updated_fields]):
80
  return jsonify({"error": "Missing required fields"}), 400
81
 
82
  return log_inventory_update(user_id, item_id, updated_fields)
 
83
  except Exception as e:
84
  return jsonify({"error": str(e)}), 500
85
 
 
87
  # Route to log assistant usage
88
  @data_logging_bp.route('/log-assistant-usage', methods=['POST'])
89
  def log_assistant_usage_route():
 
 
 
 
 
 
 
 
 
 
 
90
  try:
91
  user_id = request.json.get('user_id')
92
  manager_id = request.json.get('manager_id')
93
  interaction_type = request.json.get('interaction_type')
94
  metadata = request.json.get('metadata')
95
 
96
+ if not all([user_id, manager_id, interaction_type]):
97
  return jsonify({"error": "Missing required fields"}), 400
98
 
99
  return log_assistant_usage(user_id, manager_id, interaction_type, metadata)
 
100
  except Exception as e:
101
  return jsonify({"error": str(e)}), 500
routes/health_routes.py CHANGED
@@ -1,23 +1,20 @@
1
  # routes/health_routes.py
2
 
3
- from flask import Blueprint, request, jsonify
4
  from controllers.health_management import detect_and_log_disease, get_health_record, get_health_records_for_user
5
 
6
  # Create a Blueprint for the health-related routes
7
  health_bp = Blueprint('health', __name__)
8
 
9
-
10
  # Route to detect disease and log the health record
11
  @health_bp.route('/detect-disease', methods=['POST'])
12
  def detect_disease_route():
13
  """
14
  Detect a poultry disease and log the health record.
15
-
16
  Expects a POST request with the following fields:
17
  - user_id: ID of the user.
18
  - poultry_id: ID of the poultry.
19
  - image: Image of poultry feces for disease detection.
20
-
21
  Returns: JSON response with disease detection result and health record log status.
22
  """
23
  try:
@@ -31,9 +28,6 @@ def detect_disease_route():
31
  def get_health_record_route(record_id):
32
  """
33
  Retrieve a health record by its ID.
34
-
35
- Expects a GET request with the health record ID in the URL.
36
-
37
  Returns: JSON response with the health record details.
38
  """
39
  try:
@@ -47,9 +41,6 @@ def get_health_record_route(record_id):
47
  def get_health_records_for_user_route(user_id):
48
  """
49
  Retrieve all health records for a specific user.
50
-
51
- Expects a GET request with the user ID in the URL.
52
-
53
  Returns: JSON response with the list of health records for the user.
54
  """
55
  try:
 
1
  # routes/health_routes.py
2
 
3
+ from flask import Blueprint, jsonify
4
  from controllers.health_management import detect_and_log_disease, get_health_record, get_health_records_for_user
5
 
6
  # Create a Blueprint for the health-related routes
7
  health_bp = Blueprint('health', __name__)
8
 
 
9
  # Route to detect disease and log the health record
10
  @health_bp.route('/detect-disease', methods=['POST'])
11
  def detect_disease_route():
12
  """
13
  Detect a poultry disease and log the health record.
 
14
  Expects a POST request with the following fields:
15
  - user_id: ID of the user.
16
  - poultry_id: ID of the poultry.
17
  - image: Image of poultry feces for disease detection.
 
18
  Returns: JSON response with disease detection result and health record log status.
19
  """
20
  try:
 
28
  def get_health_record_route(record_id):
29
  """
30
  Retrieve a health record by its ID.
 
 
 
31
  Returns: JSON response with the health record details.
32
  """
33
  try:
 
41
  def get_health_records_for_user_route(user_id):
42
  """
43
  Retrieve all health records for a specific user.
 
 
 
44
  Returns: JSON response with the list of health records for the user.
45
  """
46
  try:
routes/inventory_routes.py CHANGED
@@ -1,20 +1,22 @@
1
  # routes/inventory_routes.py
2
 
3
 
4
- from flask import Blueprint, request, jsonify
5
- from controllers.inventory import add_inventory_item, update_inventory_item_by_id, get_inventory_by_id, \
 
 
 
6
  get_all_inventory
 
7
 
8
  # Create a Blueprint for the inventory-related routes
9
  inventory_bp = Blueprint('inventory', __name__)
10
 
11
-
12
  # Route to add a new inventory item
13
  @inventory_bp.route('/add-inventory-item', methods=['POST'])
14
  def add_inventory_item_route():
15
  """
16
  Add a new inventory item to the system.
17
-
18
  Expects a POST request with the following fields:
19
  - user_id: The ID of the user adding the item.
20
  - item_name: The name of the inventory item.
@@ -22,7 +24,6 @@ def add_inventory_item_route():
22
  - quantity: The total quantity of the item.
23
  - unit: The unit of measurement (e.g., "kg", "liters").
24
  - description: Optional. Additional description or notes about the item.
25
-
26
  Returns: JSON response with the status of the addition.
27
  """
28
  try:
@@ -36,12 +37,10 @@ def add_inventory_item_route():
36
  def update_inventory_item_route():
37
  """
38
  Update an existing inventory item in the system.
39
-
40
  Expects a PUT request with the following fields:
41
  - user_id: The ID of the user updating the item.
42
  - item_id: The ID of the inventory item to be updated.
43
  - updated_fields: Dictionary containing fields to be updated (e.g., quantity, used_quantity).
44
-
45
  Returns: JSON response with the status of the update.
46
  """
47
  try:
@@ -55,9 +54,7 @@ def update_inventory_item_route():
55
  def get_inventory_item_route(item_id):
56
  """
57
  Retrieve an inventory item by its ID.
58
-
59
  Expects a GET request with the item_id as a URL parameter.
60
-
61
  Returns: JSON response with the inventory item details.
62
  """
63
  try:
@@ -71,7 +68,6 @@ def get_inventory_item_route(item_id):
71
  def get_all_inventory_route():
72
  """
73
  Retrieve all inventory items in the system.
74
-
75
  Returns: JSON response with the list of all inventory items.
76
  """
77
  try:
 
1
  # routes/inventory_routes.py
2
 
3
 
4
+ from flask import Blueprint, jsonify
5
+ from controllers.inventory import (
6
+ add_inventory_item,
7
+ update_inventory_item_by_id,
8
+ get_inventory_by_id,
9
  get_all_inventory
10
+ )
11
 
12
  # Create a Blueprint for the inventory-related routes
13
  inventory_bp = Blueprint('inventory', __name__)
14
 
 
15
  # Route to add a new inventory item
16
  @inventory_bp.route('/add-inventory-item', methods=['POST'])
17
  def add_inventory_item_route():
18
  """
19
  Add a new inventory item to the system.
 
20
  Expects a POST request with the following fields:
21
  - user_id: The ID of the user adding the item.
22
  - item_name: The name of the inventory item.
 
24
  - quantity: The total quantity of the item.
25
  - unit: The unit of measurement (e.g., "kg", "liters").
26
  - description: Optional. Additional description or notes about the item.
 
27
  Returns: JSON response with the status of the addition.
28
  """
29
  try:
 
37
  def update_inventory_item_route():
38
  """
39
  Update an existing inventory item in the system.
 
40
  Expects a PUT request with the following fields:
41
  - user_id: The ID of the user updating the item.
42
  - item_id: The ID of the inventory item to be updated.
43
  - updated_fields: Dictionary containing fields to be updated (e.g., quantity, used_quantity).
 
44
  Returns: JSON response with the status of the update.
45
  """
46
  try:
 
54
  def get_inventory_item_route(item_id):
55
  """
56
  Retrieve an inventory item by its ID.
 
57
  Expects a GET request with the item_id as a URL parameter.
 
58
  Returns: JSON response with the inventory item details.
59
  """
60
  try:
 
68
  def get_all_inventory_route():
69
  """
70
  Retrieve all inventory items in the system.
 
71
  Returns: JSON response with the list of all inventory items.
72
  """
73
  try:
routes/usage_routes.py CHANGED
@@ -1,6 +1,6 @@
1
  # routes/usage_routes.py
2
 
3
- from flask import Blueprint, request, jsonify
4
  from controllers.usage_tracking import log_usage, get_usage_for_user, get_usage_for_manager, get_usage_by_type
5
 
6
  # Create a Blueprint for the usage-related routes
@@ -13,11 +13,11 @@ def log_usage_route():
13
  """
14
  Logs the usage of the assistant by a user.
15
 
16
- Expects a POST request with the following fields:
17
  - user_id: The ID of the user interacting with the assistant.
18
  - manager_id: The ID of the user's manager.
19
  - interaction_type: The type of interaction (e.g., "disease_detection", "inventory_management").
20
- - metadata: Optional. Additional details about the interaction (e.g., query details or results).
21
 
22
  Returns: JSON response indicating success or failure.
23
  """
 
1
  # routes/usage_routes.py
2
 
3
+ from flask import Blueprint, jsonify
4
  from controllers.usage_tracking import log_usage, get_usage_for_user, get_usage_for_manager, get_usage_by_type
5
 
6
  # Create a Blueprint for the usage-related routes
 
13
  """
14
  Logs the usage of the assistant by a user.
15
 
16
+ Expects a POST request with:
17
  - user_id: The ID of the user interacting with the assistant.
18
  - manager_id: The ID of the user's manager.
19
  - interaction_type: The type of interaction (e.g., "disease_detection", "inventory_management").
20
+ - metadata: Optional. Additional details about the interaction.
21
 
22
  Returns: JSON response indicating success or failure.
23
  """
services/disease_detection.py CHANGED
@@ -4,34 +4,67 @@ import cv2
4
  import numpy as np
5
  from keras.models import load_model
6
 
7
- # Load the model (ensure the path is correct)
8
  my_model = load_model('models/Final_Chicken_disease_model.h5')
9
 
10
- # Disease names and recommendations
11
  name_disease = {0: 'Coccidiosis', 1: 'Healthy', 2: 'New Castle Disease', 3: 'Salmonella'}
12
  result = {0: 'Critical', 1: 'No issue', 2: 'Critical', 3: 'Critical'}
13
- recommend = {0: 'Panadol', 1: 'You have no need Medicine', 2: 'Percetamol', 3: 'Ponston'}
 
 
 
 
 
14
 
15
 
16
  class PoultryFarmBot:
17
  def __init__(self, db):
18
- self.db = db # MongoDB database for future use
 
 
 
 
19
 
20
  def preprocess_image(self, image):
 
 
 
 
 
 
 
21
  try:
22
- image_check = cv2.resize(image, (224, 224))
23
- image_check = np.expand_dims(image_check, axis=0)
24
  return image_check
25
  except Exception as e:
26
  print(f"Error in image preprocessing: {e}")
27
  return None
28
 
29
  def predict(self, image):
 
 
 
 
 
 
 
30
  image_check = self.preprocess_image(image)
 
31
  if image_check is None:
32
  return "Image preprocessing failed.", None, None, None
33
- indx = my_model.predict(image_check).argmax()
34
- name = name_disease.get(indx, "Unknown disease")
35
- status = result.get(indx, "unknown condition")
36
- recom = recommend.get(indx, "no recommendation available")
37
- return name, status, recom
 
 
 
 
 
 
 
 
 
 
4
  import numpy as np
5
  from keras.models import load_model
6
 
7
+ # Load the model (ensure the model path is correct)
8
  my_model = load_model('models/Final_Chicken_disease_model.h5')
9
 
10
+ # Mapping of disease labels to disease names, health status, and treatment recommendations
11
  name_disease = {0: 'Coccidiosis', 1: 'Healthy', 2: 'New Castle Disease', 3: 'Salmonella'}
12
  result = {0: 'Critical', 1: 'No issue', 2: 'Critical', 3: 'Critical'}
13
+ recommend = {
14
+ 0: 'Panadol', # Treatment for Coccidiosis
15
+ 1: 'You have no need for Medicine', # Healthy case
16
+ 2: 'Percetamol', # Treatment for New Castle Disease
17
+ 3: 'Ponston' # Treatment for Salmonella
18
+ }
19
 
20
 
21
  class PoultryFarmBot:
22
  def __init__(self, db):
23
+ """
24
+ Initializes the PoultryFarmBot with a MongoDB connection.
25
+ :param db: MongoDB connection for future use in logging or storing results.
26
+ """
27
+ self.db = db
28
 
29
  def preprocess_image(self, image):
30
+ """
31
+ Preprocesses the input image for model prediction.
32
+ Resizes the image to 224x224 and expands the dimensions to match the model input format.
33
+
34
+ :param image: Input image (numpy array).
35
+ :return: Preprocessed image ready for prediction or None if an error occurs.
36
+ """
37
  try:
38
+ image_check = cv2.resize(image, (224, 224)) # Resize image
39
+ image_check = np.expand_dims(image_check, axis=0) # Add batch dimension
40
  return image_check
41
  except Exception as e:
42
  print(f"Error in image preprocessing: {e}")
43
  return None
44
 
45
  def predict(self, image):
46
+ """
47
+ Predicts the disease from the input image using the pre-trained model.
48
+
49
+ :param image: Input image (numpy array).
50
+ :return: Tuple of predicted disease name, health status, and treatment recommendation.
51
+ """
52
+ # Preprocess the image
53
  image_check = self.preprocess_image(image)
54
+
55
  if image_check is None:
56
  return "Image preprocessing failed.", None, None, None
57
+
58
+ try:
59
+ # Predict disease using the loaded model
60
+ indx = my_model.predict(image_check).argmax()
61
+
62
+ # Get the disease name, status, and recommended treatment
63
+ name = name_disease.get(indx, "Unknown disease")
64
+ status = result.get(indx, "unknown condition")
65
+ recom = recommend.get(indx, "no recommendation available")
66
+
67
+ return name, status, recom
68
+ except Exception as e:
69
+ print(f"Error during disease prediction: {e}")
70
+ return "Prediction failed.", None, None, None
services/inventory_manager.py CHANGED
@@ -1,7 +1,6 @@
1
  # services/inventory_manager.py
2
 
3
 
4
- from pymongo import MongoClient
5
  from bson.objectid import ObjectId
6
  import datetime
7
 
@@ -12,11 +11,9 @@ from config.db import db
12
  inventory_collection = db.inventory # MongoDB collection to store inventory items
13
 
14
 
15
- # Inventory Management Service
16
-
17
  class InventoryManager:
18
  """
19
- Inventory Manager Service to handle adding, updating, and retrieving inventory items.
20
  """
21
 
22
  def __init__(self):
@@ -32,7 +29,7 @@ class InventoryManager:
32
  :param quantity: The total quantity of the item.
33
  :param unit: The unit of measurement (e.g., "kg", "liters").
34
  :param description: Optional. Additional description or notes about the item.
35
- :return: The inserted inventory item's ID.
36
  """
37
  try:
38
  new_item = {
@@ -60,7 +57,7 @@ class InventoryManager:
60
  :return: Boolean indicating whether the update was successful.
61
  """
62
  try:
63
- updated_fields['updated_at'] = datetime.datetime.utcnow() # Update timestamp
64
  result = self.collection.update_one(
65
  {"_id": ObjectId(item_id)},
66
  {"$set": updated_fields}
@@ -87,14 +84,13 @@ class InventoryManager:
87
  """
88
  Retrieve all inventory items, optionally filtered by user ID.
89
 
90
- :param user_id: Optional. The ID of the user to filter by.
91
  :return: A list of inventory items or an empty list if none are found.
92
  """
93
  try:
94
  if user_id:
95
  return list(self.collection.find({"user_id": ObjectId(user_id)}))
96
- else:
97
- return list(self.collection.find())
98
  except Exception as e:
99
  print(f"Error retrieving inventory items: {e}")
100
  return []
 
1
  # services/inventory_manager.py
2
 
3
 
 
4
  from bson.objectid import ObjectId
5
  import datetime
6
 
 
11
  inventory_collection = db.inventory # MongoDB collection to store inventory items
12
 
13
 
 
 
14
  class InventoryManager:
15
  """
16
+ Inventory Manager Service to handle adding, updating, retrieving, and deleting inventory items.
17
  """
18
 
19
  def __init__(self):
 
29
  :param quantity: The total quantity of the item.
30
  :param unit: The unit of measurement (e.g., "kg", "liters").
31
  :param description: Optional. Additional description or notes about the item.
32
+ :return: The inserted inventory item's ID or None if there's an error.
33
  """
34
  try:
35
  new_item = {
 
57
  :return: Boolean indicating whether the update was successful.
58
  """
59
  try:
60
+ updated_fields['updated_at'] = datetime.datetime.utcnow() # Update the timestamp
61
  result = self.collection.update_one(
62
  {"_id": ObjectId(item_id)},
63
  {"$set": updated_fields}
 
84
  """
85
  Retrieve all inventory items, optionally filtered by user ID.
86
 
87
+ :param user_id: Optional. The ID of the user to filter the results by.
88
  :return: A list of inventory items or an empty list if none are found.
89
  """
90
  try:
91
  if user_id:
92
  return list(self.collection.find({"user_id": ObjectId(user_id)}))
93
+ return list(self.collection.find())
 
94
  except Exception as e:
95
  print(f"Error retrieving inventory items: {e}")
96
  return []
services/llama_service.py CHANGED
@@ -3,28 +3,39 @@
3
 
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
 
6
- # Load Llama 3.2 model and tokenizer for text generation
7
  model_name = "meta-llama/Llama-3.2-1B"
8
  tokenizer = AutoTokenizer.from_pretrained(model_name)
9
  model = AutoModelForCausalLM.from_pretrained(model_name)
10
 
11
- # Set the padding token to EOS token or add a new padding token
12
  if tokenizer.pad_token is None:
13
  tokenizer.add_special_tokens({'pad_token': '[PAD]'})
14
  model.resize_token_embeddings(len(tokenizer))
15
 
16
 
17
  def llama2_response(user_input):
 
 
 
 
 
 
18
  try:
 
19
  inputs = tokenizer(user_input, return_tensors="pt", truncation=True, max_length=150, padding=True)
 
 
20
  outputs = model.generate(
21
  inputs["input_ids"],
22
- max_length=150,
23
- do_sample=True,
24
- temperature=0.7,
25
- pad_token_id=tokenizer.pad_token_id,
26
- attention_mask=inputs["attention_mask"]
27
  )
 
 
28
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
29
  return response
30
  except Exception as e:
 
3
 
4
  from transformers import AutoModelForCausalLM, AutoTokenizer
5
 
6
+ # Load Llama model and tokenizer for text generation
7
  model_name = "meta-llama/Llama-3.2-1B"
8
  tokenizer = AutoTokenizer.from_pretrained(model_name)
9
  model = AutoModelForCausalLM.from_pretrained(model_name)
10
 
11
+ # Ensure the tokenizer has a padding token; if not, add a new padding token
12
  if tokenizer.pad_token is None:
13
  tokenizer.add_special_tokens({'pad_token': '[PAD]'})
14
  model.resize_token_embeddings(len(tokenizer))
15
 
16
 
17
  def llama2_response(user_input):
18
+ """
19
+ Generates a text response using the Llama model based on user input.
20
+
21
+ :param user_input: The input string from the user.
22
+ :return: A generated response string or an error message if something goes wrong.
23
+ """
24
  try:
25
+ # Tokenize the input text, ensuring truncation and padding
26
  inputs = tokenizer(user_input, return_tensors="pt", truncation=True, max_length=150, padding=True)
27
+
28
+ # Generate the model's response
29
  outputs = model.generate(
30
  inputs["input_ids"],
31
+ max_length=150, # Set a reasonable max length for the response
32
+ do_sample=True, # Enable sampling for varied responses
33
+ temperature=0.7, # Control randomness of sampling
34
+ pad_token_id=tokenizer.pad_token_id, # Ensure the use of a valid pad token
35
+ attention_mask=inputs["attention_mask"] # Use attention mask for padded tokens
36
  )
37
+
38
+ # Decode the generated response, skipping special tokens
39
  response = tokenizer.decode(outputs[0], skip_special_tokens=True)
40
  return response
41
  except Exception as e:
services/report_generator.py CHANGED
@@ -1,17 +1,14 @@
1
  # services/report_generator.py
2
 
3
 
4
- from pymongo import MongoClient
5
- from bson.objectid import ObjectId
6
  import pandas as pd
 
7
  import datetime
8
-
9
- # MongoDB Setup (import from your db configuration)
10
  from config.db import db
11
 
12
  # Define collections for report generation
13
  inventory_collection = db.inventory
14
- health_collection = db.health_records
15
  usage_collection = db.user_usage
16
 
17
 
@@ -39,13 +36,9 @@ class ReportGenerator:
39
  if not inventory_items:
40
  return pd.DataFrame([])
41
 
42
- # Convert the MongoDB documents to a pandas DataFrame
43
  df = pd.DataFrame(inventory_items)
44
  df = df.drop(columns=['_id', 'user_id']) # Drop internal fields
45
-
46
- # Add a column for total value (if relevant for future use)
47
- # df['total_value'] = df['quantity'] * df['unit_price']
48
-
49
  return df
50
  except Exception as e:
51
  print(f"Error generating inventory report: {e}")
@@ -65,10 +58,9 @@ class ReportGenerator:
65
  if not health_records:
66
  return pd.DataFrame([])
67
 
68
- # Convert the MongoDB documents to a pandas DataFrame
69
  df = pd.DataFrame(health_records)
70
- df = df.drop(columns=['_id', 'user_id'])
71
-
72
  return df
73
  except Exception as e:
74
  print(f"Error generating health report: {e}")
@@ -97,10 +89,9 @@ class ReportGenerator:
97
  if not usage_records:
98
  return pd.DataFrame([])
99
 
100
- # Convert the MongoDB documents to a pandas DataFrame
101
  df = pd.DataFrame(usage_records)
102
- df = df.drop(columns=['_id', 'user_id', 'manager_id'])
103
-
104
  return df
105
  except Exception as e:
106
  print(f"Error generating usage report: {e}")
 
1
  # services/report_generator.py
2
 
3
 
 
 
4
  import pandas as pd
5
+ from bson.objectid import ObjectId
6
  import datetime
 
 
7
  from config.db import db
8
 
9
  # Define collections for report generation
10
  inventory_collection = db.inventory
11
+ health_collection = db.health
12
  usage_collection = db.user_usage
13
 
14
 
 
36
  if not inventory_items:
37
  return pd.DataFrame([])
38
 
39
+ # Convert MongoDB documents to a pandas DataFrame
40
  df = pd.DataFrame(inventory_items)
41
  df = df.drop(columns=['_id', 'user_id']) # Drop internal fields
 
 
 
 
42
  return df
43
  except Exception as e:
44
  print(f"Error generating inventory report: {e}")
 
58
  if not health_records:
59
  return pd.DataFrame([])
60
 
61
+ # Convert MongoDB documents to a pandas DataFrame
62
  df = pd.DataFrame(health_records)
63
+ df = df.drop(columns=['_id', 'user_id']) # Drop internal fields
 
64
  return df
65
  except Exception as e:
66
  print(f"Error generating health report: {e}")
 
89
  if not usage_records:
90
  return pd.DataFrame([])
91
 
92
+ # Convert MongoDB documents to a pandas DataFrame
93
  df = pd.DataFrame(usage_records)
94
+ df = df.drop(columns=['_id', 'user_id', 'manager_id']) # Drop internal fields
 
95
  return df
96
  except Exception as e:
97
  print(f"Error generating usage report: {e}")
services/usage_tracker.py CHANGED
@@ -3,8 +3,6 @@
3
  from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
6
-
7
- # MongoDB Setup (import from your db configuration)
8
  from config.db import db
9
 
10
  # Define the usage tracking collection
 
3
  from pymongo import MongoClient
4
  from bson.objectid import ObjectId
5
  import datetime
 
 
6
  from config.db import db
7
 
8
  # Define the usage tracking collection
templates/dashboard.html CHANGED
@@ -0,0 +1 @@
 
 
1
+ <!--template/dashboard.html-->
templates/index.html CHANGED
@@ -1,3 +1,4 @@
 
1
  <!DOCTYPE html>
2
  <html dir="ltr" lang="en">
3
  <head>
 
1
+ <!--template/index.html-->
2
  <!DOCTYPE html>
3
  <html dir="ltr" lang="en">
4
  <head>
templates/login.html CHANGED
@@ -0,0 +1 @@
 
 
1
+ <!--template/login.html-->
templates/register.html CHANGED
@@ -0,0 +1 @@
 
 
1
+ <!--template/register.html-->
templates/usage_report.html CHANGED
@@ -0,0 +1 @@
 
 
1
+ <!--template/usage_report.html-->