Python script module not found on rerun of script - python

I am running a python script on RaspberryPi 4, and today when I ran the script again, it showed me the error ModuleNotFoundError: No module named 'adafruit_ssd1306' although I ran this same script yesterday about 10 times, it ran perfectly without any errors. I did not change anything in the script, not even its location. I tried force reinstalling the library,
running the script from another location, rebooting the pi, running it as sudo but none of them worked either.
By using pip3 freeze it shows that the package is installed and trying to install the package again says that the requirement is already satisfied.
Python version: 3.7
Main.py
import time
import board
import digitalio
from PIL import Image, ImageDraw, ImageFont
import adafruit_ssd1306
import requests
WIDTH = 128
HEIGHT = 64 # Change to 64 if needed
BORDER = 5
BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
API_KEY = "API Key"
sign = '°'
# Use for I2C.
i2c = board.I2C()
oled = adafruit_ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c, addr=0x3C)
dir_pin = digitalio.DigitalInOut(board.D23)
step_pin = digitalio.DigitalInOut(board.D24)
call_b = digitalio.DigitalInOut(board.D18)
dir_pin.direction = digitalio.Direction.INPUT
step_pin.direction = digitalio.Direction.INPUT
call_b.direction = digitalio.Direction.INPUT
dir_pin.pull = digitalio.Pull.UP
step_pin.pull = digitalio.Pull.UP
prev_value = True
cities = ['Delhi','Tokyo','London','San Francisco',
'kanpur','Mumbai','portugal','Toronto','Sydney','Paris','New York','Dubai',
'Moscow','Rome','Madrid','Riyadh','Bangkok','Cairo','Istanbul','Kolkata',
'Beijing','Seoul','Shanghai','Osaka','Hong Kong','Bangalore','Kathmandu',
'Chennai','Kathmandu','Manila','Jakarta','Tehran','Baghdad','Riyadh','Abu Dhabi',
'Dubai','Kuala Lumpur','Chennai','Kathmandu','Manila','Jakarta','Tehran','Baghdad']
font_size = 12
font = ImageFont.truetype('/home/pi/Desktop/Poppins-Regular.ttf', font_size)
font_big = ImageFont.truetype('/home/pi/Desktop/Poppins-Regular.ttf', font_size+4)
font_xl = ImageFont.truetype('/home/pi/Desktop/Poppins-Regular.ttf', font_size+7)
max_cities = len(cities) - 1
value = 0
def get_temp(city):
url = BASE_URL + "q=" + city + "&appid=" + API_KEY
r = requests.get(url)
if r.status_code == 200:
data = r.json()
temp = data['main']['temp']
humidity = data['main']['humidity']
temp = int(temp)
humidity = int(humidity)
temp = temp - 273
#humidity = humidity+"%"
temp = str(temp)+sign+'c'
# h = "Humidity: "+str(humidity)
return temp
def create_image(temp,city):
image = Image.new("1", (oled.width, oled.height))
draw = ImageDraw.Draw(image)
(fw,fh) = font.getsize(city)
(w,h) = font_xl.getsize(temp)
draw.text((128//2 - fw//2,12),city,fill=255,font=font) # city name
draw.text((128//2 - w//2,30),temp,fill=255,font=font_xl) # temp
return image
def text_image(city):
image_ = Image.new("1", (oled.width, oled.height))
draw = ImageDraw.Draw(image_)
(font_width, font_height) = font_big.getsize(city)
draw.text((128//2 - font_width//2, 64//2 - font_height//2),city, font=font_big, fill=255)
oled.fill(0)
oled.image(image_)
oled.show()
g = "Temprature\n Meter"
intro = Image.new("1", (oled.width, oled.height))
d = ImageDraw.Draw(intro)
# Draw text
(font_width, font_height) = font.getsize(g)
d.text((20, 6),
g, font=font_big, fill=255)
oled.fill(0)
oled.image(intro)
oled.show()
timer = 0
while True:
if prev_value != step_pin.value:
if step_pin.value == False:
if dir_pin.value == False:
print("left") # left
value = value + 1
if value > max_cities:
value = 1
print(value)
selected_city = cities[value]
print(selected_city)
text_image(selected_city)
else:
print("right") # right
if value == 0:
value = max_cities
else:
value = value - 1
print(value)
selected_city = cities[value]
print(selected_city)
text_image(selected_city)
prev_value = step_pin.value
while call_b.value == False:
timer = timer+1
if timer > 70000 and timer < 150000:
oled.fill(0)
oled.show()
timer = 0
print("blank")
time.sleep(2)
print("active")
elif timer < 15000 and timer > 500:
t = get_temp(selected_city)
print(t)
# display the data to the OLED
image = create_image(t,selected_city)
oled.fill(0) #clear display
oled.show()
oled.image(image)
oled.show()
timer = 0
time.sleep(1)
else:
timer = 0

it is sometimes happen when I forgot to activate the virtualenv, even I can install new libraries using pip or pip3 without virtualenv. But python main.py won't run. Then I realized that I haven't turn on the virtual environment.

1- make sure you typed the name of module correctly
2- make sure you use the correct python version
python3:
python3 script.py
3- also make sure it installed with the correct pip installer you may used pip for python2 by mistake
python3 -m pip install some_module
4- better way to make a virtual environment
virtualenv -p python3 env
# then
. env/bin/activate
python # ← will run python3
you may read
this answer on stack overflow about venv and pip versions
and official documentation for venv
you may search for virtual environment on raspberry pi if there is any different setups may be needed but as I remember it is most likely like Ubuntu

Related

Python CLI Menu with Arrow Keys on Windows

The terminal I use on Windows is Mingw-w64 (Git Bash). I am trying to find or create a CLI menu with Python that I can navigate with arrow keys, however nothing I find works.
The Python library, simple-term-menu, doesn't work on Windows. console-menu doesn't use arrow keys but it just throws an error when I import it anyway. After importing windows-curses, I was able to get it working in CMD but not Git Bash (it says, "Redirection is not supported.")
I know for a fact that what I'm after is possible. The JavaScript framework, Adonis, is capable of it with their create command (yarn create adonis-ts-app hello-world). The NPM one doesn't work but Yarn does. Given this, it's obviously possible, but how?
Given all of this, how can I get the CLI menu I want in Git Bash, or how can I get windows-curses to work?
In Windows OS (and only for 32 bits Python versions), you can use 'unicurses' module. You can download it from pypi.org (https://pypi.org/project/UniCurses/1.2/) and install it as a .exe file.
when you have already installed it, it will appear an 'import module error', all about it is explained on this post here in SOF just in case: UniCurses pdcurses.dll Error
Basically you have to download 'pdcurses.dll' (here is a link: https://www.opendll.com/index.php?file-download=pdcurses.dll&arch=32bit&version=3.4.0.0) and move it to a specific directory. It's detalled on the post above.
Here is an example code of how this module works to use it with Arrow Keys:
from unicurses import *
WIDTH = 30
HEIGHT = 10
startx = 0
starty = 0
choices = ["Choice 1", "Choice 2", "Choice 3", "Choice 4", "Exit"]
n_choices = len(choices)
highlight = 1
choice = 0
c = 0
def print_menu(menu_win, highlight):
x = 2
y = 2
box(menu_win, 0, 0)
for i in range(0, n_choices):
if (highlight == i + 1):
wattron(menu_win, A_REVERSE)
mvwaddstr(menu_win, y, x, choices[i])
wattroff(menu_win, A_REVERSE)
else:
mvwaddstr(menu_win, y, x, choices[i])
y += 1
wrefresh(menu_win)
stdscr = initscr()
clear()
noecho()
cbreak()
curs_set(0)
startx = int((80 - WIDTH) / 2)
starty = int((24 - HEIGHT) / 2)
menu_win = newwin(HEIGHT, WIDTH, starty, startx)
keypad(menu_win, True)
mvaddstr(0, 0, "Use arrow keys to go up and down, press ENTER to select a choice")
refresh()
print_menu(menu_win, highlight)
while True:
c = wgetch(menu_win)
if c == KEY_UP:
if highlight == 1:
highlight == n_choices
else:
highlight -= 1
elif c == KEY_DOWN:
if highlight == n_choices:
highlight = 1
else:
highlight += 1
elif c == 10: # ENTER is pressed
choice = highlight
mvaddstr(23, 0, str.format("You chose choice {0} with choice string {1}", choice, choices[choice-1]))
clrtoeol()
refresh()
else:
mvaddstr(22, 0, str.format("Character pressed is = {0}", c))
clrtoeol()
refresh()
print_menu(menu_win, highlight)
if choice == 5:
break
refresh()
endwin()
And here is an image of the result on the command line interface (CMD):
The cutie library might be what you want. Example:
options = [f'Choice {i}' for i in range(1, 5)]
chosen_idx = cutie.select(options)
chosen = options[chosen_idx]
You can use InquirerPy to create a menu like this that works using keyboard navigation
#! /usr/bin/env python3
from InquirerPy import inquirer
fav_lang = inquirer.select(
message = "What's your favorite language:",
choices = ["Go", "Kotlin", "Python", "Rust", "Java", "JavaScript"]
).execute()

OpenVINO: How to build OpenCV with Inference Engine to enable loading models from Model Optimizer

I installed OpenVINO and want to run the following code on windows 10.
import numpy as np
import cv2
import sys
from get_face_id import face_id_getter
from check import check
from win10toast import ToastNotifier
FP = 32
targetId = 0
toaster = None
if '-use_notifications' in sys.argv:
toaster = ToastNotifier()
if len(sys.argv) > 1 and '-m' in sys.argv:
FP = 16
targetId = cv2.dnn.DNN_TARGET_MYRIAD
cap = cv2.VideoCapture(0)
getter = None
if '-get_face_id' in sys.argv:
getter = face_id_getter()
weights = 'face-detection-adas-0001/FP{}/face-detection-adas-0001.bin'.format(FP)
config = 'face-detection-adas-0001/FP{}/face-detection-adas-0001.xml'.format(FP)
weights_emotions, config_emotions, emotions = None, None, None
if len(sys.argv) > 1 and '-use_emotions' in sys.argv:
weights_emotions = 'emotions-recognition-retail-0003/FP{}/emotions-recognition-retail-0003.bin'.format(FP)
config_emotions = 'emotions-recognition-retail-0003/FP{}/emotions-recognition-retail-0003.xml'.format(FP)
framework = 'DLDT'
model = cv2.dnn.readNet(weights, config, framework)
model.setPreferableTarget(targetId=targetId)
if len(sys.argv) > 1 and '-use_emotions' in sys.argv:
emotions = cv2.dnn.readNet(weights_emotions, config_emotions, framework)
emotions.setPreferableTarget(targetId=targetId)
emotions_decode = ('neutral', 'happy', 'sad', 'surprise', 'anger')
names = ["Plotnikov Egor", "Vainberg Roman", "Sataev Emil", "Unknown person"]
emotion_text = None
while(True):
ret, frame = cap.read()
blob = cv2.dnn.blobFromImage(frame, size=(672, 384), crop=False)
have_nots = False
model.setInput(blob)
ans = model.forward()
for i in range(0, 200):
x_min, y_min, x_max, y_max = np.array(ans[0, 0, i, 3:7]) * np.array([640, 480, 640, 480])
if ans[0, 0, i, 2] > 0.5:
cv2.rectangle(frame, (int(x_min), int(y_min)), (int(x_max), int(y_max)), ( 0, 255, 255))
if len(sys.argv) > 1 and '-use_emotions' in sys.argv:
blob_emotions = cv2.dnn.blobFromImage(frame[int(y_min):int(y_max), int(x_min):int(x_max)], size=(64, 64), crop=False)
emotions.setInput(blob_emotions)
ans_emotions = emotions.forward()[0, : , 0 , 0]
ans_emotions = list(map(lambda x: 1 if x > 0.5 else 0, ans_emotions))
_t = ''.join(list(map(str,ans_emotions))).find('1')
if _t == -1:
_t = 0
emotion_text = emotions_decode[_t]
if '-get_face_id' in sys.argv:
_ans = getter.get_answer(frame[int(y_min):int(y_max), int(x_min):int(x_max)])
t = check('labels.txt', _ans)
#print(names[t])
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(frame,names[t],(int(x_min), int(y_min)), font, 1,(255,255,255),2,cv2.LINE_AA)
if emotion_text != None:
cv2.putText(frame,emotion_text,(int(x_min), int(y_max)), font, 1,(255,255,255),2,cv2.LINE_AA)
if '-use_notifications' in sys.argv and not have_nots:
toaster.show_toast("Welcome, " + names[t],"")
have_nots = True
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I want to run a pre-trained OpenVINO model, but get the error:
v\modules\dnn\src\dnn.cpp:2670: error: (-2:Unspecified error) Build OpenCV with Inference Engine to enable loading models from Model Optimizer. in function 'cv::dnn::dnn4_v20190122::Net::readFromModelOptimizer'
I need to build OpenCV with Inference Engine. I'm not experienced in programming and don't know what this means.
When I try this:
https://github.com/opencv/opencv/wiki/Intel%27s-Deep-Learning-Inference-Engine-backend
and try
cmake \
-DWITH_INF_ENGINE=ON \
-DENABLE_CXX11=ON \
...
in the C:\Program Files (x86)\IntelSWTools\openvino_2019.1.148\opencv\samples
it gives an error saying:
CMake Error: The source directory "C:/Program Files (x86)/IntelSWTools/openvino_2019.1.148/opencv/samples/..." does not appear to contain CMakeLists.txt.
even though there is a CMakeLists.txt in that folder.
Can someone please help me?
For me, the solution was to remove the OpenCV Python libraries and install opencv-python-inference-engine
pip3 uninstall opencv-python
pip3 uninstall opencv-contrib-python
pip3 install opencv-python-inference-engine
You should add OpenCV to your environment variables.
Open environment variables window: Type environment variables in search box.
Edit Path from System Variables, insert OpenCV path as your installation path. In my case, I added and able to work with it.
C:\Program Files (x86)\IntelSWTools\openvino\opencv\bin
You also need to check for preferable backend and target to pick inference backend and target hardware.
see following API references:
https://docs.opencv.org/master/d6/d0f/group__dnn.html
https://docs.opencv.org/3.4/db/d30/classcv_1_1dnn_1_1Net.html#a7f767df11386d39374db49cd8df8f59e
https://docs.opencv.org/3.4/db/d30/classcv_1_1dnn_1_1Net.html#a9dddbefbc7f3defbe3eeb5dc3d3483f4
You can just use OpenCV from OpenVINO. It's already compiled with Intel's Inference Engine.

Python3.6 and Pyautogui - Pixel commands - TypeError: __new__() takes 4 positional arguments but 5 were given

I'm relatively new to Python and I'm attempting to make a fun little project using Pyautogui and Python3.6. The goal of this project is to create a tensorflow powered project that learns to play chess. The problem I am now encountering is that whenever I try to use any of the pixel commands - e.g. pyautogui.pixel(...) or screenshot.getpixel(...) - an error pops up and says this:
Traceback (most recent call last):
File "main.py", line 109, in <module>
Score()
File "main.py", line 100, in Score
if gui.pixelMatchesColor(tempX, tempY, (87, 83, 82), tolerance=20):
File "/Users/student/Library/Python/3.6/lib/python/site-packages/pyscreeze/__init__.py", line 413, in pixelMatchesColor
pix = pixel(x, y)
File "/Users/student/Library/Python/3.6/lib/python/site-packages/pyscreeze/__init__.py", line 436, in pixel
return RGB(*screenshot().getpixel((x, y)))
TypeError: __new__() takes 4 positional arguments but 5 were given
I just want to note that all other commands work fine and that it's only the pixel ones that don't work.
I have installed everything including pyautogui(duh), pyscreeze, pymsgbox, pytweening, xlib, opencv, and any other package I could think of. These were installed using this command: pip3 install package-name-here --user. I needed the --user because I don't currently have administrator rights to my computer so I'm wondering if that could have something to do with my current predicament.
I also encountered an earlier post in my search for an answer but I forgot where I found it, so I'm sorry but I can't link it, but basically it said that I should go through and remove all pycache folders. I did this using the terminal command in the ~/Library/Python/3.6 folder:
find . -name "__pycache__" -type f -o -name "__pycache__" -type d -exec rm -rf {} \
I am in no need of an exact solution to this problem, but I'm wondering if there's some way to use the pyautogui.pixelMatchesColor(...) function or any similar one that you recommend that can have a tolerance - e.g. that the RGB values can be 10 units off and still return true.
For those of you that are interested, here is my full code:
#
# IMPORT ALL NECESSARY THINGS
#
import os, time, sys, pyautogui as gui, argparse as arg
#
# FAILSAFES
#
gui.FAILSAFE = True
gui.PAUSE = 0.1
#
# SET UP ARGUMENT PARSER
#
parser = arg.ArgumentParser(description='A machine learning script powered by TensorFlow designed to be run on "chess.com" using Python.')
parser.add_argument("-s", "--sleep", nargs='?', type=int, default='5', help='Number of seconds that the program should sleep before starting. This gives you time to move over to the website before the program looks for the gamboard on screen.')
args = parser.parse_args()
#
# ASKS USER FOR WHAT SIDE IT IS ON
#
side = input("Are you white or black? ")
if side == "W" or side == "w" or side == "white" or side == "White":
side = "W"
elif side == "B" or side == "b" or side == "black" or side == "Black":
side = "B"
else:
print("Invalid selection for which side!")
side = None
sys.exit(0)
#
# PRINT "READY" AND THEN WAIT FOR SPECIFIED AMOUNT OF TIME - DEFAULT 5 SECONDS
#
print("Ready! Waiting for " + str(args.sleep) + " seconds!")
time.sleep(int(args.sleep))
#
# GET AREA OF GAMEBOARD ON SCREEN
#
if side == "W":
gameboard = gui.locateOnScreen('./img/white/chessboard_white.png', confidence=0.55, grayscale=True)
left = gameboard.left - 10
top = gameboard.top - 5
right = gameboard.left + gameboard.width + 10
bottom = gameboard.top + gameboard.height + 15
elif side == "B":
gameboard = gui.locateOnScreen('./img/black/chessboard_black.png', confidence=0.55, grayscale=True)
left = gameboard.left - 10
top = gameboard.top - 5
right = gameboard.left + gameboard.width + 10
bottom = gameboard.top + gameboard.height + 15
widthInterval = (right - gameboard.left) / 8
heightInterval = (bottom - gameboard.top) / 8
#
# DEFINES A FUNCTION THAT COUNTS THE SCORE
# - NUMBER OF YOU SIDE AND THEN SUBTRACT THE NUMBER OF OPPOSITE SIDE
#
def Score():
for i in range(8):
for j in range(8):
tempX = 32 + (i * widthInterval)
tempY = 32 + (j * heightInterval)
if gui.pixelMatchesColor(tempX, tempY, (87, 83, 82), tolerance=20):
print("True!")
if side == "W":
print("White!")
elif side == "B":
print("Black!")
Score()
Note: The problem occurs in the last 10ish lines of the above code.
Thank you so much for your help and please don't hesitate to let me know if you need any more info from me!
Max

cannot find evdev2 module

In visual studio I am trying to upload my code onto the ev3de (which is in python). It does work but as soon as I try to run it on the ev3, the program goes straight back to the screen before. When I try and run the program there are a few errors: It cannot find a module called pyev3, which I have never heard of, and it also cannot find the cwiid module, for the wiimote. Here is the code (it's not from myself):
#!/usr/bin/env python3
# Drive your robot with a wii remote!
# Left motor on port B, right motor on port C,
# vertical arm on port D.
# Requires the package 'python-cwiid'.
# Make sure bluetooth is enabled in brickman
# before trying to use this. Hold 2 to go forward
# and 1 to go backward.
import sys
import os
import time
import cwiid
import pyev3
def clamp(value, lower, upper):
return min(upper, max(value, lower))
print('press 1+2 on the wiimote now')
time.sleep(1)
w = cwiid.Wiimote()
print('connected?')
w.led = 6
w.rpt_mode = cwiid.RPT_ACC | cwiid.RPT_BTN
left_motor = pyev3.Motor(pyev3.OUTPUT_B)
left_motor.reset()
left_motor.run_mode = 'forever'
left_motor.regulation_mode = 'on'
right_motor = pyev3.Motor(pyev3.OUTPUT_C)
right_motor.reset()
right_motor.run_mode = 'forever'
right_motor.regulation_mode = 'on'
arm = pyev3.Motor(pyev3.OUTPUT_D)
arm.reset()
arm.run_mode = 'forever'
arm.regulation_mode = 'off'
target_distance = 8
top_speed = 720
left_motor.run = 1
right_motor.run = 1
last_btn_state = 0
move = 0
try:
while True:
state = w.state
buttons = state['buttons']
if buttons != last_btn_state:
if buttons & cwiid.BTN_MINUS:
top_speed -= 10
print (top_speed)
if buttons & cwiid.BTN_PLUS:
top_speed += 10
print (top_speed)
if buttons & cwiid.BTN_2:
move = 1
elif buttons & cwiid.BTN_1:
move = -1
else:
move = 0
if buttons & cwiid.BTN_LEFT:
arm.duty_cycle_sp = 100
arm.run = 1
elif buttons & cwiid.BTN_RIGHT:
arm.duty_cycle_sp = -100
arm.run = 1
else:
arm.run = 0
print (top_speed, move)
last_btn_state = buttons
if move:
acc = state['acc']
tilt = (clamp(acc[1], 95, 145) - 120) / 25.0 # roughly between -0.5 and 0.5
turn = top_speed * tilt
turn = clamp(turn, -abs(top_speed), abs(top_speed))
left_motor.pulses_per_second_sp = int(top_speed - turn) * move
right_motor.pulses_per_second_sp = int(top_speed + turn) * move
else:
left_motor.pulses_per_second_sp = 0
right_motor.pulses_per_second_sp = 0
finally:
left_motor.run = 0
right_motor.run = 0
When I run this one in Visual Studio Code, this happens:
File "c:/Users/User/Documents/fingers_crossed/drive.py", line 13, in
import cwiid ModuleNotFoundError: No module named 'cwiid' PS
C:\Users\User\Documents\fingers_crossed>
Also, why can't my robot find the ev3dev2 module?

Error in python: double free or corruption (out): 0x0000000001e4b030

Code &source
ubuntu 16.04
GNU radio 3.7.12
UHD 3.10.1.1
Numpy 1.13.1
Scipy 0.19.1
I met this problem when I use Gnuradio to genarate a dataset,These codes used to work well until I change another computer,I search this problem and find that someone think it's a problem of Numpy,but I'm not surely understand .
If anybody has any idea how I could debug this or what could possibly be the cause of this; all tips are welcome!
Here is the error report:
StackTrace:
double free or corruption (out): 0x0000000001e4b030
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7ffa89d707e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7ffa89d7937a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7ffa89d7d53c]
/usr/local/lib/libgnuradio-runtime-3.7.12git.so.0.0.0(_ZN2gr5blockD1Ev+0x77)[0x7ffa882768e7]
/usr/local/lib/libgnuradio-mediatools.so(+0xd065)[0x7ffa6940b065]
/usr/local/lib/python2.7/dist-packages/mediatools/_mediatools_swig.so(+0xbd2a)[0x7ffa6962bd2a]
/usr/local/lib/python2.7/dist-packages/mediatools/_mediatools_swig.so(+0xfe60)[0x7ffa6962fe60]
python(PyObject_Call+0x43)[0x4b0cb3]
python(PyObject_CallFunctionObjArgs+0x16a)[0x4b97fa]
/usr/local/lib/python2.7/dist-packages/mediatools
/_mediatools_swig.so(+0x12640)[0x7ffa69632640]
python[0x4fd4e6]
python[0x4fd4e6]
python(PyDict_SetItem+0x442)[0x4a0d22]
python(_PyModule_Clear+0x133)[0x502bf3]
python(PyImport_Cleanup+0x1ac)[0x50275c]
python(Py_Finalize+0x89)[0x500489]
python(Py_Main+0x46f)[0x49df2f]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7ffa89d19830]
python(_start+0x29)[0x49d9d9]
======= Memory map: ========
and Here is the code:
#!/usr/bin/env python
from gnuradio import gr, blocks
import mediatools
import numpy as np
class source_alphabet(gr.hier_block2):
def __init__(self, dtype="discrete", limit=10000, randomize=False):
if(dtype == "discrete"):
gr.hier_block2.__init__(self, "source_alphabet",
gr.io_signature(0,0,0),
gr.io_signature(1,1,gr.sizeof_char))
self.src = blocks.file_source(gr.sizeof_char, "source_material/gutenberg_shakespeare.txt")
self.convert = blocks.packed_to_unpacked_bb(1, gr.GR_LSB_FIRST);
#self.convert = blocks.packed_to_unpacked_bb(8, gr.GR_LSB_FIRST);
self.limit = blocks.head(gr.sizeof_char, limit)
self.connect(self.src,self.convert)
last = self.convert
# whiten our sequence with a random block scrambler (optionally)
if(randomize):
rand_len = 256
rand_bits = np.random.randint(2, size=rand_len)
self.randsrc = blocks.vector_source_b(rand_bits, True)
self.xor = blocks.xor_bb()
self.connect(self.randsrc,(self.xor,1))
self.connect(last, self.xor)
last = self.xor
else: # "type_continuous"
gr.hier_block2.__init__(self, "source_alphabet",
gr.io_signature(0,0,0),
gr.io_signature(1,1,gr.sizeof_float))
self.src = mediatools.audiosource_s(["source_material/serial-s01-e01.mp3"])
self.convert2 = blocks.interleaved_short_to_complex()
self.convert3 = blocks.multiply_const_cc(1.0/65535)
self.convert = blocks.complex_to_float()
self.limit = blocks.head(gr.sizeof_float, limit)
# print(self.limit)
self.connect(self.src,self.convert2,self.convert3, self.convert)
last = self.convert
# connect head or not, and connect to output
if(limit==None):
self.connect(last, self)
else:
self.connect(last, self.limit, self)
if __name__ == "__main__":
print "QA..."
# Test discrete source
tb = gr.top_block()
src = source_alphabet("discrete", 1000)
snk = blocks.vector_sink_b()
tb.run()
# Test continuous source
tb = gr.top_block()
src = source_alphabet("continuous", 1000)
snk = blocks.vector_sink_f()
tb.run()

Categories

Resources