Python | Machine Learning | Coding | R
66.5K subscribers
1.2K photos
84 videos
151 files
870 links
Help and ads: @hussein_sheikho

Discover powerful insights with Python, Machine Learning, Coding, and Rโ€”your essential toolkit for data-driven solutions, smart alg

List of our channels:
https://t.iss.one/addlist/8_rRW2scgfRhOTc0

https://telega.io/?r=nikapsOH
Download Telegram
Python | Machine Learning | Coding | R
Photo
# ๐Ÿ“š Python Tutorial: Convert EPUB to PDF (Preserving Images)
#Python #EPUB #PDF #EbookConversion #Automation

This comprehensive guide will show you how to convert EPUB files (including those with images) to high-quality PDFs using Python.

---

## ๐Ÿ”น Required Tools & Libraries
We'll use these Python packages:
- ebooklib - For EPUB parsing
- pdfkit (wrapper for wkhtmltopdf) - For PDF generation
- Pillow - For image handling (optional)

pip install ebooklib pdfkit pillow


Also install system dependencies:
# On Ubuntu/Debian
sudo apt-get install wkhtmltopdf

# On MacOS
brew install wkhtmltopdf

# On Windows (download from wkhtmltopdf.org)


---

## ๐Ÿ”น Step 1: Extract EPUB Contents
First, we'll unpack the EPUB file to access its HTML and images.

from ebooklib import epub
from bs4 import BeautifulSoup
import os

def extract_epub(epub_path, output_dir):
book = epub.read_epub(epub_path)

# Create output directory
os.makedirs(output_dir, exist_ok=True)

# Extract all items (chapters, images, styles)
for item in book.get_items():
if item.get_type() == epub.ITEM_IMAGE:
# Save images
with open(os.path.join(output_dir, item.get_name()), 'wb') as f:
f.write(item.get_content())
elif item.get_type() == epub.ITEM_DOCUMENT:
# Save HTML chapters
with open(os.path.join(output_dir, item.get_name()), 'wb') as f:
f.write(item.get_content())

return [item.get_name() for item in book.get_items() if item.get_type() == epub.ITEM_DOCUMENT]


---

## ๐Ÿ”น Step 2: Convert HTML to PDF
Now we'll convert the extracted HTML files to PDF while preserving images.

import pdfkit
from PIL import Image # For image validation (optional)

def html_to_pdf(html_files, output_pdf, base_dir):
options = {
'encoding': "UTF-8",
'quiet': '',
'enable-local-file-access': '', # Critical for local images
'no-outline': None,
'margin-top': '15mm',
'margin-right': '15mm',
'margin-bottom': '15mm',
'margin-left': '15mm',
}

# Validate images (optional)
for html_file in html_files:
soup = BeautifulSoup(open(os.path.join(base_dir, html_file)), 'html.parser')
for img in soup.find_all('img'):
img_path = os.path.join(base_dir, img['src'])
try:
Image.open(img_path) # Validate image
except Exception as e:
print(f"Image error in {html_file}: {e}")
img.decompose() # Remove broken images

# Convert to PDF
pdfkit.from_file(
[os.path.join(base_dir, f) for f in html_files],
output_pdf,
options=options
)


---

## ๐Ÿ”น Step 3: Complete Conversion Function
Combine everything into a single workflow.

def epub_to_pdf(epub_path, output_pdf, temp_dir="temp_epub"):
try:
print(f"Converting {epub_path} to PDF...")

# Step 1: Extract EPUB
print("Extracting EPUB contents...")
html_files = extract_epub(epub_path, temp_dir)

# Step 2: Convert to PDF
print("Generating PDF...")
html_to_pdf(html_files, output_pdf, temp_dir)

print(f"Success! PDF saved to {output_pdf}")
return True

except Exception as e:
print(f"Conversion failed: {str(e)}")
return False
finally:
# Clean up temporary files
if os.path.exists(temp_dir):
import shutil
shutil.rmtree(temp_dir)


---

