from subprocess import Popen
from speech_recognition import (Recognizer, AudioFile)
from speech_recognition import (UnknownValueError, RequestError)
class SpeechOggAudioFileToText:
def __init__(self):
self.recognizer = Recognizer()
def ogg_to_wav(self, file):
args = ['ffmpeg','-i', file, 'test.wav']
process = Popen(args)
process.wait()
@property
def text(self):
AUDIO_FILE = 'test.wav'
with AudioFile(AUDIO_FILE) as source:
audio = self.recognizer.record(source)
try:
text = self.recognizer.recognize_google(audio, language='RU')
return text
except UnknownValueError:
print("Не удаётся распознать аудио файл")
except RequestError as error:
print("Не удалось запросить результаты: {0}".format(error))
def main():
speech_ogg = SpeechOggAudioFileToText()
speech_ogg.ogg_to_wav('test.ogg')
print(speech_ogg.text)
if __name__ == '__main__':
main()
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.config import Config
Config.set('graphics', 'width', '800')
Config.set('graphics', 'height', '400')
Config.set('graphics', 'resizable', '0')
class ThoughtApp(App):
def build (self):
base=(BoxLayout(orientation='vertical'))
fl=FloatLayout()
adduser=(Label(text='Добавить участника:',
pos=(-120,360),
font_size=22,
bold=True,
font_name='C:\Windows\Fonts\calibril.ttf',
size_hint=(.6,.1)))
fl.add_widget(adduser)
self.textinput=(TextInput(multiline=False,
pos=(225,355),
size_hint=(.5,.15),
font_size=16))
fl.add_widget(self.textinput)
plusbtn=(Button(size_hint=(27/800,30/800),
text='+',
pos=(635,366.5),
on_press=self.pluspress,
background_color=[.55,.55,.55,1],
background_normal=''))
fl.add_widget(plusbtn)
base.add_widget(fl)
self.names_gl=GridLayout(rows=1,)
base.add_widget(self.names_gl)
return base
def pluspress(self, event):
self.names_gl.add_widget(Button(text=self.textinput.text,
background_color=[.1,.9,.9,1],
background_normal=''))
self.textinput.text=''
if __name__ == '__main__':
ThoughtApp().run()
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QtWidgets.QMessageBox.critical(None, 'Error', text)
quit()
sys.excepthook = log_uncaught_exceptions
И да будет вам счастье
import os
import datetime
import telebot
from telebot import types
bot = telebot.TeleBot('')
class TestTeleBot:
def __init__(self):
self.bot_polling()
@bot.message_handler(commands=['start'])
def start_message(message):
print('-------------------------------------------------------------------')
print(datetime.datetime.fromtimestamp(message.date).strftime('%H:%M:%S %d-%m-%Y'))
print(message.text)
print(message.from_user.id)
print(message.from_user.first_name)
print(message.from_user.last_name)
print(message.from_user.username)
print('-------------------------------------------------------------------')
bot.send_message(message.chat.id, "Здравствуте, что хотите заказать?")
keyboard_menu = types.InlineKeyboardMarkup()
pizza = types.InlineKeyboardButton(text="Пицца", callback_data="pizza")
tea = types.InlineKeyboardButton(text="Чай", callback_data="tea")
keyboard_menu.add(pizza, tea)
bot.send_message(message.chat.id, 'Выбери в меню что тебе интересно', reply_markup=keyboard_menu)
@bot.callback_query_handler(func=lambda call:True)
def handler_item_menu(callback):
print(callback.data)
if callback.data == "pizza":
keyboard_name = types.InlineKeyboardMarkup()
#Пицца “Маргарита” (Margherita)
margherita = types.InlineKeyboardButton(text="Маргарита", callback_data="margherita")
#Пицца “Карбонара” (Carbonara)
carbonara = types.InlineKeyboardButton(text="Карбонара", callback_data="carbonara")
keyboard_name.add(margherita, carbonara)
bot.send_message(callback.from_user.id, 'Какую?', reply_markup=keyboard_name)
elif callback.data == "margherita":
bot.send_message(callback.from_user.id, "Ваш заказ принят...")
if callback.data == "tea":
pass
def bot_polling(self):
return bot.polling(none_stop=True)
def main():
testTeleBot = TestTeleBot()
if __name__ == '__main__':
main()
import sys
from PyQt5.QtWidgets import *
def log_uncaught_exceptions(ex_cls, ex, tb):
text = '{}: {}:\n'.format(ex_cls.__name__, ex)
import traceback
text += ''.join(traceback.format_tb(tb))
print(text)
QMessageBox.critical(None, 'Error', text)
quit()
sys.excepthook = log_uncaught_exceptions
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('Передача значения из QLineEdit в QListWidget')
self.setGeometry(300, 300, 500, 400)
vbox = QVBoxLayout(self)
self.line_edit = QLineEdit()
self.list_widget = QListWidget()
self.button = QPushButton('Запустить')
self.button.clicked.connect(self.add_item)
vbox.addWidget(self.line_edit)
vbox.addWidget(self.list_widget)
vbox.addWidget(self.button)
def add_item(self):
self.list_widget.addItem(self.line_edit.text()) #QLineEdit метод метод text возвращает текст
# По QListWidget читайте документацию
print(self.line_edit.text())
if __name__ == "__main__":
app = QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())
from time import sleep
import pyautogui
import keyboard
ENTER = "enter"
ESCAPE = "escape"
def writing_data_file():
if keyboard.is_pressed(ENTER):
sleep(0.5)
cursor_position = pyautogui.position()
print(cursor_position)
with open("cursor_position.txt", "a") as file:
file.write("{0}\n".format(cursor_position))
if keyboard.is_pressed(ESCAPE):
quit()
while True:
writing_data_file()
#Необходимые модули.
import os
from datetime import datetime #Модуль для определения времени.
from time import sleep #Модуль для 'простойки'.
#Все необходимые символы.
digits = [
[' ---- ','| |','| |','| |','| |','| |',' ---- '], #Ноль.
[' ',' |',' |',' |',' |',' |',' '], #Один.
[' ---- ',' |',' |',' ---- ','| ','| ',' ---- '], #Два.
[' ---- ',' |',' |',' ---- ',' |',' |',' ---- '], #Три.
[' ','| |','| |',' ---- ',' |',' |',' '], #Четыре.
[' ---- ','| ','| ',' ---- ',' |',' |',' ---- '], #Пять.
[' ---- ','| ','| ',' ---- ','| |','| |',' ---- '], #Шесть.
[' ---- ',' |',' |',' |',' |',' |',' '], #Семь.
[' ---- ','| |','| |',' ---- ','| |','| |',' ---- '], #Восемь.
[' ---- ','| |','| |',' ---- ',' |',' |',' ---- '], #Девять.
[' ',' ',' [] ',' ',' [] ',' ',' ']] #Точки (разделители).
#Начинаем выводить символы в консоль.
while True:
now = list(str(datetime.now())[11:19:1]) #Здесь мы находим реальное вермя ЧЧ:ММ:CC.
for i in range(7):
#Вывод построчно больших цифр.
print ('{0} {1}{6}{2} {3}{6}{4} {5}'.format(digits[int(now[0])][i], digits[int(now[1])][i], digits[int(now[3])][i],
digits[int(now[4])][i], digits[int(now[6])][i], digits[int(now[7])][i],digits[10][i]))
sleep(1) #Ждём секунду.
os.system("cls")
import sys
from PyQt5.QtWidgets import QWidget, QLabel
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication
import requests
from bs4 import BeautifulSoup
from nltk.tokenize import RegexpTokenizer
import nltk
import io
nltk.download('stopwords')
from nltk.corpus import stopwords
import matplotlib.pyplot as pyplot
from stop_words import get_stop_words
r = requests.get('https://www.gutenberg.org/files/2701/2701-h/2701-h.htm')
# Извлечение HTML
html = r.text
# Создаём BeautifulSoup из HTML
soup = BeautifulSoup(html, "html5lib")
# Получаем текст
text = soup.get_text()
# Создаём tokenizer, выкидывая знаки пунктуации
tokenizer = RegexpTokenizer('\w+')
# Создаём tokens
tokens = tokenizer.tokenize(text)
# Создаем новый list
words = []
# Перебираем список
for word in tokens:
words.append(word.lower())
# Получаем английские стоп-слова и выводим некоторые из них
sw = nltk.corpus.stopwords.words('english')
with io.open("STOP_EN.txt", "r", encoding='utf-8') as myfile:
data = myfile.read().splitlines()
sw.extend(data)
data2 = get_stop_words('en')
sw.extend(data2)
# Создаем новый list
words_ns = []
for word in words:
if word not in sw:
words_ns.append(word)
# создаем график плотности ключевых слов
fd = nltk.FreqDist(words_ns)
total = fd.N()
for wordo in fd:
fd[wordo] /= float(total)/100
fd.plot(25)
pyplot.savefig("image.png")
class ImageViewer(QWidget):
def __init__(self):
super().__init__()
image_label = QLabel(self)
pixmap = QPixmap("image.png")
image_label.setPixmap(pixmap)
self.resize(pixmap.width(), pixmap.height()) # fit window to the image
self.setWindowTitle('График функции')
def main():
app = QApplication(sys.argv)
image_viewer = ImageViewer()
image_viewer.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
import sys
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
import cv2 # OpenCV
import qimage2ndarray # for a memory leak
class ThreadCamera(QThread):
status = True
changePixmap = Signal(QImage)
def __init__(self):
super().__init__()
self.capture = cv2.VideoCapture(0)
def setStatus(self, status):
self.status = status
def captureRelease(self):
self.capture.release()
def run(self):
while self.status:
face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')
ret, frame = self.capture.read()
if (ret == True):
self.capture.set(3,640)
self.capture.set(4, 480)
frame = cv2.cvtColor (frame, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
image = qimage2ndarray.array2qimage(frame)
self.changePixmap.emit(image)
class ThreadVideoFile(QThread):
status = True
changePixmap = Signal(QImage)
def __init__(self, path):
super().__init__()
self.capture = cv2.VideoCapture(path)
def set_status(self, status):
self.status = status
def captureRelease(self):
self.capture.release()
def run(self):
while self.status:
face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')
ret, frame = self.capture.read()
if (ret == True):
self.capture.set(3,640)
self.capture.set(4, 480)
frame = cv2.cvtColor (frame, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor (frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
frame = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
image = qimage2ndarray.array2qimage(frame)
self.changePixmap.emit(image)
class Dialog(QDialog):
def __init__(self, parent):
super().__init__()
self.resize(400, 100)
self.label = QLabel()
self.label.setText("<center><h1>Выберите действие</h1></center>")
self.button_open_camera = QPushButton('Камера')
self.button_open_camera.clicked.connect(parent.open_camera)
self.button_open_file = QPushButton('Видео файл')
self.button_open_file.clicked.connect(parent.open_file)
layout = QVBoxLayout()
layout.addWidget(self.label)
layout.addWidget(self.button_open_camera)
layout.addWidget(self.button_open_file)
self.setLayout(layout)
class VideoWidget(QWidget):
def __init__(self):
super().__init__()
self.initUI()
self.thread_camera = ThreadCamera()
self.thread_video = ThreadVideoFile("videoplayback.mp4")
@Slot(QImage)
def setImage (self, image):
self.label.setPixmap(QPixmap.fromImage(image))
def initUI(self):
self.setFixedSize(640, 480)
self.label = QLabel(self)
self.label.setText("Загрузите видео")
self.label.setAlignment(Qt.AlignCenter)
self.label.installEventFilter(self)
self.layout = QVBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.addWidget(self.label)
self.setLayout(self.layout)
def eventFilter(self, obj, event):
# Только фильтровать событие label, переписать его поведение,
# другие события будут проигнорированы
if obj == self.label:
# здесь отфильтруйте событие mouse и перепишите его поведение
if event.type() == QEvent.MouseButtonPress:
if event.buttons() == Qt.LeftButton:
self.dialog = Dialog(self)
self.dialog.exec_()
return False
def open_file(self):
if self.thread_video.isRunning() is True:
self.thread_video.set_status(False)
self.thread_video.captureRelease()
self.dialog.hide()
self.thread_camera.setStatus(False)
self.thread_camera.captureRelease()
self.label.setText("Загрузите видео")
fileDialog = QFileDialog(self)
supportedMimeTypes = ["video", "*.*"]
fileDialog.setMimeTypeFilters(supportedMimeTypes)
moviesLocation = QStandardPaths.writableLocation(QStandardPaths.MoviesLocation)
fileDialog.setDirectory(moviesLocation)
if fileDialog.exec_() == QDialog.Accepted:
self.file = fileDialog.selectedUrls()[0].toDisplayString()
self.thread_video = ThreadVideoFile(self.file)
self.thread_video.changePixmap.connect(self.setImage)
self.thread_video.start()
def open_camera(self):
self.dialog.hide()
self.thread_video.set_status(False)
self.thread_video.captureRelease()
self.label.setText("Загрузите видео")
self.thread_camera = ThreadCamera()
self.thread_camera.changePixmap.connect(self.setImage)
self.thread_camera.start()
def main():
app = QApplication([])
video_widget = VideoWidget()
video_widget.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
data = [
['Место', 'адрес', 'время', 'событие', 'время', 'событие'], \
['Место', 'адрес', 'время', 'событие', 'время', 'событие', 'событие'], \
['Место', 'адрес', 'время', 'событие', 'событие', 'время', 'событие'], \
['Место', 'адрес', 'время', 'событие', 'событие']
]
my_dict = {'Место': 'Place', 'адрес': 'Address', 'время': 'Time', 'событие': 'Event'}
def main():
for i in range(len(data)):
print("#следующий список...")
for j in data[i]:
print(my_dict[j], j)
if __name__ == '__main__':
main()
#ifndef PERSON_H
#define PERSON_H
#include <string>
using namespace std;
namespace person{
class CppPerson{
public:
string name;
int age;
CppPerson();
CppPerson(const string &name, const int &age);
~CppPerson();
void setName(const string &name);
string getName();
int getAge();
};
}
#endif
#include <string>
#include "Person.hpp"
namespace person{
CppPerson::CppPerson(){}
CppPerson::CppPerson(const string &name, const int &age){
this->name = name;
this->age = age;
}
CppPerson::~CppPerson(){}
void CppPerson::setName(const string &name){
this->name = name;
}
string CppPerson::getName(){
return name;
}
int CppPerson::getAge(){
return age;
}
}
from libcpp.string cimport string
cdef extern from "Person.hpp" namespace "person":
cdef cppclass CppPerson:
CppPerson(string name, int age) except +
void setName(string name)
string getName()
int getAge()
cdef class Person:
cdef CppPerson *cpp_person
def __cinit__(self, name, age):
self.cpp_person = new CppPerson(name.encode(), age)
if self.cpp_person == NULL:
raise MemoryError('Not enough memory.')
def __dealloc__(self):
del self.cpp_person
def setName(self, name):
self.cpp_person.setName(name.encode())
def getName(self):
return self.cpp_person.getName().decode()
def getAge(self):
return self.cpp_person.getAge()
from distutils.core import setup, Extension
from Cython.Build import cythonize
setup(ext_modules = cythonize(Extension(
"person_module", # the extesion name
sources=["person_module.pyx", "Person.cpp"], # the Cython source and
# additional C++ source files
language="c++", # generate and compile C++ code
)))
from person_module import Person
def main():
alexandr = Person("Александр", 35)
print(alexandr.getName())
print(alexandr.getAge())
if __name__ == '__main__':
main()
# Python 3.7+
import asyncio
async def hello_world():
await asyncio.sleep(3)
print('Hello World!')
asyncio.run(hello_world())
from threading import Timer
def hello_world():
print('Hello World!')
timer = Timer(3, hello_world)
timer.start()
timer.join()
# Python 3.7+
import asyncio
from threading import Timer
async def hello_world():
await asyncio.sleep(3)
print('Hello World!')
def wait():
asyncio.run(hello_world())
timer = Timer(3, wait)
timer.start()
timer.join()
from tkinter import Tk, Button, mainloop
from vlc import MediaPlayer
URL = "https://str2.pcradio.ru/Eminem-med"
class Player(Tk):
def __init__(self):
print("Инициализация Player")
self.player = MediaPlayer()
super().__init__()
self.button = Button(self, text="Воспроизвести файл из интернета")
self.button.configure(command=self.play)
self.button.pack()
self.protocol("WM_DELETE_WINDOW", self.on_closing)
def play(self):
return self.player.play()
def set_mrl(self, mrl):
return self.player.set_mrl(mrl)
def on_closing(self):
self.player.stop()
del self.player
self.destroy()
class TkPlayer(Player):
pass
def main():
tk_player = TkPlayer()
tk_player.set_mrl(URL)
tk_player.mainloop()
if __name__ == '__main__':
main()
from threading import Thread
import time
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
def listener():
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
def main():
for i in range(10):
time.sleep(1)
print(i)
if __name__ == '__main__':
th = Thread(target=listener)
th.start()
main()
import sys
from PyQt5.QtWidgets import (QWidget, QApplication, QPushButton, QSlider,
QVBoxLayout, QMessageBox)
from PyQt5.QtCore import Qt
class QButtonExample(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setGeometry(300, 300, 200, 150)
self.button = QPushButton(self, text="Ты не сможешь на меня нажать!")
self.button.setEnabled(False)
self.button.clicked.connect(self.handleButton)
slider = QSlider(Qt.Horizontal, self)
slider.setFocusPolicy(Qt.NoFocus)
slider.setGeometry(30, 40, 100, 30)
slider.valueChanged[int].connect(self.changeValue)
boxLayout = QVBoxLayout(self)
# boxLayout.addStretch(1)
boxLayout.addWidget(self.button)
boxLayout.addWidget(slider)
def changeValue(self, value):
if value > 50:
self.button.setEnabled(True)
else:
self.button.setEnabled(False)
def handleButton(self):
QMessageBox.information(None, 'Сообщение от программы', "Да ладно! у тебя получилось!")
if __name__ == '__main__':
app = QApplication(sys.argv)
myApplication = QButtonExample()
myApplication.show()
sys.exit(app.exec_())
import psutil
user_commands = ""
while user_commands != "Выйти":
user_commands = input("Введите команду -->")
if user_commands == "Диагностика компьютера":
print("ЦП: {0}".format(psutil.cpu_percent()))
print("Память всего: {0}, занято: {1} %".format(psutil.virtual_memory()[0], psutil.virtual_memory()[2]))
from tkinter import Tk, Entry, Checkbutton, mainloop
class Example(Tk):
def __init__(self):
super().__init__()
self.input_field_1 = Entry(self)
self.input_field_1.grid(row=0, column=0)
self.check_button_1 = Checkbutton(self)
self.check_button_1.grid(row=0, column=1)
self.input_field_2 = Entry(self)
self.input_field_2.grid(row=1, column=0)
self.check_button_2 = Checkbutton(self, command=self.disable_or_normal_input_field_2)
self.check_button_2.grid(row=1, column=1)
def disable_or_normal_input_field_2(self):
if self.input_field_2['state'] == 'normal':
self.input_field_2.configure(state="disable")
else:
self.input_field_2.configure(state="normal")
print("Поле ввода 2 статус:", self.input_field_2['state'])
def main():
example = Example()
example.mainloop()
if __name__ == '__main__':
main()