Python/ django
58.9K subscribers
2.08K photos
61 videos
47 files
2.79K links
по всем вопросам @haarrp

@itchannels_telegram - 🔥 все ит-каналы

@ai_machinelearning_big_data -ML

@ArtificialIntelligencedl -AI

@datascienceiot - 📚

@pythonlbooks

РКН: clck.ru/3FmxmM
加入频道
🟡 This week's digest of useful content from the world of Python

Дайджест полезных материалов из мира Python за неделю.

Почитать:

Разработка событийно-ориентированных микросервисов с помощью Python
Бережем время, деньги, нервы: наш опыт улучшения справочника факторов для ML-моделей оценки риска. Часть 2
Я люблю питон, и вот почему он меня бесит
Список популярных утечек с GitHub: Анализ репозиториев компаний
PyCon Russia 2023. Зона Python. Краткий обзор докладов
Менеджеры контекста в Python
Что происходит, когда запускаешь «Hello World» в Linux
Ускорение кода с помощью многопроцессорной обработки в Python
Руководство по созданию бота YouTube с помощью LangChain и Pinecone Vectorstore
Перехват FTP-пароля с помощью Python
Как Python использует сборку мусора для эффективного управления памятью
Converting An Image File Into PDF Using Python
Introducing Kids to Coding Through Tkinter: A Fun Path to Python's Graphical User Interfaces

Посмотреть:

🌐Как работать с декораторами в Python. Часть 1
🌐 Методы сокращения и улучшения кода на Python
🌐 Продвинутые методы улучшения кода на Python
🌐 Создаем продвинутый интерфейс на Python
🌐 Harvard CS50’s Artificial Intelligence with Python – Full University Course

Хорошего дня!

@pythonl
Media is too big
VIEW IN TELEGRAM
🎼 AudioLDM 2: A General Framework for Audio, Music, and Speech Generation

AudioLDM 2: Нейросеть, создающая музыку из текстового описания.

conda create -n audioldm python=3.8; conda activate audioldm
pip3 install git+https://github.com/haoheliu/AudioLDM2.git
git clone https://github.com/haoheliu/AudioLDM2; cd AudioLDM2

python3 app.py

Github
Demo

@pythonl
👱‍♂️ Creating Face Swaps with Python and OpenCV

Скрипт замены лиц с помощью Python и OpenCV.

Step 1: Face Detection
import cv2
def detect_face(image_path):
# Load the face detection classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Read and convert the image to grayscale
image = cv2.imread(image_path)
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Detect faces in the image
faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5)

# Assuming there's only one face in the image, return its coordinates
if len(faces) == 1:
return faces[0]
else:
return None


Step 2: Swapping Faces

def main():
# Paths to the input images
image_path_1 = 'path_to_image1.jpg'
image_path_2 = 'path_to_image2.jpg'

# Detect the face in the second image
face_coords_2 = detect_face(image_path_2)
if face_coords_2 is None:
print("No face found in the second image.")
return

# Load and resize the source face
image_1 = cv2.imread(image_path_1)
face_width, face_height = face_coords_2[2], face_coords_2[3]
image_1_resized = cv2.resize(image_1, (face_width, face_height))

# Extract the target face region from the second image
image_2 = cv2.imread(image_path_2)
roi = image_2[face_coords_2[1]:face_coords_2[1] + face_height, face_coords_2[0]:face_coords_2[0] + face_width]

# Flip the target face horizontally
reflected_roi = cv2.flip(roi, 1)

# Blend the two faces together
alpha = 0.7
blended_image = cv2.addWeighted(image_1_resized, alpha, reflected_roi, 1 - alpha, 0)

# Replace the target face region with the blended image
image_2[face_coords_2[1]:face_coords_2[1] + face_height, face_coords_2[0]:face_coords_2[0] + face_width] = blended_image

# Display the result
cv2.imshow('Blended Image', image_2)
cv2.waitKey(0)
cv2.destroyAllWindows()

if __name__ == "__main__":
main()


@pythonl
🖥 Text-to-Speech with PyTorch

Преобразование текста в речь с помощью PyTorch.

import torchaudio
import torch
import matplotlib.pyplot as plt
import IPython.display

bundle = torchaudio.pipelines.TACOTRON2_WAVERNN_PHONE_LJSPEECH

processor = bundle.get_text_processor()
tacotron2 = bundle.get_tacotron2().to(device) # Move model to the desired device
vocoder = bundle.get_vocoder().to(device) # Move model to the desired device

text = " My first text to speech!"

with torch.inference_mode():
processed, lengths = processor(text)
processed = processed.to(device) # Move processed text data to the device
lengths = lengths.to(device) # Move lengths data to the device
spec, spec_lengths, _ = tacotron2.infer(processed, lengths)
waveforms, lengths = vocoder(spec, spec_lengths)