## ๐Ÿ”น Advanced Options
### 1. Custom Styling
Add CSS to improve PDF appearance:

def html_to_pdf(html_files, output_pdf, base_dir):
options = {
# ... previous options ...
'user-style-sheet': 'styles.css', # Custom CSS
}

# Create CSS file if needed
css = """
body { font-family: "Times New Roman", serif; font-size: 12pt; }
img { max-width: 100%; height: auto; }
"""
with open(os.path.join(base_dir, 'styles.css'), 'w') as f:
f.write(css)

pdfkit.from_file(/* ... */)
โค10๐Ÿ”ฅ2๐ŸŽ‰1
Python | Machine Learning | Coding | R
Photo
### 2. Handling Complex EPUBs
For problematic EPUBs, try this pre-processing:

def clean_html(html_file):
with open(html_file, 'r+', encoding='utf-8') as f:
content = f.read()
soup = BeautifulSoup(content, 'html.parser')

# Remove problematic elements
for element in soup(['script', 'iframe', 'object']):
element.decompose()

# Fix image paths
for img in soup.find_all('img'):
if not os.path.isabs(img['src']):
img['src'] = os.path.abspath(os.path.join(os.path.dirname(html_file), img['src']))

# Write back cleaned HTML
f.seek(0)
f.write(str(soup))
f.truncate()


---

## ๐Ÿ”น Full Usage Example
if __name__ == "__main__":
import argparse

parser = argparse.ArgumentParser(description='Convert EPUB to PDF')
parser.add_argument('epub_file', help='Input EPUB file path')
parser.add_argument('pdf_file', help='Output PDF file path')
args = parser.parse_args()

success = epub_to_pdf(args.epub_file, args.pdf_file)
if not success:
exit(1)


Run from command line:
python epub_to_pdf.py input.epub output.pdf


---

## ๐Ÿ”น Troubleshooting Common Issues
| Problem | Solution |
|---------|----------|
| Missing images | Ensure enable-local-file-access is set |
| Broken CSS paths | Use absolute paths in CSS references |
| Encoding issues | Specify UTF-8 in both HTML and pdfkit options |
| Large file sizes | Optimize images before conversion |
| Layout problems | Add CSS media queries for print |

---

## ๐Ÿ”น Alternative Libraries
If pdfkit doesn't meet your needs:

1. WeasyPrint (pure Python)

   pip install weasyprint


2. PyMuPDF (fitz)

   pip install pymupdf


3. Calibre's ebook-convert CLI

   ebook-convert input.epub output.pdf


---

## ๐Ÿ”น Best Practices
1. Always clean temporary files after conversion
2. Validate input EPUBs before processing
3. Handle metadata (title, author, etc.)
4. Batch process multiple files with threading
5. Log conversion results for debugging

---

### ๐Ÿ“š Final Notes
This solution preserves:
โœ”๏ธ All images in original quality
โœ”๏ธ Chapter structure and formatting
โœ”๏ธ Text encoding and special characters

For production use, consider adding:
- Progress tracking
- Parallel conversion of chapters
- EPUB metadata preservation
- Custom cover page support

#PythonAutomation #EbookTools #PDFConversion ๐Ÿš€

Try enhancing this script by:
1. Adding a progress bar
2. Preserving table of contents
3. Supporting custom cover pages
4. Creating a GUI version

https://t.iss.one/CodeProgrammer โค๏ธ
โค16
This channels is for Programmers, Coders, Software Engineers.

0๏ธโƒฃ Python
1๏ธโƒฃ Data Science
2๏ธโƒฃ Machine Learning
3๏ธโƒฃ Data Visualization
4๏ธโƒฃ Artificial Intelligence
5๏ธโƒฃ Data Analysis
6๏ธโƒฃ Statistics
7๏ธโƒฃ Deep Learning
8๏ธโƒฃ programming Languages

โœ… https://t.iss.one/addlist/8_rRW2scgfRhOTc0

