# Counters for male and female
male_count = 0
female_count = 0
# A copy of the original image for drawing results
output_img = img.copy()
# Loop through each person's bounding box
for (x1, y1, x2, y2) in person_boxes:
# Crop the person from the image
person_crop = img[y1:y2, x1:x2]
label = "Unknown"
try:
# Apply gender detection on the person crop
# padding is used to better detect faces at the edge of the crop
face, confidence = cv.detect_face(person_crop, threshold=0.5)
# We process only if one face is detected to avoid ambiguity
if len(face) > 0:
# Get the first face detected
(startX, startY, endX, endY) = face[0]
face_crop = np.copy(person_crop[startY:endY, startX:endX])
# Predict gender of the detected face
(gender_label, gender_confidence) = cv.detect_gender(face_crop)
if gender_confidence > 0.6: # Confidence threshold
label = gender_label
if label == 'male':
male_count += 1
elif label == 'female':
female_count += 1
except Exception as e:
# Sometimes cvlib can fail on small or unclear crops
label = "Error"
# Draw bounding box and label on the output image
color = (0, 255, 0) if label in ["male", "female"] else (0, 0, 255)
cv2.rectangle(output_img, (x1, y1), (x2, y2), color, 2)
cv2.putText(output_img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
print(f"Males detected: {male_count}")
print(f"Females detected: {female_count}")
---
Step 5: Displaying Final Results
Finally, we calculate the percentages and display the annotated image along with a summary of our findings.
#Results #Visualization
# Calculate percentages
known_gender_count = male_count + female_count
if known_gender_count > 0:
male_percentage = (male_count / known_gender_count) * 100
female_percentage = (female_count / known_gender_count) * 100
else:
male_percentage = 0
female_percentage = 0
# Prepare the summary text
summary_text1 = f"Total People: {total_people}"
summary_text2 = f"Men: {male_count} ({male_percentage:.1f}%)"
summary_text3 = f"Women: {female_count} ({female_percentage:.1f}%)"
# Add summary text to the image
cv2.putText(output_img, summary_text1, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3)
cv2.putText(output_img, summary_text2, (10, 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3)
cv2.putText(output_img, summary_text3, (10, 90), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 3)
# Save or display the final image
cv2.imwrite('crowd_analysis_result.jpg', output_img)
print("\n--- Analysis Complete ---")
print(summary_text1)
print(summary_text2)
print(summary_text3)
print("Result image saved as 'crowd_analysis_result.jpg'")
---
Step 6: Discussion of Results and Limitations
#Discussion #Ethics #AI
Person Detection Accuracy: YOLOv8 is highly effective at detecting people, but it can struggle with heavy occlusion (people hiding others) or very low-resolution images, potentially leading to an undercount.
Gender Classification Reliability: The secondary gender classification model (
Ethical Considerations & Bias: Gender classification from images is an inherently problematic task. These models are trained on datasets that may contain biases and often rely on stereotypical features (e.g., hair length). The model's performance can be worse for certain ethnicities and it cannot account for non-binary gender identities. This tool should be seen as a rough estimator based on visual stereotypes, not a definitive measure of gender.
Performance: For real-time video, this multi-step process (YOLO -> crop -> face detection -> gender detection) can be slow. A more advanced approach would be to fine-tune a single object detection model on a custom dataset with 'man' and 'woman' classes for much faster and more integrated performance.
━━━━━━━━━━━━━━━
By: @DataScienceN ✨
Gender Classification Reliability: The secondary gender classification model (
cvlib) is a simplified model. Its accuracy depends heavily on clear, front-facing views of faces. It may fail on side profiles, poor lighting, or small faces.Ethical Considerations & Bias: Gender classification from images is an inherently problematic task. These models are trained on datasets that may contain biases and often rely on stereotypical features (e.g., hair length). The model's performance can be worse for certain ethnicities and it cannot account for non-binary gender identities. This tool should be seen as a rough estimator based on visual stereotypes, not a definitive measure of gender.
Performance: For real-time video, this multi-step process (YOLO -> crop -> face detection -> gender detection) can be slow. A more advanced approach would be to fine-tune a single object detection model on a custom dataset with 'man' and 'woman' classes for much faster and more integrated performance.
━━━━━━━━━━━━━━━
By: @DataScienceN ✨
🔥 Trending Repository: chef
📝 Description: The only AI app builder that knows backend
🔗 Repository URL: https://github.com/get-convex/chef
🌐 Website: https://chef.convex.dev
📖 Readme: https://github.com/get-convex/chef#readme
📊 Statistics:
🌟 Stars: 2.5K stars
👀 Watchers: 22
🍴 Forks: 497 forks
💻 Programming Languages: TypeScript - JavaScript - CSS
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: The only AI app builder that knows backend
🔗 Repository URL: https://github.com/get-convex/chef
🌐 Website: https://chef.convex.dev
📖 Readme: https://github.com/get-convex/chef#readme
📊 Statistics:
🌟 Stars: 2.5K stars
👀 Watchers: 22
🍴 Forks: 497 forks
💻 Programming Languages: TypeScript - JavaScript - CSS
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: docs
📝 Description: A collaborative note taking, wiki and documentation platform that scales. Built with Django and React.
🔗 Repository URL: https://github.com/suitenumerique/docs
🌐 Website: https://docs.numerique.gouv.fr
📖 Readme: https://github.com/suitenumerique/docs#readme
📊 Statistics:
🌟 Stars: 14.1K stars
👀 Watchers: 56
🍴 Forks: 423 forks
💻 Programming Languages: Python - TypeScript - CSS - JavaScript - Makefile - Shell
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: A collaborative note taking, wiki and documentation platform that scales. Built with Django and React.
🔗 Repository URL: https://github.com/suitenumerique/docs
🌐 Website: https://docs.numerique.gouv.fr
📖 Readme: https://github.com/suitenumerique/docs#readme
📊 Statistics:
🌟 Stars: 14.1K stars
👀 Watchers: 56
🍴 Forks: 423 forks
💻 Programming Languages: Python - TypeScript - CSS - JavaScript - Makefile - Shell
🏷️ Related Topics:
#government #documentation #django #opensource #mit #knowledge #wiki #reactjs #self_hosted #mit_license #collaborative #knowledge_base #yjs #realtime_collaboration #g2g #blocknotejs
==================================
🧠 By: https://t.iss.one/DataScienceM
❤1
🔥 Trending Repository: Deep-Live-Cam
📝 Description: real time face swap and one-click video deepfake with only a single image
🔗 Repository URL: https://github.com/hacksider/Deep-Live-Cam
🌐 Website: https://deeplivecam.net/
📖 Readme: https://github.com/hacksider/Deep-Live-Cam#readme
📊 Statistics:
🌟 Stars: 74.6K stars
👀 Watchers: 454
🍴 Forks: 10.9K forks
💻 Programming Languages: Python
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: real time face swap and one-click video deepfake with only a single image
🔗 Repository URL: https://github.com/hacksider/Deep-Live-Cam
🌐 Website: https://deeplivecam.net/
📖 Readme: https://github.com/hacksider/Deep-Live-Cam#readme
📊 Statistics:
🌟 Stars: 74.6K stars
👀 Watchers: 454
🍴 Forks: 10.9K forks
💻 Programming Languages: Python
🏷️ Related Topics:
#ai #realtime #artificial_intelligence #faceswap #gan #webcam #webcamera #deepfake #deep_fake #ai_face #video_deepfake #realtime_deepfake #deepfake_webcam #realtime_face_changer #fake_webcam #ai_webcam #ai_deep_fake #real_time_deepfake
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: copilot-cli
📝 Description: GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.
🔗 Repository URL: https://github.com/github/copilot-cli
📖 Readme: https://github.com/github/copilot-cli#readme
📊 Statistics:
🌟 Stars: 4.4K stars
👀 Watchers: 42
🍴 Forks: 282 forks
💻 Programming Languages: Not available
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: GitHub Copilot CLI brings the power of Copilot coding agent directly to your terminal.
🔗 Repository URL: https://github.com/github/copilot-cli
📖 Readme: https://github.com/github/copilot-cli#readme
📊 Statistics:
🌟 Stars: 4.4K stars
👀 Watchers: 42
🍴 Forks: 282 forks
💻 Programming Languages: Not available
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: ruoyi-vue-pro
📝 Description: 🔥 官方推荐 🔥 RuoYi-Vue 全新 Pro 版本,优化重构所有功能。基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 微信小程序,支持 RBAC 动态权限、数据权限、SaaS 多租户、Flowable 工作流、三方登录、支付、短信、商城、CRM、ERP、AI 大模型等功能。你的 ⭐️ Star ⭐️,是作者生发的动力!
🔗 Repository URL: https://github.com/YunaiV/ruoyi-vue-pro
🌐 Website: https://doc.iocoder.cn/
📖 Readme: https://github.com/YunaiV/ruoyi-vue-pro#readme
📊 Statistics:
🌟 Stars: 33.8K stars
👀 Watchers: 252
🍴 Forks: 7.3K forks
💻 Programming Languages: Java - PLpgSQL - TSQL
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: 🔥 官方推荐 🔥 RuoYi-Vue 全新 Pro 版本,优化重构所有功能。基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 微信小程序,支持 RBAC 动态权限、数据权限、SaaS 多租户、Flowable 工作流、三方登录、支付、短信、商城、CRM、ERP、AI 大模型等功能。你的 ⭐️ Star ⭐️,是作者生发的动力!
🔗 Repository URL: https://github.com/YunaiV/ruoyi-vue-pro
🌐 Website: https://doc.iocoder.cn/
📖 Readme: https://github.com/YunaiV/ruoyi-vue-pro#readme
📊 Statistics:
🌟 Stars: 33.8K stars
👀 Watchers: 252
🍴 Forks: 7.3K forks
💻 Programming Languages: Java - PLpgSQL - TSQL
🏷️ Related Topics:
#mysql #redis #vue #spring_security #springboot #redisson #mybatis_plus #flowable
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: xiaomusic
📝 Description: 使用小爱音箱播放音乐,音乐使用 yt-dlp 下载。
🔗 Repository URL: https://github.com/hanxi/xiaomusic
🌐 Website: https://xdocs.hanxi.cc/
📖 Readme: https://github.com/hanxi/xiaomusic#readme
📊 Statistics:
🌟 Stars: 6.4K stars
👀 Watchers: 22
🍴 Forks: 637 forks
💻 Programming Languages: Python
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: 使用小爱音箱播放音乐,音乐使用 yt-dlp 下载。
🔗 Repository URL: https://github.com/hanxi/xiaomusic
🌐 Website: https://xdocs.hanxi.cc/
📖 Readme: https://github.com/hanxi/xiaomusic#readme
📊 Statistics:
🌟 Stars: 6.4K stars
👀 Watchers: 22
🍴 Forks: 637 forks
💻 Programming Languages: Python
🏷️ Related Topics:
#python #music #docker #vue #docker_compose #xiaomi #pdm #xiaoai #xiaoai_speaker #xiaomusic
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: lingo.dev
📝 Description: ⚡ Lingo.dev - open-source, AI-powered i18n toolkit for instant localization with LLMs. Bring your own LLM or use Lingo.dev Localization Engine. Join discord:
🔗 Repository URL: https://github.com/lingodotdev/lingo.dev
🌐 Website: https://lingo.dev/go/discord
📖 Readme: https://github.com/lingodotdev/lingo.dev#readme
📊 Statistics:
🌟 Stars: 3.9K stars
👀 Watchers: 8
🍴 Forks: 599 forks
💻 Programming Languages: TypeScript - JavaScript - PHP - HTML - MDX - EJS
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: ⚡ Lingo.dev - open-source, AI-powered i18n toolkit for instant localization with LLMs. Bring your own LLM or use Lingo.dev Localization Engine. Join discord:
🔗 Repository URL: https://github.com/lingodotdev/lingo.dev
🌐 Website: https://lingo.dev/go/discord
📖 Readme: https://github.com/lingodotdev/lingo.dev#readme
📊 Statistics:
🌟 Stars: 3.9K stars
👀 Watchers: 8
🍴 Forks: 599 forks
💻 Programming Languages: TypeScript - JavaScript - PHP - HTML - MDX - EJS
🏷️ Related Topics:
#react #javascript #i18n #typescript #react_native
==================================
🧠 By: https://t.iss.one/DataScienceM
❤1
#YOLOv8 #ComputerVision #HomeSecurity #ObjectTracking #AI #Python
Lesson: Tracking Suspicious Individuals Near a Home at Night with YOLOv8
This tutorial demonstrates how to build an advanced security system using YOLOv8's object tracking capabilities. The system will detect people in a night-time video feed, track their movements, and trigger an alert if a person loiters for too long within a predefined "alert zone" (e.g., a driveway or porch).
---
We will use
Create a Python script (e.g.,
---
We will load a standard YOLOv8 model capable of detecting 'person'. The key is to define a polygon representing the area we want to monitor. We will also set a time threshold to define "loitering". You will need a video file of your target area, for example,
---
This is the core of the system. We will read the video frame by frame and use YOLOv8's
(Note: The code below should be placed inside the
---
Inside the main loop, we'll iterate through each tracked person. We check if their position is inside our alert zone. If it is, we start or update a timer. If the timer exceeds our threshold, we trigger an alert for that person's ID.
Lesson: Tracking Suspicious Individuals Near a Home at Night with YOLOv8
This tutorial demonstrates how to build an advanced security system using YOLOv8's object tracking capabilities. The system will detect people in a night-time video feed, track their movements, and trigger an alert if a person loiters for too long within a predefined "alert zone" (e.g., a driveway or porch).
---
#Step 1: Project Setup and DependenciesWe will use
ultralytics for YOLOv8 and its built-in tracker, opencv-python for video processing, and numpy for defining our security zone.pip install ultralytics opencv-python numpy
Create a Python script (e.g.,
security_tracker.py) and import the necessary libraries. We'll also use defaultdict to easily manage timers for each tracked person.import cv2
import numpy as np
from ultralytics import YOLO
from collections import defaultdict
import time
# Hashtags: #Setup #Python #OpenCV #YOLOv8
---
#Step 2: Model Loading and Zone ConfigurationWe will load a standard YOLOv8 model capable of detecting 'person'. The key is to define a polygon representing the area we want to monitor. We will also set a time threshold to define "loitering". You will need a video file of your target area, for example,
night_security_footage.mp4.# Load the YOLOv8 model
model = YOLO('yolov8n.pt')
# Path to your night-time video file
VIDEO_PATH = 'night_security_footage.mp4'
# Define the polygon for the alert zone.
# IMPORTANT: You MUST adjust these [x, y] coordinates to fit your video's perspective.
# This example defines a rectangular area for a driveway.
ALERT_ZONE_POLYGON = np.array([
[100, 500], [800, 500], [850, 250], [50, 250]
], np.int32)
# Time in seconds a person can be in the zone before an alert is triggered
LOITERING_THRESHOLD_SECONDS = 5.0
# Dictionaries to store tracking data
# Stores the time when a tracked object first enters the zone
loitering_timers = {}
# Stores the IDs of individuals who have triggered an alert
alert_triggered_ids = set()
# Hashtags: #Configuration #AIModel #SecurityZone
---
#Step 3: Main Loop for Tracking and Zone MonitoringThis is the core of the system. We will read the video frame by frame and use YOLOv8's
track() function. This function not only detects objects but also assigns a unique ID to each one, allowing us to follow them across frames.cap = cv2.VideoCapture(VIDEO_PATH)
while cap.isOpened():
success, frame = cap.read()
if not success:
break
# Run YOLOv8 tracking on the frame, persisting tracks between frames
results = model.track(frame, persist=True)
# Get the bounding boxes and track IDs
boxes = results[0].boxes.xywh.cpu()
track_ids = results[0].boxes.id.int().cpu().tolist()
# Visualize the results on the frame
annotated_frame = results[0].plot()
# Draw the alert zone polygon on the frame
cv2.polylines(annotated_frame, [ALERT_ZONE_POLYGON], isClosed=True, color=(0, 255, 255), thickness=2)
# Hashtags: #RealTime #ObjectTracking #VideoProcessing
(Note: The code below should be placed inside the
while loop of Step 3)---
#Step 4: Implementing Loitering Logic and AlertsInside the main loop, we'll iterate through each tracked person. We check if their position is inside our alert zone. If it is, we start or update a timer. If the timer exceeds our threshold, we trigger an alert for that person's ID.
# --- Loitering Logic --- (This code continues inside the while loop)
for box, track_id in zip(boxes, track_ids):
x, y, w, h = box
center_point = (int(x), int(y))
# Check if the center of the person is inside the alert zone
is_inside_zone = cv2.pointPolygonTest(ALERT_ZONE_POLYGON, center_point, False) >= 0
if is_inside_zone:
# If person is inside, start or check their timer
if track_id not in loitering_timers:
# First time this person is detected in the zone
loitering_timers[track_id] = time.time()
else:
# Person is still in the zone, check duration
elapsed_time = time.time() - loitering_timers[track_id]
if elapsed_time > LOITERING_THRESHOLD_SECONDS:
# Loitering detected! Trigger alert.
alert_triggered_ids.add(track_id)
else:
# If person leaves the zone, reset their timer
if track_id in loitering_timers:
del loitering_timers[track_id]
if track_id in alert_triggered_ids:
alert_triggered_ids.remove(track_id) # Optional: reset alert when they leave
# Add visual alert text for tracked individuals who triggered the alert
for track_id in alert_triggered_ids:
# This part requires re-iterating through boxes to find the right one to draw on.
# A more optimized way would be to store box coordinates with the track_id.
for box, tid in zip(results[0].boxes.xyxy.cpu(), track_ids):
if tid == track_id:
x1, y1, _, _ = map(int, box)
cv2.putText(annotated_frame, "ALERT: LOITERING!", (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
break
# Display the annotated frame
cv2.imshow("Suspicious Activity Tracker", annotated_frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
# Hashtags: #SecurityAI #AlertSystem #HomeSafety
---
#Step 5: Results and DiscussionWhen you run the script, you will see your video with:
• A yellow polygon outlining your defined security zone.
• Bounding boxes around each person with a unique tracking ID.
• If a person stays inside the zone for longer than
LOITERING_THRESHOLD_SECONDS, a red "ALERT: LOITERING!" message will appear above their bounding box.Discussion and Ethical Considerations:
Defining "Suspicious": This system does not understand "suspicious behavior." It only follows a simple rule:
person + location + time. The interpretation of this as "suspicious" is a human one.False Positives: The system will trigger an alert for anyone who meets the criteria, including a homeowner, a delivery driver waiting for a signature, or a neighbor stopping to chat. The
LOITERING_THRESHOLD_SECONDS must be carefully tuned to balance security with convenience.Tracking Stability: In low-light conditions, the tracker might lose a person and assign them a new ID when they reappear, resetting the timer. Using a higher-quality camera or a YOLO model fine-tuned on night-time data (e.g., from thermal or infrared cameras) would significantly improve performance.
Bias and Fairness: AI models can be less accurate in identifying individuals from underrepresented groups in their training data. In a security context, this could lead to a higher rate of missed detections or false alarms for certain people, which is a serious ethical issue. This tool should be used to assist human judgment, not replace it.
#ProjectComplete #AIforGood #ResponsibleAI
━━━━━━━━━━━━━━━
By: @DataScienceN ✨
#PyQt5 #SQLite #DesktopApp #Pharmacy #Barcode #Python
Lesson: Building a Pharmacy Management System with PyQt5 and Barcode Scanning
This tutorial will guide you through creating a complete desktop application for managing a pharmacy. The system will use a SQLite database for inventory, and a Point of Sale (POS) interface that uses barcode scanning to add drugs to a sale and automatically deducts stock upon completion.
---
First, we create a dedicated file to handle all SQLite database operations. This keeps our data logic separate from our UI logic. Create a file named
---
Create the main application file,
Lesson: Building a Pharmacy Management System with PyQt5 and Barcode Scanning
This tutorial will guide you through creating a complete desktop application for managing a pharmacy. The system will use a SQLite database for inventory, and a Point of Sale (POS) interface that uses barcode scanning to add drugs to a sale and automatically deducts stock upon completion.
---
#Step 1: Database Setup (database.py)First, we create a dedicated file to handle all SQLite database operations. This keeps our data logic separate from our UI logic. Create a file named
database.py.import sqlite3
DB_NAME = 'pharmacy.db'
def connect():
return sqlite3.connect(DB_NAME)
def setup_database():
conn = connect()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS drugs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
barcode TEXT NOT NULL UNIQUE,
quantity INTEGER NOT NULL,
price REAL NOT NULL,
expiry_date TEXT NOT NULL
)
''')
conn.commit()
conn.close()
def add_drug(name, barcode, quantity, price, expiry_date):
conn = connect()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO drugs (name, barcode, quantity, price, expiry_date) VALUES (?, ?, ?, ?, ?)",
(name, barcode, quantity, price, expiry_date))
conn.commit()
except sqlite3.IntegrityError:
return False # Barcode already exists
finally:
conn.close()
return True
def get_all_drugs():
conn = connect()
cursor = conn.cursor()
cursor.execute("SELECT id, name, barcode, quantity, price, expiry_date FROM drugs ORDER BY name")
drugs = cursor.fetchall()
conn.close()
return drugs
def find_drug_by_barcode(barcode):
conn = connect()
cursor = conn.cursor()
cursor.execute("SELECT id, name, barcode, quantity, price, expiry_date FROM drugs WHERE barcode = ?", (barcode,))
drug = cursor.fetchone()
conn.close()
return drug
def update_drug_quantity(drug_id, sold_quantity):
conn = connect()
cursor = conn.cursor()
cursor.execute("UPDATE drugs SET quantity = quantity - ? WHERE id = ?", (sold_quantity, drug_id))
conn.commit()
conn.close()
# Hashtags: #SQLite #DatabaseDesign #DataPersistence #Python
---
#Step 2: Main Application and Inventory Management UICreate the main application file,
main.py. We will set up the main window with tabs for "Point of Sale" and "Inventory Management". We will fully implement the inventory tab first, allowing users to view and add drugs to the database.import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import QDate
import database as db
class PharmacyApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Pharmacy Management System")
self.setGeometry(100, 100, 1200, 700)
db.setup_database()
self.tabs = QTabWidget()
self.setCentralWidget(self.tabs)
self.pos_tab = QWidget()
self.inventory_tab = QWidget()
self.tabs.addTab(self.pos_tab, "Point of Sale")
self.tabs.addTab(self.inventory_tab, "Inventory Management")
self.setup_inventory_ui()
# self.setup_pos_ui() will be done in the next step
self.load_inventory_data()
def setup_inventory_ui(self):
layout = QVBoxLayout()
self.inventory_table = QTableWidget()
self.inventory_table.setColumnCount(6)
self.inventory_table.setHorizontalHeaderLabels(['ID', 'Name', 'Barcode', 'Quantity', 'Price', 'Expiry Date'])
layout.addWidget(self.inventory_table)
form = QFormLayout()
self.drug_name = QLineEdit()
self.drug_barcode = QLineEdit()
self.drug_qty = QSpinBox()
self.drug_qty.setRange(0, 9999)
self.drug_price = QLineEdit()
self.drug_expiry = QDateEdit(QDate.currentDate().addYears(1))
self.drug_expiry.setDisplayFormat("yyyy-MM-dd")
form.addRow("Name:", self.drug_name)
form.addRow("Barcode:", self.drug_barcode)
form.addRow("Quantity:", self.drug_qty)
form.addRow("Price:", self.drug_price)
form.addRow("Expiry Date:", self.drug_expiry)
add_btn = QPushButton("Add Drug to Inventory")
add_btn.clicked.connect(self.add_drug_to_db)
layout.addLayout(form)
layout.addWidget(add_btn)
self.inventory_tab.setLayout(layout)
def load_inventory_data(self):
drugs = db.get_all_drugs()
self.inventory_table.setRowCount(len(drugs))
for row, drug in enumerate(drugs):
for col, data in enumerate(drug):
self.inventory_table.setItem(row, col, QTableWidgetItem(str(data)))
def add_drug_to_db(self):
name = self.drug_name.text()
barcode = self.drug_barcode.text()
qty = self.drug_qty.value()
price = float(self.drug_price.text())
expiry = self.drug_expiry.date().toString("yyyy-MM-dd")
if not all([name, barcode, qty > 0, price > 0]):
QMessageBox.warning(self, "Input Error", "Please fill all fields correctly.")
return
if db.add_drug(name, barcode, qty, price, expiry):
self.load_inventory_data()
else:
QMessageBox.warning(self, "Database Error", "A drug with this barcode already exists.")
# Main execution block at the end of the file
if __name__ == '__main__':
app = QApplication(sys.argv)
window = PharmacyApp()
window.show()
sys.exit(app.exec_())
# Hashtags: #PyQt5 #GUI #CRUD #Inventory
---
#Step 3: Point of Sale (POS) UI and Barcode HandlingNow, let's build the user interface for the sales tab. This will include an input for the barcode, a table for the current sale items (the "cart"), and buttons to finalize or clear the sale. A physical barcode scanner typically emulates a keyboard, entering the numbers and pressing "Enter". We will simulate this with the
returnPressed signal on a QLineEdit.Add these methods to the
PharmacyApp class:# In __init__, call the setup method
self.setup_pos_ui()
self.current_sale_items = {} # Dictionary to store {drug_id: {data, quantity}}
def setup_pos_ui(self):
main_layout = QHBoxLayout()
# Left side: Sale and Barcode input
left_layout = QVBoxLayout()
barcode_group = QGroupBox("Scan Barcode")
barcode_layout = QVBoxLayout()
self.barcode_input = QLineEdit()
self.barcode_input.setPlaceholderText("Scan or type barcode and press Enter...")
self.barcode_input.returnPressed.connect(self.add_item_to_sale)
barcode_layout.addWidget(self.barcode_input)
barcode_group.setLayout(barcode_layout)
self.sales_table = QTableWidget()
self.sales_table.setColumnCount(5)
self.sales_table.setHorizontalHeaderLabels(['ID', 'Name', 'Quantity', 'Unit Price', 'Total Price'])
left_layout.addWidget(barcode_group)
left_layout.addWidget(self.sales_table)
# Right side: Totals and Actions
right_layout = QVBoxLayout()
total_group = QGroupBox("Sale Summary")
total_form = QFormLayout()
self.total_amount_label = QLabel("0.00")
total_form.addRow("Total Amount:", self.total_amount_label)
total_group.setLayout(total_form)
complete_sale_btn = QPushButton("Complete Sale")
complete_sale_btn.clicked.connect(self.complete_sale)
clear_sale_btn = QPushButton("Clear Sale")
clear_sale_btn.clicked.connect(self.clear_sale)
right_layout.addWidget(total_group)
right_layout.addWidget(complete_sale_btn)
right_layout.addWidget(clear_sale_btn)
right_layout.addStretch()
main_layout.addLayout(left_layout, stretch=3) # Left side takes 3/4 of space
main_layout.addLayout(right_layout, stretch=1) # Right side takes 1/4
self.pos_tab.setLayout(main_layout)
#Hashtags: #PointOfSale #BarcodeScanner #UIUX #PyQt5
---
#Step 4: Implementing the Sales LogicThis is the core logic that connects the barcode input to the sales table and the database. When a barcode is entered, we find the drug, add it to the current sale, and update the UI. The "Complete Sale" button will finalize the transaction by updating the database.
Add these methods to the
PharmacyApp class:def add_item_to_sale(self):
barcode = self.barcode_input.text()
if not barcode:
return
drug = db.find_drug_by_barcode(barcode)
if not drug:
QMessageBox.warning(self, "Not Found", "No drug found with this barcode.")
self.barcode_input.clear()
return
drug_id = drug[0]
if drug[3] <= 0: # Check quantity
QMessageBox.warning(self, "Out of Stock", f"{drug[1]} is out of stock.")
self.barcode_input.clear()
return
if drug_id in self.current_sale_items:
# Item already in sale, increment quantity
self.current_sale_items[drug_id]['quantity'] += 1
else:
# Add new item to sale
self.current_sale_items[drug_id] = {
'data': drug,
'quantity': 1
}
self.update_sales_table()
self.barcode_input.clear()
def update_sales_table(self):
self.sales_table.setRowCount(len(self.current_sale_items))
total_sale_amount = 0.0
for row, item in enumerate(self.current_sale_items.values()):
drug_data = item['data']
quantity = item['quantity']
unit_price = drug_data[4]
total_price = quantity * unit_price
self.sales_table.setItem(row, 0, QTableWidgetItem(str(drug_data[0]))) # ID
self.sales_table.setItem(row, 1, QTableWidgetItem(drug_data[1])) # Name
self.sales_table.setItem(row, 2, QTableWidgetItem(str(quantity)))
self.sales_table.setItem(row, 3, QTableWidgetItem(f"{unit_price:.2f}"))
self.sales_table.setItem(row, 4, QTableWidgetItem(f"{total_price:.2f}"))
total_sale_amount += total_price
self.total_amount_label.setText(f"{total_sale_amount:.2f}")
def complete_sale(self):
if not self.current_sale_items:
return
for drug_id, item in self.current_sale_items.items():
db.update_drug_quantity(drug_id, item['quantity'])
QMessageBox.information(self, "Success", f"Sale completed. Total: {self.total_amount_label.text()}")
self.clear_sale()
self.load_inventory_data() # Refresh inventory tab to show new quantities
def clear_sale(self):
self.current_sale_items.clear()
self.update_sales_table()
#Hashtags: #BusinessLogic #PointOfSale #PythonCode #Transaction
---
#Step 5: Results and DiscussionWith all the code in place, you have a fully functional pharmacy management system.
How to Use It:
• Run the
main.py script.• Go to the "Inventory Management" tab and add a few drugs with unique barcodes.
• Go to the "Point of Sale" tab. The cursor will be in the barcode input field.
• Type a barcode of a drug you added and press Enter. The drug will appear in the sales table.
• Scan the same barcode again. The quantity for that drug in the sales table will increase to 2.
• Click "Complete Sale". A success message will appear. The sales table will clear.
• Switch back to the "Inventory Management" tab. You will see that the quantity of the sold drugs has decreased accordingly.
❤2
Discussion and Potential Improvements:
Real Barcode Scanner: This application works directly with a USB barcode scanner. A scanner acts as a keyboard, so when it scans a code, it types the numbers and sends an "Enter" keystroke, which perfectly triggers our
Data Integrity: We added a basic check for stock (
Features for a Real Pharmacy: A production-level system would need many more features: prescription management, patient records, batch tracking for recalls, advanced reporting (e.g., top-selling drugs, low-stock alerts), user accounts with different permission levels, and receipt printing.
Database: SQLite is perfect for a single-user, standalone application. For a pharmacy with multiple terminals, a client-server database like PostgreSQL or MySQL would be necessary.
This project provides a solid foundation, demonstrating how to integrate hardware (like a barcode scanner) with a database-backed desktop application to solve a real-world business problem.
#ProjectComplete #SoftwareEngineering #PythonGUI #HealthTech
━━━━━━━━━━━━━━━
By: @DataScienceN ✨
Real Barcode Scanner: This application works directly with a USB barcode scanner. A scanner acts as a keyboard, so when it scans a code, it types the numbers and sends an "Enter" keystroke, which perfectly triggers our
returnPressed signal.Data Integrity: We added a basic check for stock (
quantity > 0). A more robust system would check if the quantity in the cart exceeds the quantity in stock before allowing the sale to complete.Features for a Real Pharmacy: A production-level system would need many more features: prescription management, patient records, batch tracking for recalls, advanced reporting (e.g., top-selling drugs, low-stock alerts), user accounts with different permission levels, and receipt printing.
Database: SQLite is perfect for a single-user, standalone application. For a pharmacy with multiple terminals, a client-server database like PostgreSQL or MySQL would be necessary.
This project provides a solid foundation, demonstrating how to integrate hardware (like a barcode scanner) with a database-backed desktop application to solve a real-world business problem.
#ProjectComplete #SoftwareEngineering #PythonGUI #HealthTech
━━━━━━━━━━━━━━━
By: @DataScienceN ✨
❤2
🔥 Trending Repository: nano-vllm
📝 Description: Nano vLLM
🔗 Repository URL: https://github.com/GeeeekExplorer/nano-vllm
📖 Readme: https://github.com/GeeeekExplorer/nano-vllm#readme
📊 Statistics:
🌟 Stars: 7.4K stars
👀 Watchers: 62
🍴 Forks: 949 forks
💻 Programming Languages: Python
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: Nano vLLM
🔗 Repository URL: https://github.com/GeeeekExplorer/nano-vllm
📖 Readme: https://github.com/GeeeekExplorer/nano-vllm#readme
📊 Statistics:
🌟 Stars: 7.4K stars
👀 Watchers: 62
🍴 Forks: 949 forks
💻 Programming Languages: Python
🏷️ Related Topics:
#nlp #deep_learning #inference #pytorch #transformer #llm
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: glow
📝 Description: Render markdown on the CLI, with pizzazz! 💅🏻
🔗 Repository URL: https://github.com/charmbracelet/glow
📖 Readme: https://github.com/charmbracelet/glow#readme
📊 Statistics:
🌟 Stars: 19.9K stars
👀 Watchers: 75
🍴 Forks: 480 forks
💻 Programming Languages: Go - Dockerfile
🏷️ Related Topics:
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: Render markdown on the CLI, with pizzazz! 💅🏻
🔗 Repository URL: https://github.com/charmbracelet/glow
📖 Readme: https://github.com/charmbracelet/glow#readme
📊 Statistics:
🌟 Stars: 19.9K stars
👀 Watchers: 75
🍴 Forks: 480 forks
💻 Programming Languages: Go - Dockerfile
🏷️ Related Topics:
#markdown #cli #hacktoberfest #excitement
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: hacker-scripts
📝 Description: Based on a true story
🔗 Repository URL: https://github.com/NARKOZ/hacker-scripts
📖 Readme: https://github.com/NARKOZ/hacker-scripts#readme
📊 Statistics:
🌟 Stars: 49K stars
👀 Watchers: 2.1k
🍴 Forks: 6.7K forks
💻 Programming Languages: JavaScript - Python - Java - Perl - Kotlin - Clojure
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: Based on a true story
🔗 Repository URL: https://github.com/NARKOZ/hacker-scripts
📖 Readme: https://github.com/NARKOZ/hacker-scripts#readme
📊 Statistics:
🌟 Stars: 49K stars
👀 Watchers: 2.1k
🍴 Forks: 6.7K forks
💻 Programming Languages: JavaScript - Python - Java - Perl - Kotlin - Clojure
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
🔥 Trending Repository: moon-dev-ai-agents
📝 Description: autonomous ai agents for trading in python
🔗 Repository URL: https://github.com/moondevonyt/moon-dev-ai-agents
🌐 Website: https://algotradecamp.com
📖 Readme: https://github.com/moondevonyt/moon-dev-ai-agents#readme
📊 Statistics:
🌟 Stars: 2.2K stars
👀 Watchers: 100
🍴 Forks: 1.1K forks
💻 Programming Languages: Python - HTML
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM
📝 Description: autonomous ai agents for trading in python
🔗 Repository URL: https://github.com/moondevonyt/moon-dev-ai-agents
🌐 Website: https://algotradecamp.com
📖 Readme: https://github.com/moondevonyt/moon-dev-ai-agents#readme
📊 Statistics:
🌟 Stars: 2.2K stars
👀 Watchers: 100
🍴 Forks: 1.1K forks
💻 Programming Languages: Python - HTML
🏷️ Related Topics: Not available
==================================
🧠 By: https://t.iss.one/DataScienceM