fig, [ax1, ax2] = plt.subplots(2, 1, figsize=(16, 9))
ax1.imshow(spec[0].cpu().detach(), origin="lower", aspect="auto") # Display the generated spectrogram
ax2.plot(waveforms[0].cpu().detach()) # Display the generated waveform7. Play the generated audio using IPython.display.Audio
IPython.display.Audio(waveforms[0:1].cpu(), rate=vocoder.sample_rate)

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Automate the Mundane: How Python Scripts Transform Tedious Tasks

Автоматическая организация файлов в папке загрузок, в зависимости от их типа.

import os
import shutil

# Paths
DOWNLOADS_PATH = os.path.expanduser('~/Downloads') # Modify this if your downloads are in a different location
ORGANIZED_PATHS = {
'Documents': ['.pdf', '.doc', '.docx', '.txt', '.md', '.xlsx', '.ppt'],
'Images': ['.jpg', '.jpeg', '.gif', '.png', '.svg'],
'Music': ['.mp3', '.wav', '.wma', '.ogg', '.flac', '.aac'],
'Videos': ['.mp4', '.mkv', '.flv', '.mov', '.avi'],
'Archives': ['.zip', '.tar', '.tar.gz', '.rar', '.7z'],
}

def organize_downloads():
for filename in os.listdir(DOWNLOADS_PATH):
file_path = os.path.join(DOWNLOADS_PATH, filename)

# Ensure we're working with files only
if not os.path.isfile(file_path):
continue

# Find the file's type based on its extension
file_type = None
for folder, extensions in ORGANIZED_PATHS.items():
for extension in extensions:
if filename.endswith(extension):
file_type = folder
break
if file_type:
break

# Move the file to its designated folder
if file_type:
dest_folder = os.path.join(DOWNLOADS_PATH, file_type)
os.makedirs(dest_folder, exist_ok=True)
shutil.move(file_path, os.path.join(dest_folder, filename))
else:
# You can add a category for uncategorized files if needed
pass

if __name__ == "__main__":
organize_downloads()


@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 ItsDangerous

To ensure the safety of passing data to untrusted environments, use ItsDangerous. ItsDangerous adds a unique signature to the data to verify that the data has not been tampered.

При передаче данных между различными веб-запросами существует риск инъекции вредоносного кода.

Для обеспечения безопасности передачи данных в по API следует использовать ItsDangerous. ItsDangerous добавляет к данным уникальную подпись, которая позволяет убедиться в том, что данные не были подделаны.

pip install -U itsdangerous


from itsdangerous import URLSafeSerializer
auth_s = URLSafeSerializer("secret key", "auth")
token = auth_s.dumps({"id": 5, "name": "itsdangerous"})

print(token)
# eyJpZCI6NSwibmFtZSI6Iml0c2Rhbmdlcm91cyJ9.6YP6T0BaO67XP--9UzTrmurXSmg

data = auth_s.loads(token)
print(data["name"])
# itsdangerous


Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥Pytest-postgresql

This is a pytest plugin, that enables you to test your code that relies on a running PostgreSQL Database.

Это плагин pytest, позволяющий тестировать код, основанный на базе данных PostgreSQL. Он позволяет задавать фикстуры для PostgreSQL.

pip install pytest-postgresql

Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Легкий способ получать свежие обновлении и следить за трендами в разработке на вашем языке. Находите свой стек и подписывайтесь:


Машинное обучение: @ai_machinelearning_big_data
Go: @Golang_google
C#: @csharp_ci
Базы данных: @sqlhub
Python: @python_job_interview
C/C++/: @cpluspluc
Data Science: @data_analysis_ml
Devops: @devOPSitsec
Rust: @rust_code
Javascript: @javascriptv
React: @react_tg
PHP: @phpshka
Docker: @docker
Android: @android_its
Мобильная разработка: @mobdevelop
Linux: linuxacademy
Big Data: t.me/bigdatai
Хакинг: @linuxkalii
Java:@javatg
Собеседования: @machinelearning_interview


💼 Папка с вакансиями: t.me/addlist/_zyy_jQ_QUsyM2Vi
Папка Go разработчика: t.me/addlist/MUtJEeJSxeY2YTFi
Папка Python разработчика: t.me/addlist/eEPya-HF6mkxMGIy

🔥ИТ-Мемы: t.me/memes_prog

🇬🇧Английский: @english_forprogrammers

📕Ит-книги https://yangx.top/addlist/BkskQciUW_FhNjEy
🔍Building a Python QR Scanner to Generate Characters

Создание QR-сканера на языке Python для генерации символов.

@Pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 PostgresML

PostgresML is a machine learning extension for PostgreSQL that enables you to perform training and inference on text and tabular data using SQL queries.

PostgresML - это расширение машинного обучения для PostgreSQL, позволяющее выполнять обучение и выводы на текстовых и табличных данных с помощью SQL-запросов.

Github

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
A Complete Guide to Using Multiple Databases in Django

Руководство по использованию нескольких баз данных в Django.

@pythonl