โœ… https://t.iss.one/Codeprogrammer
Please open Telegram to view this post
VIEW IN TELEGRAM
โค6๐Ÿ’ฏ2
Please open Telegram to view this post
VIEW IN TELEGRAM
โค5
๐Ÿ“š JaidedAI/EasyOCR โ€” an open-source Python library for Optical Character Recognition (OCR) that's easy to use and supports over 80 languages out of the box.

### ๐Ÿ” Key Features:

๐Ÿ”ธ Extracts text from images and scanned documents โ€” including handwritten notes and unusual fonts
๐Ÿ”ธ Supports a wide range of languages like English, Russian, Chinese, Arabic, and more
๐Ÿ”ธ Built on PyTorch โ€” uses modern deep learning models (not the old-school Tesseract)
๐Ÿ”ธ Simple to integrate into your Python projects

### โœ… Example Usage:

import easyocr

reader = easyocr.Reader(['en', 'ru']) # Choose supported languages
result = reader.readtext('image.png')


### ๐Ÿ“Œ Ideal For:

โœ… Text extraction from photos, scans, and documents
โœ… Embedding OCR capabilities in apps (e.g. automated data entry)

๐Ÿ”— GitHub: https://github.com/JaidedAI/EasyOCR

๐Ÿ‘‰ Follow us for more: @DataScienceN

#Python #OCR #MachineLearning #ComputerVision #EasyOCR
โค3๐Ÿ‘Ž1๐ŸŽ‰1
Transformer Lesson - Part 1/7: Introduction and Architecture

Let's start:
https://hackmd.io/@husseinsheikho/transformers

โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
โค7๐Ÿ‘3
๐Ÿ”ฅ Master Vision Transformers with 65+ MCQs! ๐Ÿ”ฅ

Are you preparing for AI interviews or want to test your knowledge in Vision Transformers (ViT)?

๐Ÿง  Dive into 65+ curated Multiple Choice Questions covering the fundamentals, architecture, training, and applications of ViT โ€” all with answers!

๐ŸŒ Explore Now: https://hackmd.io/@husseinsheikho/vit-mcq

๐Ÿ”น Table of Contents
Basic Concepts (Q1โ€“Q15)
Architecture & Components (Q16โ€“Q30)
Attention & Transformers (Q31โ€“Q45)
Training & Optimization (Q46โ€“Q55)
Advanced & Real-World Applications (Q56โ€“Q65)
Answer Key & Explanations

#VisionTransformer #ViT #DeepLearning #ComputerVision #Transformers #AI #MachineLearning #MCQ #InterviewPrep


โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
โค5
This media is not supported in your browser
VIEW IN TELEGRAM
๐Ÿงน ObjectClear โ€” an AI-powered tool for removing objects from images effortlessly.

โš™๏ธ What It Can Do:

๐Ÿ–ผ๏ธ Upload any image
๐ŸŽฏ Select the object you want to remove
๐ŸŒŸ The model automatically erases the object and intelligently reconstructs the background

โšก๏ธ Under the Hood:

โ€” Uses Segment Anything (SAM) by Meta for object segmentation
โ€” Leverages Inpaint-Anything for realistic background generation
โ€” Works in your browser with an intuitive Gradio UI

โœ”๏ธ Fully open-source and can be run locally.

๐Ÿ“Ž GitHub: https://github.com/zjx0101/ObjectClear

#AI #ImageEditing #ComputerVision #Gradio #OpenSource #Python


โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
โค10
๐Ÿš€ Comprehensive Tutorial: Build a Folder Monitoring & Intruder Detection System in Python

In this comprehensive, step-by-step tutorial, you will learn how to build a real-time folder monitoring and intruder detection system using Python.

๐Ÿ” Your Goal:
Create a background program that:
- Monitors a specific folder on your computer.
- Instantly captures a photo using the webcam whenever someone opens that folder.
- Saves the photo with a timestamp in a secure folder.
- Runs automatically when Windows starts.
- Keeps running until you manually stop it (e.g., via Task Manager or a hotkey).

Read and get code: https://hackmd.io/@husseinsheikho/Build-a-Folder-Monitoring

#Python #Security #FolderMonitoring #IntruderDetection #OpenCV #FaceCapture #Automation #Windows #TaskScheduler #ComputerVision


โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
โค7๐Ÿ”ฅ1๐ŸŽ‰1
๐Ÿš€ Comprehensive Guide: How to Prepare for an Image Processing Job Interview โ€“ 500 Most Common Interview Questions

Let's start: https://hackmd.io/@husseinsheikho/IP

#ImageProcessing #ComputerVision #OpenCV #Python #InterviewPrep #DigitalImageProcessing #MachineLearning #AI #SignalProcessing #ComputerGraphics

โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
โค4๐Ÿ‘Ž1๐Ÿ”ฅ1
A useful find on GitHub CheatSheets-for-Developers

LINK: https://github.com/crescentpartha/CheatSheets-for-Developers

This is a huge collection of cheat sheets for a wide variety of technologies:

JavaScript, Python, Git, Docker, SQL, Linux, Regex, and many others.


Conveniently structured โ€” you can quickly find the topic you need.

Save it and use it ๐Ÿ”ฅ

๐Ÿ‘‰ @DATASCIENCEN
Please open Telegram to view this post
VIEW IN TELEGRAM
โค4๐Ÿ‘2
5 minutes of work - 127,000$ profit!

Opened access to the Jay Welcome Club where the AI bot does all the work itself๐Ÿ’ป

Usually you pay crazy money to get into this club, but today access is free for everyone!

23,432% on deposit earned by club members in the last 6 months๐Ÿ“ˆ

Just follow Jay's trades and earn! ๐Ÿ‘‡

https://t.iss.one/+mONXtEgVxtU5NmZl
โค3
Join our WhatsApp channel

There are dedicated resources only for WhatsApp users

https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
โค3
๐Ÿš€ Comprehensive Guide: How to Prepare for a Graph Neural Networks (GNN) Job Interview โ€“ 350 Most Common Interview Questions

Read: https://hackmd.io/@husseinsheikho/GNN-interview

#GNN #GraphNeuralNetworks #MachineLearning #DeepLearning #AI #DataScience #PyTorchGeometric #DGL #NodeClassification #LinkPrediction #GraphML

โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
โค8
This repo is awesome. It features RAG, AI Agents, Multi-agent Teams, MCP, Voice Agents, and more.

โœ… link: https://github.com/Shubhamsaboo/awesome-llm-apps

#RAG #AIAgents #MultiAgentSystems #VoiceAI #LLMApps


โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
1โค5๐Ÿ”ฅ5๐Ÿ‘1
500 Essential Web Scraping Interview Questions

Start: https://hackmd.io/@husseinsheikho/WS-Interview

โœ‰๏ธ Our Telegram channels: https://t.iss.one/addlist/0f6vfFbEMdAwODBk

๐Ÿ“ฑ Our WhatsApp channel: https://whatsapp.com/channel/0029VaC7Weq29753hpcggW2A
Please open Telegram to view this post
VIEW IN TELEGRAM
โค5๐Ÿ‘4
This media is not supported in your browser
VIEW IN TELEGRAM
This repository contains a collection of everything needed to work with libraries related to AI and LLM.

More than 120 libraries, sorted by stages of LLM development:

โ†’ Training, fine-tuning, and evaluation of LLM models
โ†’ Integration and deployment of applications with LLM and RAG
โ†’ Fast and scalable model launching
โ†’ Working with data: extraction, structuring, and synthetic generation
โ†’ Creating autonomous agents based on LLM
โ†’ Prompt optimization and ensuring safe use in production

๐ŸŒŸ link: https://github.com/Shubhamsaboo/awesome-llm-apps

๐Ÿ‘‰ @codeprogrammer
Please open Telegram to view this post
VIEW IN TELEGRAM
โค7๐Ÿ’ฏ3