Commit 6edc119e authored by vaisakh.nair's avatar vaisakh.nair 🎯

Merge branch 'develop_vaisakh' into 'develop'

JK report feature.

See merge request !1
parents f8e51d3c 849661db
MONGO_CLIENT=mongodb://localhost
# MONGO_CLIENT=mongodb://localhost
# MONGO_PORT=2717
# MONGO_DATABASE=admin
# MONGO_COLLECTION=eventLogs
MONGO_CLIENT=mongodb://admin:iLens%241234@192.168.3.181:2717/admin?connectTimeoutMS=10000&authSource=admin&authMechanism=SCRAM-SHA-1
MONGO_PORT=2717
MONGO_DATABASE=admin
MONGO_DATABASE=ilens_ai
MONGO_COLLECTION=eventLogs
\ No newline at end of file
template_file: D:\vision_utilities\vision_utilities\report_generator\templates\daily_report_jk_template.xlsx
# logo_image: path/to/logo.png
cameras:
- camera_name: jk
packer_name: Packer 1
- camera_name: camera_42
packer_name: Packer 2
- camera_name: camera_44
packer_name: Packer 4
- camera_name: camera_45
packer_name: Packer 5
- camera_name: camera_46
packer_name: Packer 6
- camera_name: camera_47
packer_name: Packer 7
import pandas as pd
from pymongo import MongoClient
from datetime import datetime, timedelta
import schedule
import time
import os
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import yaml
from dotenv import load_dotenv
from collections import defaultdict
load_dotenv(dotenv_path='.env')
class DailyReportGenerator:
def __init__(self):
# Connect to MongoDB
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
self.collection = db[os.environ["MONGO_COLLECTION"]]
# Load configuration from config.yml
with open('config.yml') as config_file:
self.config = yaml.safe_load(config_file)
self.template_file = self.config['template_file']
self.camera_mappings = {
item['camera_name']: item['packer_name']
for item in self.config['cameras']
}
def get_shift_name(self, timestamp):
hour = timestamp.hour
if 6 <= hour < 14:
return 'Shift A'
......@@ -21,55 +40,109 @@ class DailyReportGenerator:
else:
return 'Shift C'
def map_packer_name(self, camera_name):
packer_mapping = {
'camera_41': 'Packer 1',
'camera_42': 'Packer 2',
'camera_44': 'Packer 4',
'camera_45': 'Packer 5',
'camera_46': 'Packer 6',
'camera_47': 'Packer 7'
}
return packer_mapping.get(camera_name, 'Unknown')
def get_packer_name(self, camera_name):
return self.camera_mappings.get(camera_name, 'Unknown')
def get_count(self, start_time, end_time, camera_name):
query = {
'timestamp': {'$gte': start_time, '$lte': end_time},
'cameraName': camera_name
}
count = self.collection.count_documents(query)
return count
documents = self.collection.find(query).sort('timestamp', 1)
count_difference = 0
first_count = 0
last_count = 0
for i, document in enumerate(documents):
if i == 0:
first_count = int(document['cement_bag_count'])
last_count = int(document['cement_bag_count'])
count_difference = last_count - first_count
return count_difference
def create_excel_report(self):
data = []
report_file = 'daily_report.xlsx'
current_time = datetime.now()
start_time = datetime(current_time.year, current_time.month, current_time.day - 1, 6, 0, 0)
end_time = datetime(current_time.year, current_time.month, current_time.day, 6, 0, 0)
for camera_name in ['camera_41', 'camera_42', 'camera_44', 'camera_45', 'camera_46', 'camera_47']:
shift_name = self.get_shift_name(start_time)
packer_name = self.map_packer_name(camera_name)
# Calculate the previous day's date
previous_day = current_time - timedelta(days=1)
report_date = previous_day.strftime("%Y-%m-%d")
report_file = f"daily_report_{report_date}.xlsx"
wb = load_workbook(self.template_file)
sheet = wb.active
# Set report date
sheet['L6'] = report_date
serial_number = 1
# Define the shifts and their respective time ranges
shifts = {
'Shift A': (datetime(current_time.year, current_time.month, current_time.day -1 , 6, 0, 0),
datetime(current_time.year, current_time.month, current_time.day -1, 14, 0, 0)),
'Shift B': (datetime(current_time.year, current_time.month, current_time.day -1, 14, 0, 0),
datetime(current_time.year, current_time.month, current_time.day -1, 22, 0, 0)),
'Shift C': (datetime(current_time.year, current_time.month, current_time.day- 1, 22, 0, 0),
datetime(current_time.year, current_time.month, current_time.day, 6, 0, 0))
}
# Start filling details from row 8
row = 7
total_count = 0 # Initialize total count
packer_counts = defaultdict(int) # Initialize packer counts dictionary
# Get the camera_names and corresponding packer_names from config.yml
camera_names = [item['camera_name'] for item in self.config['cameras']]
packer_names = [item['packer_name'] for item in self.config['cameras']]
for camera_name, packer_name in zip(camera_names, packer_names):
for shift, (start_time, end_time) in shifts.items():
count = self.get_count(start_time, end_time, camera_name)
data.append({
'Date': start_time.date(),
'Shift Name': shift_name,
'Packer Name': packer_name,
'Count': count
})
# Fill in the data in respective cells
sheet[f'A{row}'] = serial_number
sheet[f'B{row}'] = end_time.date()
sheet[f'C{row}'] = shift
sheet[f'D{row}'] = packer_name
sheet[f'E{row}'] = count
total_count += count # Accumulate the count
packer_counts[packer_name] += count # Accumulate the count for the packer
row += 1
serial_number += 1
df = pd.DataFrame(data)
writer = pd.ExcelWriter('daily_report.xlsx', engine='openpyxl')
df.to_excel(writer, index=False, sheet_name='Report')
writer.save()
# Fill the total count in cell E26
sheet['F26'] = total_count
def schedule_report_generation(self):
schedule.every().day.at('08:00').do(self.create_excel_report)
# Fill the packer counts in column L
for packer_name, count in packer_counts.items():
packer_row = 9 + packer_names.index(packer_name) * 3
print('packer_row ------------- ',packer_row , 'packer_names.index(packer_name)--------- ',packer_names.index(packer_name))
sheet[f'F{packer_row}'] = count
while True:
schedule.run_pending()
time.sleep(1)
# Save the report file
wb.save(report_file)
# Create an instance of DailyReportGenerator and start scheduling report generation
# Return the absolute path of the generated report file
file_path = os.path.abspath(report_file)
return file_path
# Create an instance of DailyReportGenerator
report_generator = DailyReportGenerator()
report_generator.schedule_report_generation()
# Generate the daily report
report_path = report_generator.create_excel_report()
# Print the path of the generated report
print(f"Generated Daily Report: {report_path}")
import pandas as pd
from pymongo import MongoClient
from datetime import datetime, timedelta
import schedule
import time
import os
class DailyReportGenerator:
def __init__(self):
# Connect to MongoDB
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
self.collection = db[os.environ["MONGO_COLLECTION"]]
def get_shift_name(self, timestamp):
hour = timestamp.hour
if 6 <= hour < 14:
return 'Shift A'
elif 14 <= hour < 22:
return 'Shift B'
else:
return 'Shift C'
def map_packer_name(self, camera_name):
packer_mapping = {
'camera_41': 'Packer 1',
'camera_42': 'Packer 2',
'camera_44': 'Packer 4',
'camera_45': 'Packer 5',
'camera_46': 'Packer 6',
'camera_47': 'Packer 7'
}
return packer_mapping.get(camera_name, 'Unknown')
def get_count(self, start_time, end_time, camera_name):
query = {
'timestamp': {'$gte': start_time, '$lte': end_time},
'cameraName': camera_name
}
documents = self.collection.find(query).sort('timestamp', 1)
first_document = None
last_document = None
for document in documents:
if first_document is None:
first_document = document
last_document = document
if first_document is None or last_document is None:
return 0
count_difference = int(last_document['cement_bag_count']) - int(first_document['cement_bag_count'])
return count_difference
def create_excel_report(self):
data = []
current_time = datetime.now()
start_time = datetime(current_time.year, current_time.month, current_time.day - 1, 6, 0, 0)
end_time = datetime(current_time.year, current_time.month, current_time.day, 6, 0, 0)
for camera_name in ['camera_41', 'camera_42', 'camera_44', 'camera_45', 'camera_46', 'camera_47']:
shift_name = self.get_shift_name(start_time)
packer_name = self.map_packer_name(camera_name)
count = self.get_count(start_time, end_time, camera_name)
data.append({
'Date': start_time.date(),
'Shift Name': shift_name,
'Packer Name': packer_name,
'Count': count
})
df = pd.DataFrame(data)
file_path = os.path.abspath('daily_report.xlsx')
writer = pd.ExcelWriter(file_path, engine='openpyxl')
df.to_excel(writer, index=False, sheet_name='Report')
writer.save()
print('file path ***************** ---------', file_path)
return file_path
def schedule_report_generation(self):
schedule.every().day.at('08:00').do(self.create_excel_report)
while True:
schedule.run_pending()
time.sleep(1)
# Create an instance of DailyReportGenerator and start scheduling report generation
report_generator = DailyReportGenerator()
report_generator.schedule_report_generation()
import pandas as pd
from pymongo import MongoClient
from datetime import datetime, timedelta
import os
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import yaml
from dotenv import load_dotenv
load_dotenv(dotenv_path='.env')
class DailyReportGenerator:
def __init__(self):
# Connect to MongoDB
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
self.collection = db[os.environ["MONGO_COLLECTION"]]
# Load configuration from config.yml
with open('config.yml') as config_file:
config = yaml.safe_load(config_file)
self.template_file = config['template_file']
# self.logo_image = config['logo_image']
def get_shift_name(self, timestamp):
hour = timestamp.hour
if 6 <= hour < 14:
return 'Shift A'
elif 14 <= hour < 22:
return 'Shift B'
else:
return 'Shift C'
def map_packer_name(self, camera_name):
packer_mapping = {
'jk_4cebd0ec': 'Packer 1',
'camera_42': 'Packer 2',
'camera_44': 'Packer 4',
'camera_45': 'Packer 5',
'camera_46': 'Packer 6',
'camera_47': 'Packer 7'
}
return packer_mapping.get(camera_name, 'Unknown')
def get_count(self, start_time, end_time, camera_name):
query = {
'timestamp': {'$gte': start_time, '$lte': end_time},
'cameraName': camera_name
}
documents = self.collection.find(query).sort('timestamp', 1)
first_document = None
last_document = None
for document in documents:
if first_document is None:
first_document = document
last_document = document
if first_document is None or last_document is None:
return 0
count_difference = int(last_document['cement_bag_count']) - int(first_document['cement_bag_count'])
return count_difference
def create_excel_report(self):
report_file = 'daily_report.xlsx'
current_time = datetime.now()
report_date = current_time.strftime("%Y-%m-%d")
report_file = f"daily_report_{report_date}.xlsx"
start_time = datetime(current_time.year, current_time.month, current_time.day - 1, 6, 0, 0)
end_time = datetime(current_time.year, current_time.month, current_time.day, 23, 59, 0)
wb = load_workbook(self.template_file)
sheet = wb.active
# Add logos
# logo_image = Image(self.logo_image)
# sheet.add_image(logo_image, 'A1')
# sheet.merge_cells('A1:C3')
# Set report date
sheet['L6'] = report_date
serial_number = 1
# Start filling details from row 8
row = 8
for camera_name in ['jk_4cebd0ec', 'camera_42', 'camera_44', 'camera_45', 'camera_46', 'camera_47']:
shift_name = self.get_shift_name(start_time)
packer_name = self.map_packer_name(camera_name)
count = self.get_count(start_time, end_time, camera_name)
# Fill in the data in respective cells
sheet[f'A{row}'] = serial_number
sheet[f'B{row}'] = start_time.date()
sheet[f'C{row}'] = shift_name
sheet[f'D{row}'] = packer_name
sheet[f'E{row}'] = count
row += 1
serial_number += 1
# Save the report file
wb.save(report_file)
# Return the absolute path of the generated report file
file_path = os.path.abspath(report_file)
return file_path
# Create an instance of DailyReportGenerator
report_generator = DailyReportGenerator()
# Generate the daily report
report_path = report_generator.create_excel_report()
# Print the path of the generated report
print(f"Generated Daily Report: {report_path}")
import pandas as pd
from pymongo import MongoClient
from datetime import datetime, timedelta
import os
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import yaml
from dotenv import load_dotenv
from collections import defaultdict
load_dotenv(dotenv_path='.env')
class DailyReportGenerator:
def __init__(self):
# Connect to MongoDB
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
self.collection = db[os.environ["MONGO_COLLECTION"]]
# Load configuration from config.yml
with open('config.yml') as config_file:
config = yaml.safe_load(config_file)
self.template_file = config['template_file']
# self.logo_image = config['logo_image']
def get_shift_name(self, timestamp):
hour = timestamp.hour
if 6 <= hour < 14:
return 'Shift A'
elif 14 <= hour < 22:
return 'Shift B'
else:
return 'Shift C'
def map_packer_name(self, camera_name):
packer_mapping = {
'camera_41': 'Packer 1',
'camera_42': 'Packer 2',
'camera_44': 'Packer 4',
'camera_45': 'Packer 5',
'camera_46': 'Packer 6',
'camera_47': 'Packer 7'
}
return packer_mapping.get(camera_name, 'Unknown')
def get_count(self, start_time, end_time, camera_name):
query = {
'timestamp': {'$gte': start_time, '$lte': end_time},
'cameraName': camera_name
}
documents = self.collection.find(query).sort('timestamp', 1)
count_difference = 0
first_count = 0
last_count = 0
for i, document in enumerate(documents):
if i == 0:
first_count = int(document['cement_bag_count'])
last_count = int(document['cement_bag_count'])
count_difference = last_count - first_count
return count_difference
def create_excel_report(self):
report_file = 'daily_report.xlsx'
current_time = datetime.now()
report_date = current_time.strftime("%Y-%m-%d")
report_file = f"daily_report_{report_date}.xlsx"
wb = load_workbook(self.template_file)
sheet = wb.active
# Set report date
sheet['L6'] = report_date
serial_number = 1
# Define the shifts and their respective time ranges
shifts = {
'Shift A': (datetime(current_time.year, current_time.month, current_time.day -1 , 6, 0, 0),
datetime(current_time.year, current_time.month, current_time.day -1, 14, 0, 0)),
'Shift B': (datetime(current_time.year, current_time.month, current_time.day -1, 14, 0, 0),
datetime(current_time.year, current_time.month, current_time.day -1, 22, 0, 0)),
'Shift C': (datetime(current_time.year, current_time.month, current_time.day- 1, 22, 0, 0),
datetime(current_time.year, current_time.month, current_time.day, 6, 0, 0))
}
# Start filling details from row 8
row = 7
for camera_name in ['camera_41', 'camera_42', 'camera_44', 'camera_45', 'camera_46', 'camera_47']:
for shift, (start_time, end_time) in shifts.items():
packer_name = self.map_packer_name(camera_name)
count = self.get_count(start_time, end_time, camera_name)
# Fill in the data in respective cells
sheet[f'A{row}'] = serial_number
sheet[f'B{row}'] = end_time.date()
sheet[f'C{row}'] = shift
sheet[f'D{row}'] = packer_name
sheet[f'E{row}'] = count
row += 1
serial_number += 1
# Save the report file
wb.save(report_file)
# Return the absolute path of the generated report file
file_path = os.path.abspath(report_file)
return file_path
# Create an instance of DailyReportGenerator
report_generator = DailyReportGenerator()
# Generate the daily report
report_path = report_generator.create_excel_report()
# Print the path of the generated report
print(f"Generated Daily Report: {report_path}")
import pandas as pd
from pymongo import MongoClient
from datetime import datetime, timedelta
import os
from openpyxl import load_workbook
from openpyxl.drawing.image import Image
import yaml
from dotenv import load_dotenv
from collections import defaultdict
load_dotenv(dotenv_path='.env')
class DailyReportGenerator:
def __init__(self):
# Connect to MongoDB
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
self.collection = db[os.environ["MONGO_COLLECTION"]]
# Load configuration from config.yml
with open('config.yml') as config_file:
self.config = yaml.safe_load(config_file)
self.template_file = self.config['template_file']
self.camera_mappings = {
item['camera_name']: item['packer_name']
for item in self.config['cameras']
}
def get_shift_name(self, timestamp):
hour = timestamp.hour
if 6 <= hour < 14:
return 'Shift A'
elif 14 <= hour < 22:
return 'Shift B'
else:
return 'Shift C'
def get_packer_name(self, camera_name):
return self.camera_mappings.get(camera_name, 'Unknown')
def get_count(self, start_time, end_time, camera_name):
query = {
'timestamp': {'$gte': start_time, '$lte': end_time},
'cameraName': camera_name
}
documents = self.collection.find(query).sort('timestamp', 1)
count_difference = 0
first_count = 0
last_count = 0
for i, document in enumerate(documents):
if i == 0:
first_count = int(document['cement_bag_count'])
last_count = int(document['cement_bag_count'])
count_difference = last_count - first_count
return count_difference
def create_excel_report(self):
report_file = 'daily_report.xlsx'
current_time = datetime.now()
report_date = current_time.strftime("%Y-%m-%d")
report_file = f"daily_report_{report_date}.xlsx"
wb = load_workbook(self.template_file)
sheet = wb.active
# Set report date
sheet['L6'] = report_date
serial_number = 1
# Define the shifts and their respective time ranges
shifts = {
'Shift A': (datetime(current_time.year, current_time.month, current_time.day -1 , 6, 0, 0),
datetime(current_time.year, current_time.month, current_time.day -1, 14, 0, 0)),
'Shift B': (datetime(current_time.year, current_time.month, current_time.day -1, 14, 0, 0),
datetime(current_time.year, current_time.month, current_time.day -1, 22, 0, 0)),
'Shift C': (datetime(current_time.year, current_time.month, current_time.day- 1, 22, 0, 0),
datetime(current_time.year, current_time.month, current_time.day, 6, 0, 0))
}
# Start filling details from row 8
row = 7
total_count = 0 # Initialize total count
# Get the camera_names from config.yml
camera_names = [item['camera_name'] for item in self.config['cameras']]
for camera_name in camera_names:
for shift, (start_time, end_time) in shifts.items():
packer_name = self.get_packer_name(camera_name)
count = self.get_count(start_time, end_time, camera_name)
# Fill in the data in respective cells
sheet[f'A{row}'] = serial_number
sheet[f'B{row}'] = end_time.date()
sheet[f'C{row}'] = shift
sheet[f'D{row}'] = packer_name
sheet[f'E{row}'] = count
total_count += count # Accumulate the count
row += 1
serial_number += 1
# Fill the total count in cell E26
sheet['E26'] = total_count
# Save the report file
wb.save(report_file)
# Return the absolute path of the generated report file
file_path = os.path.abspath(report_file)
return file_path
# Create an instance of DailyReportGenerator
report_generator = DailyReportGenerator()
# Generate the daily report
report_path = report_generator.create_excel_report()
# Print the path of the generated report
print(f"Generated Daily Report: {report_path}")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment