Commit c009609a authored by vaisakh.nair's avatar vaisakh.nair 🎯

a sample.py created with the email sendingm logic

parent 03541e24
......@@ -5,4 +5,9 @@
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=ilens_ai
MONGO_COLLECTION=eventLogs
\ No newline at end of file
MONGO_COLLECTION=eventLogs
SMTP_HOST=
SMTP_PORT=
SMTP_USERNAME=
SMTP_PASSWORD=
SENDER_EMAIL=
\ No newline at end of file
......@@ -4,12 +4,17 @@ FROM python:3.9
# Set the working directory in the container
WORKDIR /app
# Copy the code files into the container
COPY app.py utils config.yml .env ./
# Copy the project files to the working directory
COPY . /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Install the project dependencies
RUN pip install -r requirements.txt
# Run the application
CMD ["python", "app.py"]
# Set the working directory to the app folder
WORKDIR /app/utils
# Expose the port on which your application runs (if needed)
# EXPOSE <port_number>
# Define the command to run your application
CMD ["python", "../app.py"]
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
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
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()
# 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)
# Fill in the data in respective cells
sheet[f'A{row}'] = serial_number
sheet[f'B{row}'] = end_time.date()
sheet[f'C{row}'] = packer_name
sheet[f'D{row}'] = shift
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
# Fill the total count in cell E26
sheet['F26'] = total_count
# Fill the packer counts in column L
for packer_name, count in packer_counts.items():
packer_row = 9 + packer_names.index(packer_name) * 3
sheet[f'F{packer_row}'] = 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
def get_receiver_emails(self):
# Connect to MongoDB and retrieve the email addresses from the collection
client = MongoClient(os.environ["MONGO_CLIENT"])
db = client[os.environ["MONGO_DATABASE"]]
collection = db[os.environ["MONGO_COLLECTION"]]
emails = []
documents = collection.find()
for document in documents:
emails.append(document["email"])
return emails
def send_email(self, report_path):
# Email configuration
smtp_host = os.environ["SMTP_HOST"]
smtp_port = os.environ["SMTP_PORT"]
smtp_username = os.environ["SMTP_USERNAME"]
smtp_password = os.environ["SMTP_PASSWORD"]
sender_email = os.environ["SENDER_EMAIL"]
receiver_emails = self.get_receiver_emails() # Fetch receiver email addresses
# Create a multipart message
msg = MIMEMultipart()
msg["From"] = sender_email
msg["To"] = ", ".join(receiver_emails)
msg["Subject"] = "Daily Report"
# Attach the report file
attachment = open(report_path, "rb")
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", f"attachment; filename= {report_path}")
msg.attach(part)
# Send the email
with smtplib.SMTP(smtp_host, smtp_port) as smtp:
smtp.starttls()
smtp.login(smtp_username, smtp_password)
smtp.send_message(msg)
# Close the attachment file
attachment.close()
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