├── android_automation.py ├── background_img_remove.py ├── blurring_background_img.py ├── compres_pdf.py ├── compress_video.py ├── create_presentation.py ├── cut_url.py ├── cut_video.py ├── desctope_automation.py ├── download_files_from_url.py ├── encryprion_decription.py ├── excell_automation.py ├── fetch_html_css_js.py ├── from_csv_to_json.py ├── from_json_to_csv.py ├── from_mp4_to_gif.py ├── from_pdf_to_audio_book.py ├── from_pdf_to_docx.py ├── gazpacho_soup_html.py ├── generate_fake_person.py ├── generate_qr_code.py ├── google_news.py ├── images_extraction_from_pdf.py ├── insta_bot.py ├── instaloader.py ├── merge_pdf_in_directory.py ├── mp4_to_mp3.py ├── multiple_email_sender.py ├── news_catcher_api.py ├── open_ai_api.py ├── playlist_youtube_downloader.py ├── proxy_checker.py ├── py_tg_bot_api.py ├── remove_background.py ├── remove_background_of_images_api.py ├── send_discord_webhooks.py ├── use_py_script_in_html.py ├── video_cropper.py ├── work_with_json.py ├── work_with_xlsx.py └── youtube_downloader.py /android_automation.py: -------------------------------------------------------------------------------- 1 | # Automate Mobile Phones 2 | # pip install opencv-python 3 | 4 | import subprocess 5 | 6 | def main_adb(cm): 7 | p = subprocess.Popen(cm.split(' '), stdout=subprocess.PIPE, shell=True) 8 | (output, _) = p.communicate() 9 | return output.decode('utf-8') 10 | 11 | # Swipe 12 | def swipe(x1, y1, x2, y2, duration): 13 | cmd = 'adb shell input swipe {} {} {} {} {}'.format(x1, y1, x2, y2, duration) 14 | return main_adb(cmd) 15 | 16 | # Tap or Clicking 17 | def tap(x, y): 18 | cmd = 'adb shell input tap {} {}'.format(x, y) 19 | return main_adb(cmd) 20 | 21 | # Make a Call 22 | def make_call(number): 23 | cmd = f"adb shell am start -a android.intent.action.CALL -d tel:{number}" 24 | return main_adb(cmd) 25 | 26 | # Send SMS 27 | def send_sms(number, message): 28 | cmd = 'adb shell am start -a android.intent.action.SENDTO -d sms:{} --es sms_body "{}"'.format(number, message) 29 | return main_adb(cmd) 30 | 31 | # Download File From Mobile to PC 32 | def download_file(file_name): 33 | cmd = 'adb pull /sdcard/{}'.format(file_name) 34 | return main_adb(cmd) 35 | 36 | # Take a screenshot 37 | def screenshot(): 38 | cmd = 'adb shell screencap -p' 39 | return main_adb(cmd) 40 | 41 | # Power On and Off 42 | def power_off(): 43 | cmd = '"adb shell input keyevent 26"' 44 | return main_adb(cmd) 45 | -------------------------------------------------------------------------------- /background_img_remove.py: -------------------------------------------------------------------------------- 1 | # pip install rembg Pillow 2 | 3 | from rembg import remove 4 | from PIL import Image 5 | 6 | input_path = 'image.png' 7 | background_path = 'background.jpg' 8 | output_path = 'image_output.png' 9 | 10 | open_image = Image.open(input_path) 11 | output = remove(open_image) 12 | 13 | background = Image.open(background_path) 14 | 15 | background = background.resize(output.size) 16 | 17 | background.paste(output, (0, 0), output) 18 | 19 | background.save(output_path) 20 | -------------------------------------------------------------------------------- /blurring_background_img.py: -------------------------------------------------------------------------------- 1 | # pip install opencv-python mediapipe numpy 2 | 3 | import cv2 4 | import mediapipe as mp 5 | import numpy as np 6 | 7 | # Инициализация Mediapipe Selfie Segmentation 8 | mp_selfie_segmentation = mp.solutions.selfie_segmentation 9 | 10 | # Загрузка изображения 11 | image_path = 'image.png' 12 | image = cv2.imread(image_path) 13 | height, width, _ = image.shape 14 | 15 | # Создание копии изображения для размывания фона 16 | blurred_image = cv2.GaussianBlur(image, (21, 21), 0) 17 | 18 | # Инициализация Selfie Segmentation 19 | with mp_selfie_segmentation.SelfieSegmentation(model_selection=1) as selfie_segmentation: 20 | # Обработка изображения 21 | results = selfie_segmentation.process(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) 22 | 23 | # Создание маски для области человека 24 | mask = results.segmentation_mask > 0.5 25 | mask = mask.astype(np.uint8) * 255 26 | 27 | # Инвертирование маски для фона 28 | background_mask = cv2.bitwise_not(mask) 29 | 30 | # Извлечение фона и размывание его 31 | background_blurred = cv2.bitwise_and(blurred_image, blurred_image, mask=background_mask) 32 | 33 | # Извлечение человека из исходного изображения 34 | person = cv2.bitwise_and(image, image, mask=mask) 35 | 36 | # Объединение размытого фона и человека 37 | final_image = cv2.add(background_blurred, person) 38 | 39 | # Сохранение результата 40 | output_path = 'output.jpg' 41 | cv2.imwrite(output_path, final_image) 42 | 43 | cv2.waitKey(0) 44 | cv2.destroyAllWindows() 45 | -------------------------------------------------------------------------------- /compres_pdf.py: -------------------------------------------------------------------------------- 1 | # Code snippet is using the ConvertAPI Python Client: https://github.com/ConvertAPI/convertapi-python 2 | 3 | convertapi.api_secret = 'your-api-secret' 4 | convertapi.convert('compress', { 5 | 'File': '/path/to/my_file.pdf' 6 | }, from_format = 'pdf').save_files('/path/to/dir') 7 | -------------------------------------------------------------------------------- /compress_video.py: -------------------------------------------------------------------------------- 1 | # pip install moviepy 2 | 3 | from moviepy.editor import VideoFileClip 4 | 5 | 6 | def compress_video(input_file, output_file, target_bitrate): 7 | # Загрузка видеофайла 8 | video = VideoFileClip(input_file) 9 | # Изменение размера видео до высоты 360 пикселей 10 | video = video.resize(height=360) 11 | # Запись сжатого видеофайла с указанным битрейтом и кодеком "libx264" 12 | video.write_videofile(output_file, bitrate=target_bitrate, codec="libx264") 13 | 14 | 15 | # Сжатие видео "video.mp4" и сохранение его в файле "output_video.mp4" с целевым битрейтом "1000k" 16 | compress_video("video.mp4", "output_video.mp4", "1000k") 17 | -------------------------------------------------------------------------------- /create_presentation.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import collections.abc 3 | 4 | from pptx import Presentation 5 | from pptx.util import Inches 6 | 7 | # Slide content 8 | slide_content = [ 9 | ("Introduction", "Phosphorus in Plant Nutrition\n\n- Essential nutrient for plant growth and development.\n- Soil phosphorus content impacts plant yield and quality of agricultural products."), 10 | ("Phosphorus Uptake by Plants", "Amount of phosphorus consumed by plants during vegetation.\nExample: Wheat consumes 10-12 kg of phosphorus per 1 ton of grain."), 11 | ("Phosphorus Fertilizers", "Role of Phosphate Fertilizers\n\n- To replenish phosphorus in soil for plant growth.\n- Necessary due to rapid binding of phosphorus in soil."), 12 | ] 13 | 14 | # Create a PowerPoint presentation 15 | prs = Presentation() 16 | 17 | # Loop through the slide content and create slides 18 | for title, content in slide_content: 19 | slide = prs.slides.add_slide(prs.slide_layouts[5]) 20 | title_shape = slide.shapes.title 21 | title_shape.text = title 22 | 23 | left = Inches(1) 24 | top = Inches(2) 25 | width = Inches(8) 26 | height = Inches(5.5) 27 | 28 | textbox = slide.shapes.add_textbox(left, top, width, height) 29 | text_frame = textbox.text_frame 30 | 31 | p = text_frame.add_paragraph() 32 | p.text = content 33 | 34 | # Save the presentation 35 | prs.save("presentation.pptx") 36 | print("Presentation created and saved as 'presentation.pptx'.") 37 | -------------------------------------------------------------------------------- /cut_url.py: -------------------------------------------------------------------------------- 1 | from __future__ import with_statement 2 | import contextlib 3 | 4 | try: 5 | from urllib.parse import urlencode 6 | except ImportError: 7 | from urllib import urlencodetry 8 | from urllib.request import urlopen 9 | except ImportError: 10 | from urllib2 import urlopenimport sys 11 | 12 | 13 | def make_tiny(url): 14 | request_url = ('http://tinyurl.com/api-create.php?' + urlencode({'url':url})) 15 | 16 | with contextlib.closing(urlopen(request_url)) as response: 17 | return response.read().decode('utf-8') 18 | 19 | def main(): 20 | for tinyurl in map(make_tiny, sys.argv[1:]): 21 | print(tinyurl) 22 | 23 | if __name__ == '__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /cut_video.py: -------------------------------------------------------------------------------- 1 | from moviepy.editor import * 2 | 3 | 4 | def cut_video(input_file, start_time, end_time, output_file): 5 | '''time in sec''' 6 | video = VideoFileClip(input_file) 7 | trimmed_video = video.subclip(start_time, end_time) 8 | trimmed_video.write_videofile(output_file, codec="libx264", audio_codec="aac") 9 | 10 | cut_video("1.mp4", 300, 3264, "1-cutted.mp4") 11 | -------------------------------------------------------------------------------- /desctope_automation.py: -------------------------------------------------------------------------------- 1 | # Automate Desktop App 2 | 3 | # pip install ahk 4 | from ahk import AHK 5 | from ahk.window import Window 6 | 7 | 8 | auto = AHK() 9 | 10 | # Do Mouse Actions 11 | auto.mouse_move(100, 100) 12 | auto.mouse_down(button='left') 13 | auto.mouse_up(button='left') 14 | auto.click() 15 | auto.double_click() 16 | auto.right_click() 17 | auto.mouse_position() 18 | auto.mouse_drag(100, 100, 200, 200) 19 | 20 | # Do Keyboard Actions 21 | auto.key_press('a') 22 | auto.key_down('a') 23 | auto.type('Hello World') 24 | 25 | # Get Active Window 26 | active = auto.active_window() 27 | print(active) 28 | 29 | # List of Windows 30 | windows = auto.windows() 31 | 32 | # Open a Window 33 | window = auto.run_script('notepad.exe') 34 | 35 | # Give focus to window 36 | window.focus() 37 | 38 | # Kill or Terminate a Window 39 | window.kill()# 40 | 41 | Maimize or Maximize a Window 42 | window.maximize() 43 | window.minimize() 44 | 45 | # Search an image on the screen 46 | cord = auto.image_search('image.png') 47 | print(cord) 48 | -------------------------------------------------------------------------------- /download_files_from_url.py: -------------------------------------------------------------------------------- 1 | # Download Files from URL 2 | 3 | url = "https://instagram.com/favicon.ico" 4 | 5 | # Method 1 6 | # pip install requests 7 | 8 | import requests 9 | 10 | r = requests.get(url) 11 | 12 | with open("favicon.ico", "wb") as f: 13 | f.write(r.content) 14 | 15 | # Method 2 16 | # pip install wget 17 | 18 | import wget 19 | 20 | r = wget.download(url, "favicon.ico") 21 | 22 | # Method 3 23 | # pip install urllib3 24 | 25 | import urllib.request 26 | 27 | urllib.request.urlretrieve(url, "favicon.ico") 28 | -------------------------------------------------------------------------------- /encryprion_decription.py: -------------------------------------------------------------------------------- 1 | # File Encrypytion and Decryption 2 | # pip install pyAesCrypt 3 | 4 | import pyAesCrypt 5 | 6 | def Encrypt_File(filename, password): 7 | pyAesCrypt.encryptFile(filename, filename + ".aes", password) 8 | print("File Encrypted") 9 | 10 | def Decrypt_File(filename, password): 11 | pyAesCrypt.decryptFile(filename + ".aes", filename, password) 12 | print("File Decrypted") 13 | 14 | Encrypt_File("test.py", "pass1243") 15 | Decrypt_File("test.py.aes", "pass1243") 16 | -------------------------------------------------------------------------------- /excell_automation.py: -------------------------------------------------------------------------------- 1 | # Automate Excel Files 2 | # pip install xlwings 3 | 4 | import xlwings as ex 5 | 6 | wb = ex.Book("test.xlsx") 7 | ws = wb.sheets[0] 8 | 9 | # Read Data Cell 10 | print(ws.range("A1").value) 11 | 12 | # Read Data Row 13 | print(ws.range("A1:A3").value) 14 | 15 | # Read Data Column 16 | print(ws.range("A1:C3").value) 17 | 18 | # Write Data to Cell 19 | ws.range("A1").value = "Hello World" 20 | 21 | # Write Data to Row 22 | ws.range("A1:A3").value = ["Hello", "World", "!"] 23 | 24 | # Write Data to Column 25 | ws.range("A1:C3").value = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 26 | 27 | # Save 28 | wb.save() 29 | -------------------------------------------------------------------------------- /fetch_html_css_js.py: -------------------------------------------------------------------------------- 1 | # Fetch HTML with Python 2 | 3 | # pip install requests 4 | # pip install seleniumimport requests as req 5 | 6 | from selenium import webdriver 7 | 8 | 9 | def Fetch_Static(): 10 | r= req.get("https://www.example.com") 11 | if r.status_code == 200: 12 | return r.text 13 | 14 | def Fetch_Dynamic(): 15 | browser = webdriver.Chrome() 16 | browser.get("https://www.example.com") 17 | return browser.page_source 18 | -------------------------------------------------------------------------------- /from_csv_to_json.py: -------------------------------------------------------------------------------- 1 | # Convert CSV to JSON 2 | 3 | import csv 4 | import json 5 | 6 | 7 | def CSV_to_JSON(csv_file): 8 | data = {} 9 | with open(csv_file, encoding = 'utf-8') as f: 10 | csvrows = csv.DictReader(f) 11 | for rows in csvrows: 12 | key = rows['Name'] 13 | data[key] = rows with open("output.json", 'w', encoding = 'utf-8') as f: 14 | f.write(json.dumps(data, indent = 4)) 15 | 16 | CSV_to_JSON('test.csv') 17 | -------------------------------------------------------------------------------- /from_json_to_csv.py: -------------------------------------------------------------------------------- 1 | import json, csv 2 | 3 | with open("data.json") as file: 4 | data = json.load(file) 5 | 6 | 7 | emp_details = data['emp_details'] 8 | 9 | 10 | with open("data.csv", 'w', newline='') as f: 11 | csv_writer = csv.writer(f) 12 | csv_writer.writerow(emp_details[0].keys()) 13 | for row in emp_details: 14 | csv_writer.writerow(row.values()) 15 | -------------------------------------------------------------------------------- /from_mp4_to_gif.py: -------------------------------------------------------------------------------- 1 | # Convert Video to Gif 2 | 3 | # pip install moviepy 4 | 5 | import moviepy.editor as mpy 6 | 7 | def video_to_gif(videofile): 8 | clip = mpy.VideoFileClip(videofile) 9 | clip.write_gif("test.gif") 10 | clip.close() 11 | 12 | video_to_Gif("test.mp4") 13 | -------------------------------------------------------------------------------- /from_pdf_to_audio_book.py: -------------------------------------------------------------------------------- 1 | # pip install gtts pypdf2 2 | 3 | import PyPDF2 4 | from gtts import gTTS 5 | 6 | 7 | def convert_pdf_to_audio(pdf_path, audio_path): 8 | # Открываем PDF-файл в режиме бинарного чтения 9 | with open(pdf_path, 'rb') as pdf_file: 10 | # Создаём объект класса PdfReader 11 | pdf_reader = PyPDF2.PdfReader(pdf_file) 12 | 13 | text = '' 14 | # Проходимся по каждой странице в PDF при помощи цикла 15 | for page_num in range(len(pdf_reader.pages)): 16 | # Извлекаем текущую страницу 17 | page = pdf_reader.pages[page_num] 18 | # Извлекаем текст с текущей страницы и добавляем его к строке 'text' 19 | text += page.extract_text() 20 | # Выводим извлеченный текст из PDF 21 | print(text) 22 | 23 | # Создаём объект класса gTTS для преобразования текста в речь 24 | tts = gTTS(text=text, lang='ru') 25 | # Сохраняем итоговый аудиофайл 26 | tts.save(audio_path) 27 | 28 | 29 | convert_pdf_to_audio('document.pdf', 'audio.mp3') 30 | -------------------------------------------------------------------------------- /from_pdf_to_docx.py: -------------------------------------------------------------------------------- 1 | # pip install pdfplumber python-docx 2 | import pdfplumber 3 | from docx import Document 4 | 5 | # Открываем PDF-файл 6 | pdf = pdfplumber.open("my_pdf.pdf") 7 | 8 | # Создаем новый документ Word 9 | doc = Document() 10 | 11 | # Проходим по каждой странице в PDF 12 | for page in pdf.pages: 13 | # Извлекаем текст со страницы 14 | text = page.extract_text() 15 | # Добавляем текст в качестве абзаца в документ Word 16 | doc.add_paragraph(text) 17 | 18 | # Сохраняем документ Word 19 | doc.save("output.docx") 20 | -------------------------------------------------------------------------------- /gazpacho_soup_html.py: -------------------------------------------------------------------------------- 1 | # Parse and Extract HTML 2 | 3 | # pip install gazpacho 4 | 5 | import gazpacho 6 | 7 | # Extract HTML from URL 8 | url = 'https://www.example.com/' 9 | html = gazpacho.get(url) 10 | print(html) 11 | 12 | # Extract HTML with Headers 13 | headers = {'User-Agent': 'Mozilla/5.0'} 14 | html = gazpacho.get(url, headers=headers) 15 | print(html) 16 | 17 | # Parse HTML 18 | parse = gazpacho.Soup(html) 19 | 20 | # Find single tags 21 | tag1 = parse.find('h1') 22 | tag2 = parse.find('span') 23 | 24 | # Find multiple tags 25 | tags1 = parse.find_all('p') 26 | tags2 = parse.find_all('a') 27 | 28 | # Find tags by class 29 | tag = parse.find('.class') 30 | 31 | # Find tags by Attribute 32 | tag = parse.find("div", attrs={"class": "test"}) 33 | 34 | # Extract text from tags 35 | text = parse.find('h1').text 36 | text = parse.find_all('p')[0].text 37 | -------------------------------------------------------------------------------- /generate_fake_person.py: -------------------------------------------------------------------------------- 1 | # Python Faker 2 | # pip install Faker 3 | 4 | from faker import Faker 5 | 6 | dumy = Faker() 7 | 8 | # Get Profile 9 | print(dumy.profile()) 10 | 11 | # Get random sentence 12 | print(dumy.sentence()) 13 | 14 | # Get a random name 15 | print(dumy.name()) 16 | 17 | # Get a random address 18 | print(dumy.address()) 19 | 20 | # Get a random phone number 21 | print(dumy.phone_number()) 22 | 23 | # Get a random email address 24 | print(dumy.email()) 25 | 26 | # Get a random company name 27 | print(dumy.company()) 28 | 29 | # Get a random city 30 | print(dumy.city()) 31 | 32 | # Get a random state 33 | print(dumy.state()) 34 | 35 | # Get a random zip code 36 | print(dumy.zipcode()) 37 | -------------------------------------------------------------------------------- /generate_qr_code.py: -------------------------------------------------------------------------------- 1 | # Python QrCode 2 | # pip install pyqrcode 3 | # pip install pypng 4 | 5 | import pyqrcode 6 | import png 7 | 8 | link = "https://medium.com/" 9 | 10 | qr = pyqrcode.create(link) 11 | 12 | # save in png 13 | qr.png('qr.png', scale=6) 14 | 15 | # save in svg 16 | qr.svg('qr.svg', scale=6) 17 | 18 | # save in png with low error correction 19 | qr.png('qr_low.png', scale=6, module_color='red', background='white', quiet_zone=1) 20 | 21 | 22 | #or 23 | import qrcode 24 | 25 | input_URL = "https://www.google.com/" 26 | 27 | qr = qrcode.QRCode( 28 | version=1, 29 | error_correction=qrcode.constants.ERROR_CORRECT_L, 30 | box_size=15, 31 | border=4, 32 | ) 33 | 34 | qr.add_data(input_URL) 35 | qr.make(fit=True) 36 | 37 | img = qr.make_image(fill_color="red", back_color="white") 38 | img.save("url_qrcode.png") 39 | 40 | print(qr.data_list) 41 | -------------------------------------------------------------------------------- /google_news.py: -------------------------------------------------------------------------------- 1 | # Scrape News Headlines 2 | # pip install GoogleNews 3 | 4 | from GoogleNews import GoogleNews 5 | 6 | gnews = GoogleNews()# Search news by keyword 7 | gnews.search('python') 8 | gnews.results()# Get News Titles 9 | gnews.get_texts() 10 | gnews.results()# Get News url 11 | gnews.get_urls() 12 | gnews.results()# Search news by lang 13 | gnews.search('python', lang='en', region= 'UK') 14 | gnews.results() 15 | -------------------------------------------------------------------------------- /images_extraction_from_pdf.py: -------------------------------------------------------------------------------- 1 | # pip install pymupdf 2 | import fitz 3 | 4 | 5 | file = 'my_pdf.pdf' 6 | 7 | # Открытие PDF-файла 8 | pdf = fitz.open(file) 9 | 10 | # Перебор каждой страницы PDF-файла 11 | for i in range(len(pdf)): 12 | # Перебор каждого изображения на текущей странице 13 | for image in pdf.get_page_images(i): 14 | # Получение ссылки на изображение 15 | xref = image[0] 16 | # Создание объекта пиксмапы из ссылки на изображение 17 | pix = fitz.Pixmap(pdf, xref) 18 | # Проверка, имеет ли изображение менее 5 цветовых компонентов (не является ли изображением в формате CMYK) 19 | if pix.n < 5: 20 | # Сохранение пиксмапы в виде изображения PNG 21 | pix.save(f'{xref}.png') 22 | else: 23 | # Создание новой пиксмапы с цветовым пространством RGB 24 | pix1 = fitz.open(fitz.csRGB, pix) 25 | # Сохранение новой пиксмапы в виде изображения PNG 26 | pix1.save(f'{xref}.png') 27 | # Освобождение ресурсов, связанных с новой пиксмапой 28 | pix1 = None 29 | # Освобождение ресурсов, связанных с исходной пиксмапой 30 | pix = None 31 | -------------------------------------------------------------------------------- /insta_bot.py: -------------------------------------------------------------------------------- 1 | from instabot import Bot 2 | bot = Bot() 3 | bot.login(username="", password="") 4 | 5 | ###### upload a picture ####### 6 | bot.upload_photo("yoda.jpg", caption="biscuit eating baby") 7 | 8 | ###### follow someone ####### 9 | bot.follow("elonrmuskk") 10 | 11 | ###### send a message ####### 12 | bot.send_message("Hello from Dhaval", ['user1','user2']) 13 | 14 | ###### get follower info ####### 15 | my_followers = bot.get_user_followers("dhavalsays") 16 | for follower in my_followers: 17 | print(follower) 18 | 19 | ####### Unfollow Everyone ####### 20 | bot.unfollow_everyone() 21 | 22 | ###### Upload An Image ####### 23 | file = open('image_path', 'r') 24 | bot.upload_photo(file, caption="image_caption") 25 | -------------------------------------------------------------------------------- /instaloader.py: -------------------------------------------------------------------------------- 1 | import instaloader 2 | 3 | 4 | ig = instaloader.Instaloader() 5 | 6 | dp = input('Enter insta username : ') 7 | 8 | ig.download_profile(dp, profile_pic_only=True) 9 | 10 | -------------------------------------------------------------------------------- /merge_pdf_in_directory.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from PyPDF2 import PdfMerger 3 | 4 | 5 | def merge_pdfs_in_directory(directory_path, output_path): 6 | merger = PdfMerger() 7 | 8 | for file_path in Path(directory_path).rglob('*.pdf'): 9 | merger.append(file_path) 10 | 11 | merger.write(output_path) 12 | merger.close() 13 | 14 | 15 | directory_path = '' 16 | output_path = '' 17 | 18 | merge_pdfs_in_directory(directory_path, output_path) 19 | -------------------------------------------------------------------------------- /mp4_to_mp3.py: -------------------------------------------------------------------------------- 1 | #pip install moviepy 2 | 3 | from moviepy.editor import * 4 | videofile = VideoFileClip("input mp4 filename") 5 | audiofile = videofile.audio 6 | audiofile.write_audiofile("output mp3 filename")videofile.close() 7 | audiofile.close() 8 | -------------------------------------------------------------------------------- /multiple_email_sender.py: -------------------------------------------------------------------------------- 1 | # Bulk Email Sender 2 | 3 | import smtplib as smtp 4 | from email.message import EmailMessage 5 | 6 | emails = ["test1@email.com", "test2@email.com"] 7 | Email = "myemail@test.com" 8 | Pass = "mypassword"E_msg = EmailMessage() 9 | 10 | E_msg['Subject'] = "Test Email" 11 | E_msg['From'] = Email 12 | E_msg['To'] = emails 13 | E_msg.set_content("This is a test email") 14 | 15 | with smtp.SMTP_SSL('smtp.gmail.com', 465) as smtp: 16 | smtp.login(Email, Pass) 17 | smtp.send_message(E_msg) 18 | -------------------------------------------------------------------------------- /news_catcher_api.py: -------------------------------------------------------------------------------- 1 | # Get your API : https://newscatcherapi.com/ 2 | 3 | import requests 4 | 5 | 6 | query = "Tesla" 7 | country = "US" 8 | URL = f"https://api.newscatcherapi.com/v2/search?q=\"{query}\"&lang=en&countries={country}" 9 | 10 | payload={} 11 | headers = { 12 | 'X-API-KEY': 'Your API Key' 13 | } 14 | 15 | r = requests.get(URL, headers=headers, data=payload) 16 | news = r.text 17 | print(news) 18 | -------------------------------------------------------------------------------- /open_ai_api.py: -------------------------------------------------------------------------------- 1 | # Get your API : https://beta.openai.com/ 2 | 3 | import openai as ai 4 | 5 | 6 | ai.api_key = "Your API key" 7 | text = "Hey I hope you are doing great?" 8 | 9 | resp = ai.Completion.create( 10 | model="text-davinci-002", 11 | prompt=f"Translate this into 1. French:\n\n{text}\n\n1.", 12 | temperature=0.3, 13 | max_tokens=100, 14 | top_p=1.0, 15 | ) 16 | -------------------------------------------------------------------------------- /playlist_youtube_downloader.py: -------------------------------------------------------------------------------- 1 | from pytube import Playlist 2 |   3 | playlist = Playlist("https://www.youtube.com/playlist?example") 4 |   5 | print(f"Download: {playlist.title}") 6 | for video in playlist.videos: 7 |     video.streams.first().download() 8 |     print(f"Video {video.title} downloaded") 9 | -------------------------------------------------------------------------------- /proxy_checker.py: -------------------------------------------------------------------------------- 1 | # pip install proxy-checking 2 | from proxy_checking import ProxyChecker 3 | 4 | checker = ProxyChecker() 5 | r = checker.check_proxy(':') 6 | print(r) 7 | -------------------------------------------------------------------------------- /py_tg_bot_api.py: -------------------------------------------------------------------------------- 1 | # Telegram Bot 2 | # pip install pyTelegramBotAPI 3 | 4 | import telebot 5 | 6 | bot = telebot.TeleBot('YOUR TOKEN') 7 | 8 | # send message 9 | bot.send_message(chat_id='YOUR ID', text='Medium.com') 10 | 11 | # send photo 12 | bot.send_photo(chat_id='YOUR ID', photo=open('photo.jpg', 'rb')) 13 | 14 | # send audio 15 | bot.send_audio(chat_id='YOUR ID', audio=open('audio.mp3', 'rb')) 16 | 17 | # send document 18 | bot.send_document(chat_id='YOUR ID', document=open('document.pdf', 'rb')) 19 | 20 | # send video 21 | bot.send_video(chat_id='YOUR ID', video=open('video.mp4', 'rb')) 22 | 23 | # Reply handler 24 | @bot.message_handler(commands=['start', 'about', 'help']) 25 | def send_welcome(msg): 26 | bot.reply_to(msg, "Welcome") 27 | 28 | # Reply all Handler 29 | @bot.message_handler(func=lambda msg: True) 30 | def echo_all(msg): 31 | bot.reply_to(msg, msg.text) 32 | 33 | # Ban Member handler 34 | @bot.message_handler(commands=['ban']) 35 | def ban_member(msg): 36 | bot.kick_chat_member(chat_id=msg.chat.id, user_id=msg.from_user.id) 37 | bot.reply_to(msg, "You have been banned")bot.infinity_polling() 38 | -------------------------------------------------------------------------------- /remove_background.py: -------------------------------------------------------------------------------- 1 | from rembg import remove 2 | from PIL import Image 3 | 4 | 5 | input_path = "input_img.jpg" 6 | output_path = "output_img.png" 7 | 8 | input_img = Image.open(input_path) 9 | output_img = remove(input_img) 10 | output_img.save(output_path) 11 | -------------------------------------------------------------------------------- /remove_background_of_images_api.py: -------------------------------------------------------------------------------- 1 | # Get Your API: https://www.remove.bg/tools-api 2 | # pip install remove-bg-api 3 | 4 | from remove_bg_api import RemoveBg 5 | 6 | 7 | # Remove from File 8 | bg = RemoveBg("Your API") 9 | img = bg.remove_bg_file(input_path="img.jpg", out_path="out.jpg") 10 | 11 | # Remove from URL 12 | img_url = "https://www.example.com/img" 13 | img = bg.remove_background_from_img_url(input_url=img_url, out_path="out.jpg") 14 | -------------------------------------------------------------------------------- /send_discord_webhooks.py: -------------------------------------------------------------------------------- 1 | # Send Discord Webhooks 2 | # pip install discord-webhook 3 | 4 | from discord_webhook import DiscordWebhook 5 | 6 | # Send Simple Webhook 7 | hook = DiscordWebhook(url='Discord webhook api', content="Hello Medium") 8 | hook.execute() 9 | 10 | # Send Multiple Webhooks 11 | url = ["webhook_api1, webhook_api2"] 12 | hook = DiscordWebhook(url=url, content="Hello Medium") 13 | hook.execute() 14 | 15 | # Send Embed Webhook 16 | hook = DiscordWebhook(url='Discord webhook api', content="Hello Medium") 17 | hook.add_embed(title="Embed Title", description="Embed Description") 18 | hook.execute() 19 | 20 | # Send File Webhook 21 | hook = DiscordWebhook(url='Discord webhook api', content="Hello Medium") 22 | hook.add_file(file_path="file_path") 23 | hook.execute() 24 | 25 | # Delete Webhook 26 | hook = DiscordWebhook(url='Discord webhook api', content="Hello Medium") 27 | web = hook.execute() 28 | hook.delete(web) 29 | -------------------------------------------------------------------------------- /use_py_script_in_html.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | - numpy 7 | - matplotlib 8 | 9 | 10 | 11 | 12 |

Plotting a histogram of Standard Normal distribution

13 |
14 | 15 | import matplotlib.pyplot as plt 16 | import numpy as np 17 | 18 | np.random.seed(42) 19 | 20 | rv = np.random.standard_normal(1000) 21 | 22 | fig, ax = plt.subplots() 23 | ax.hist(rv, bins=30) 24 | fig 25 | 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /video_cropper.py: -------------------------------------------------------------------------------- 1 | # Crop Video 2 | # pip install moviepy 3 | 4 | from moviepy.editor import * 5 | 6 | # x1, y1 is the top left corner of the crop 7 | # x2, y2 is the bottom right corner of the crop 8 | 9 | filename = 'test.mp4' 10 | clip = VideoFileClip(filename) 11 | clip = clip.crop(x1=250, y1=150, x2=clip.width, y2=clip.height) 12 | clip.write_videofile("test_crop.mp4") 13 | -------------------------------------------------------------------------------- /work_with_json.py: -------------------------------------------------------------------------------- 1 | # Parse JSON 2 | 3 | import json 4 | import requests 5 | 6 | 7 | # Parse Json from URL 8 | url = "https://www.example.com/api" 9 | response = requests.get(url) 10 | data = response.json() 11 | 12 | # Load Json File 13 | with open('example.json') as json_file: 14 | json_data = json.load(json_file) 15 | 16 | test = {"product": "test", 17 | "price": "10.00", 18 | "quantity": "1"} 19 | 20 | # Find Price 21 | price = test["price"] 22 | 23 | # Write to Json File 24 | with open('example.json', 'w') as out: 25 | json.dump(test, out) 26 | 27 | 28 | # Write Json with Format 29 | with open('example.json', 'w') as out: 30 | json.dump(test, out, indent=4) 31 | -------------------------------------------------------------------------------- /work_with_xlsx.py: -------------------------------------------------------------------------------- 1 | from openpyxl import Workbook, load_workbook 2 | 3 | ## loading previous workbook 4 | wb = load_workbook('SampleData.xlsx') 5 | 6 | ## access the content from the active sheet 7 | ws = wb.active 8 | print(ws) 9 | 10 | 11 | ## Accessing other sheets 12 | ws = wb["SalesOrders"] 13 | print(ws) 14 | 15 | ## Access Cell 16 | cell_to_access= ws['A5'] 17 | print(cell_to_access) 18 | 19 | 20 | ## Accessing Cell Value 21 | cell_value = ws['B5'].value 22 | print(cell_value) 23 | 24 | ## Changing the value of a cell 25 | print(ws['B1'].value) 26 | 27 | ws['B1'].value="Location" 28 | print(ws['B1'].value) 29 | 30 | ## Printing Sheet Names 31 | print(wb.sheetnames) 32 | 33 | ## Creating New Sheet 34 | wb.create_sheet("Percentage") 35 | print(wb.sheetnames) 36 | 37 | ## Saving the sheet 38 | wb.save("test1.xlsx") 39 | 40 | ## Create new workbook 41 | wb = Workbook() 42 | ws = wb.active 43 | ws.title = "Test" 44 | 45 | ## Adding data to the worksheet 46 | ws.append(["S.N.","A", "B", "C"]) 47 | 48 | ## Adding Rows 49 | for i in range(2): 50 | ws.insert_rows(5) # row_number as input 51 | 52 | ## Deleting Rows 53 | for i in range(3): 54 | ws.delete_rows(3) # column_number as the input. 55 | 56 | ## Adding new columns 57 | ws.insert_cols(3) # column_number as the input 58 | 59 | ## Deleting columns 60 | ws.delete_cols(2) # column_number as the input 61 | 62 | ## Moving Data 63 | ws.move_range("B2:D9", rows=0, cols=2 ) 64 | 65 | wb.save("New_WB.xlsx") 66 | -------------------------------------------------------------------------------- /youtube_downloader.py: -------------------------------------------------------------------------------- 1 | import pytube 2 | 3 | 4 | link = input('Enter youtube video url: ') 5 | 6 | yt = pytube.YouTube(link) 7 | 8 | yt.streams.first().download() 9 | 10 | print('Done') 11 | --------------------------------------------------------------------------------