My training script for the model:
seed = 42
import random
import os
import numpy as np
def seed_everything(seed):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
seed_everything(seed)
from detectron2.engine import DefaultTrainer
from detectron2.config import get_cfg
from detectron2.data.catalog import Metadata
import os
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml"))
cfg.DATASETS.TRAIN = ("experiment",)
cfg.DATASETS.TEST = ("test",)
cfg.DATALOADER.NUM_WORKERS = 2
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7
cfg.MODEL.DEVICE = "cuda"
cfg.SOLVER.IMS_PER_BATCH = 2
num_gpu = 1
bs = (num_gpu * 2)
cfg.SOLVER.BASE_LR = 0.02 * bs / 16
cfg.SOLVER.MAX_ITER = 7500
cfg.MODEL.ROI_HEADS.BATCH_SIZE_PER_IMAGE = 128
cfg.MODEL.ROI_HEADS.NUM_CLASSES = 4
os.makedirs(cfg.OUTPUT_DIR, exist_ok=True)
trainer = DefaultTrainer(cfg)
trainer.resume_or_load(resume=False)
trainer.train()
My inference script on server-1 is:
import cv2
cfg.MODEL.WEIGHTS = os.path.join(cfg.OUTPUT_DIR, "model_final.pth")
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7
cfg.SEED = 42
predictor = DefaultPredictor(cfg)
img = cv2.imread('filename.jpg')
outputs = predictor(img)
print(outputs["instances"])
pred_classes = outputs['instances'].pred_classes.tolist()
classes = ["Handwritten", "Logo", "Markings", "Signature"]
for pred_class in pred_classes:
print('*'*10)
print(classes[pred_class])
print('*'*10)
if any(classes[pred_class] == "Handwritten" for pred_class in pred_classes):
print(True)
else:
print(False)
My inference script on server-2 is:
class Handwritten:
"""
Detects a list of handwritten pages in a PDF chart.
Attributes
----------
path_of_model : str
Path where the trained model is stored.
path_of_weights : str
Path where the weights file is stored.
"""
def __init__(self, path_of_weights: str) -> None:
"""Initialize Handwritten class.
Parameters
----------
path_of_model : str
path_of_weights : str
"""
self.cfg = get_cfg()
self.cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.7
self.cfg.MODEL.ROI_HEADS.NUM_CLASSES = 4
self.cfg.MODEL.WEIGHTS = path_of_weights
self.cfg.MODEL.DEVICE = "cpu"
self.cfg.SEED = 42
self.predictor = DefaultPredictor(self.cfg)
self.metadata = Metadata()
self.metadata.set(
thing_classes=["Handwritten", "Logo", "Markings", "Signature"],
thing_dataset_id_to_contiguous_id={0: 0, 1: 1, 2: 2, 3: 3},
)
def __call__(self, img: Any) -> Any:
"""Return the predicted output classes for the image."""
self.outputs = self.predictor(img)
return self.outputs["instances"]
def detect_hw(self, image: Any) -> bool:
"""Detect handwritten dx entity in image and if present then classifies it as hw page.
Parameters
----------
image : Matrix
.Image matrix of a page.
Return
-------
True/False : bool
Boolean value that states if the page is handwritten or not.
"""
outputs = self.__call__(image)
pred_classes = outputs.pred_classes.tolist()
classes = ["Handwritten", "Logo", "Markings", "Signature"]
if any(classes[pred_class] == "Handwritten" for pred_class in pred_classes):
return True
else:
return False
app = FastAPI()
path_of_weights = "model/model_final.pth"
model = Handwritten(path_of_weights)
#app.post("/cv/predict", status_code=200)
def predict(
page_no: int = Form(...), dimensions: list = Form(...), image: UploadFile = File(...)
) -> Dict[str, int]:
"""Predicts if image is handwritten page or not.
Parameters
----------
page_no : Page number of the given input page
dimensions : Height and width of the page
image : Image of the page as bytestream
"""
image_bytes = image.file.read()
decoded_image = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
height, width = int(dimensions[0]), int(dimensions[1])
prediction_time = time.time()
pg_image = cv2.resize(decoded_image, (height, width))
try:
# Check if page is handwritten
hw_result = model.detect_hw(pg_image)
# If handwritten, consider for output
if hw_result:
hw_pages = page_no
else:
hw_pages = -99
prediction_info = {
"hw_pages": hw_pages,
"prediction_time": prediction_time,
}
#_logger.info(f"prediction info: {prediction_info}")
except HTTPError as e:
do something
return {"hw_pages": hw_pages}
While the model keeps giving good results on server-1, it is somehow being very erratic in server-2. The weights and the seed is the same. Somehow, I am unable to understand this change in behavior in both of these scenarios.
The model is trained on server-1
Server-1 is g4dn.2xlarge. Server-2 is g4dn.xlarge
Is there something wrong which I am doing?
I am trying to be able to display labels that are tied to a frame. I am unable to get either to show. There is something going on because packing or adding these changes the window size.
Main creates the main app, from which I create several frames that would belong to server objects. When servers are updated, they should reflect the change in the frames (and the labels attached to those frames) that are their respective attributes. However neither the frame nor labels display any text or color.
main.py
from settings.gui_settings import GLOBAL_FONT, SERVER_HEADER_COLUMN_FONT
from tkinter import *
from server import Server
from server_gui import ServerGui
SERVERS = []
# get_servers()
SERVERS = [
Server(hostname='tyan-a320-1', ipv4='10.86.201.3', bmc_ipv4='10.86.203.88'),
Server(hostname='tyan-a320-2', ipv4='10.86.201.91', bmc_ipv4='10.86.202.250'),
Server(hostname='tyan-a320-3', ipv4='10.86.201.13', bmc_ipv4='10.86.201.2'),
Server(hostname='tyan-a320-4', ipv4='10.86.201.50', bmc_ipv4='10.86.200.243'),
]
main_window = Tk()
for server in SERVERS:
server.gui = ServerGui(main_window)
server.gui.create_label('title', textvariable=server.hostname, font=(GLOBAL_FONT, SERVER_HEADER_COLUMN_FONT),\
bg='red', container=True)
server.gui.labels['title'].pack()
server.gui.pack()
#server.update()
last_update_lbl = Label(master=main_window, text=f'Last Update: {time.ctime()}')
last_update_lbl.pack(side=TOP)
#main_window.update()
main_window.mainloop()
server.py
from settings.gui_settings import UP_COLOR, DOWN_COLOR
from diagnostics import poll
from diagnostics import ping
from diagnostics import SERVICES
class Server:
def __init__(self, *args, **kwargs):
for k, v in kwargs.items():
self.__setattr__(k, v)
self.services = {}
for service in SERVICES:
self.services[service] = None
def update(self):
address = None
for service in self.services.keys():
if 'bmc' in service:
address = self.bmc_ipv4
else:
address = self.ipv4
result = None
if service == 'icmp':
result = ping(address)
else:
result = poll(address, SERVICES[service])
if result:
self.services[service] = f'{service}: UP'
else:
self.services[service] = f'{service}: DOWN'
if hasattr(self, 'gui'):
self.gui.update_label(service, 'textvariable', self.services[service])
self.gui.update_label(service, 'bg', UP_COLOR if 'UP' in self.services[service] else DOWN_COLOR)
self.gui.master.update()
server_gui.py
from tkinter import Frame, Label, StringVar
class ServerGui(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.labels = {}
def create_label(self, name, **kwargs):
if not len(name):
print("Label not named")
exit(0)
text = None
label = Label(self)
for k, v in kwargs.items():
if k == 'textvariable':
text = StringVar(master=label, value=v)
label.textvariable = text
else:
label.__setattr__(k, v)
if 'bg' not in kwargs.keys():
label.bg = LABEL_DEFAULT_COLOR
if not text:
text = StringVar(master=label, value=name)
self.labels[name] = label
self.labels[name].pack()
print('Label %s created' % name)
def update_label(self, name, attr, value):
if name not in self.labels:
self.create_label(name,
textvariable=StringVar(self, f'{name}'),
font=(GLOBAL_FONT, SERVER_INFO_FONT),
padx=10,
pady=10
)
self.labels[name].pack()
if attr == 'textvariable':
self.labels[name].textvariable.set(value)
else:
setattr(self.labels[name], attr, value)
settings/gui_settings.py
MAIN_WINDOW_MIN_WIDTH = 700
GLOBAL_FONT = 'Tahoma'
SERVER_HEADER_COLUMN_FONT = 20
SERVER_INFO_FONT = 12
UP_COLOR = 'green'
DOWN_COLOR = 'red'
LABEL_DEFAULT_COLOR = 'green'
When I am running a pyopengl program, I get an error.
I searhed the web but all it says is that it is a pyopengl version problem, but I am using the latest update.
Traceback (most recent call last):
File "C:/Users/TheUser/Desktop/MyPytonDen/ThinMatrixOpenGl/engineTester/MainGameLoop.py", line 10, in
from ThinMatrixOpenGl.renderEngine.MasterRenderer import MasterRendererClass
File "C:\Users\TheUser\Desktop\MyPytonDen\ThinMatrixOpenGl\renderEngine\MasterRenderer.py", line 10, in
class MasterRendererClass:
File "C:\Users\TheUser\Desktop\MyPytonDen\ThinMatrixOpenGl\renderEngine\MasterRenderer.py", line 11, in MasterRendererClass
shader = StaticShaderClass()
File "C:\Users\TheUser\Desktop\MyPytonDen\ThinMatrixOpenGl\shaders\staticShader.py", line 22, in init
super().init(self.VERTEX_FILE, self.FRAGMENT_FILE)
File "C:\Users\TheUser\Desktop\MyPytonDen\ThinMatrixOpenGl\shaders\shaderProgram.py", line 13, in init
self.Vertex_Shader_Id = Load_Shader(vertex_file, GL_VERTEX_SHADER)
File "C:\Users\TheUser\Desktop\MyPytonDen\ThinMatrixOpenGl\shaders\shaderProgram.py", line 84, in Load_Shader
Shader_Id = glCreateShader(type_of_shader)
File "C:\Users\TheUser\AppData\Local\Programs\Python\Python38-32\lib\site-packages\OpenGL\platform\baseplatform.py", line 423, in call
raise error.NullFunctionError(
OpenGL.error.NullFunctionError: Attempt to call an undefined function glCreateShader, check for bool(glCreateShader) before calling
Process finished with exit code 1
I checked the OpenGL source code. Not that I meddle with it in the first place but its fine.
For some reason, StaticShader refuses to initialize now.
In my program, before doing some change, it was working just fine and it is still working in some other project.
Despite I didn't even get close to shader codes it gave me this.
What exactly is this and how can I handle it.
Btw while this poped up I was trying to update the render algorithm although it did not change much.
class StaticShaderClass(ShaderProgramClass):
VERTEX_FILE = "../shaders/vertexShader.txt"
FRAGMENT_FILE = "../shaders/fragmentShader.txt"
location_transformation_matrix: int
location_projection_matrix: int
location_view_matrix: int
location_light_position: int
location_light_color: int
location_shine_damper: int
location_reflectivity: int
def __init__(self):
super().__init__(self.VERTEX_FILE, self.FRAGMENT_FILE)
def Bind_Attributes(self):
super().Bind_Attribute(0, "position")
super().Bind_Attribute(1, "texture_coord")
super().Bind_Attribute(2, "normal")
def GetAllUniformLocation(self):
self.location_transformation_matrix = super().GetUniformLocation("transformation_matrix")
self.location_projection_matrix = super().GetUniformLocation("projection_matrix")
self.location_view_matrix = super().GetUniformLocation("view_matrix")
self.location_light_position = super().GetUniformLocation("light_position")
self.location_light_color = super().GetUniformLocation("light_color")
self.location_shine_damper = super().GetUniformLocation("shine_damper")
self.location_reflectivity = super().GetUniformLocation("reflectivity")
def Load_Shine_Variables(self, damper, reflectivity):
Load_Float(self.location_shine_damper, damper)
Load_Float(self.location_reflectivity, reflectivity)
def Load_Transformation_Matrix(self, matrix: Matrix44):
super().Load_Matrix(self.location_transformation_matrix, matrix)
def Load_Projection_Matrix(self, projection: Matrix44):
super().Load_Matrix(self.location_projection_matrix, projection)
def Load_view_Matrix(self, camera: CameraClass):
view_matrix = Maths.Create_view_Matrix(camera)
super().Load_Matrix(self.location_view_matrix, view_matrix)
def Load_Light(self, light: Light):
Load_Vector(self.location_light_position, light.position)
Load_Vector(self.location_light_color, light.color)
class ShaderProgramClass(ABC):
Program_Id: int
Vertex_Shader_Id: int
Fragment_Shader_Id: int
def __init__(self, vertex_file: str, fragment_file: str):
self.Vertex_Shader_Id = Load_Shader(vertex_file, GL_VERTEX_SHADER)
self.Fragment_Shader_Id = Load_Shader(fragment_file, GL_FRAGMENT_SHADER)
self.Program_Id = glCreateProgram()
glAttachShader(self.Program_Id, self.Vertex_Shader_Id)
glAttachShader(self.Program_Id, self.Fragment_Shader_Id)
self.Bind_Attributes()
glLinkProgram(self.Program_Id)
# glGetProgramInfoLog(self.Program_Id)
glValidateProgram(self.Program_Id)
self.GetAllUniformLocation()
def Start(self):
glUseProgram(self.Program_Id)
def Clean_up(self):
self.Stop()
glDetachShader(self.Program_Id, self.Vertex_Shader_Id)
glDetachShader(self.Program_Id, self.Fragment_Shader_Id)
glDeleteShader(self.Vertex_Shader_Id)
glDeleteShader(self.Fragment_Shader_Id)
glDeleteProgram(self.Program_Id)
#abstractmethod
def Bind_Attributes(self):
pass
def Bind_Attribute(self, attribute: int, variable_name: str):
glBindAttribLocation(self.Program_Id, attribute, variable_name)
#staticmethod
def Stop():
glUseProgram(0)
#abstractmethod
def GetAllUniformLocation(self):
pass
def GetUniformLocation(self, uniform_name: str):
return glGetUniformLocation(self.Program_Id, uniform_name)
#staticmethod
def Load_Matrix(location, matrix):
matrix = np.array(matrix, dtype=np.float32)
# it may require matrix s data type to change float later
glUniformMatrix4fv(location, 1, False, matrix)
def Load_Float(location: int, value: float):
glUniform1f(location, value)
def Load_Vector(location: int, vector: Vector3):
glUniform3f(location, vector.x, vector.y, vector.z)
def Load_Boolean(location: int, value: bool):
to_load = 0
if value:
to_load = 1
glUniform1f(location, to_load)
def Load_Shader(file: str, type_of_shader: int):
try:
src = ""
with open(file, "r") as f:
text = f.readlines()
for i in text:
src += str(i)
except ():
raise Exception(FileNotFoundError, "file is not exist or could not be readied for some reason")
Shader_Id = glCreateShader(type_of_shader)
print(Shader_Id)
glShaderSource(Shader_Id, src)
glCompileShader(Shader_Id)
if glGetShaderiv(Shader_Id, GL_COMPILE_STATUS) == GL_FALSE:
print(glGetShaderInfoLog(Shader_Id))
print("could not compile shader!")
return Shader_Id
#version 400 core
in vec3 position;
in vec2 texture_coord;
in vec3 normal;
out vec2 pass_texture_coord;
out vec3 surface_normal;
out vec3 to_light_vector;
out vec3 to_camera_vector;
uniform mat4 transformation_matrix;
uniform mat4 projection_matrix;
uniform mat4 view_matrix;
uniform vec3 light_position;
void main(){
vec4 world_position = transformation_matrix * vec4(position, 1.0f);
gl_Position = projection_matrix * view_matrix * world_position;
pass_texture_coord = texture_coord;
surface_normal = (transformation_matrix * vec4(normal,0.0)).xyz;
to_light_vector = light_position - world_position.xyz;
to_camera_vector = (inverse(view_matrix) * vec4(0.0,0.0,0.0,1.0)).xyz - world_position.xyz;
}
Let me quote Python class attributes are evaluated on declaration:
In Python, class attributes are evaluated and put into memory when the class is defined (or imported).
A valid and current OpenGL context is required for each OpenGL instruction, such as for creating the shader program. Therefore, if the shader program is stored in a class attribute and the class is defined or imported before the OpenGL window and context are created, the shader program cannot be generated.
I got this error when I tried to run my gnuradio python program through Flask webserver. I am getting this error when I added my USRP b200 lines of code into my original "working/healthy" code. In this program I am trying to control the variables of my code through slider widgets in my Flask webserver.
Again, the USRP that I am using works just fine whenever I I run any app in my GnuRadio software itself. But when I try it through Flask it runs for a second or 2 then crashes.
Any assistance would be highly appreciated.
error Traceback:
linux; GNU C++ version 7.3.0; Boost_106501; UHD_003.010.003.000-0-unknown
[top_block_22] __init__: sample_rate: 0
[top_block_22] __init__: amplitude: 0
[top_block_22] __init__: frequency: 0
[top_block_22] __init__: bandwidth: 0
[top_block_22] __init__: USRPsamp_rate: 0
[top_block_22] __init__: gain: 0
[top_block_22] __init__: center_frequency: 0
-- Detected Device: B200mini
-- Operating over USB 3.
-- Initialize CODEC control...
-- Initialize Radio control...
-- Performing register loopback test... pass
-- Performing CODEC loopback test... pass
-- Setting master clock rate selection to 'automatic'.
-- Asking for clock rate 16.000000 MHz...
-- Actually got clock rate 16.000000 MHz.
-- Performing timer loopback test... pass
gr::log :INFO: audio source - Audio sink arch: alsa
UHD Warning:
The hardware does not support the requested TX sample rate:
Target sample rate: 0.000000 MSps
Actual sample rate: 0.031250 MSps
-- Asking for clock rate 32.000000 MHz...
-- Actually got clock rate 32.000000 MHz.
-- Performing timer loopback test... pass
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU * Serving Flask app "app" (lazy loading)
U * Environment: production
UU WARNING: This is a development server. Do not use it in a production deployment.
UU Use a production WSGI server instead.
UU * Debug mode: on
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
UUUU * Restarting with stat
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUlinux; GNU C++ version 7.3.0; Boost_106501; UHD_003.010.003.000-0-unknown
UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU[top_block_22] __init__: sample_rate: 0
[top_block_22] __init__: amplitude: 0
[top_block_22] __init__: frequency: 0
[top_block_22] __init__: bandwidth: 0
[top_block_22] __init__: USRPsamp_rate: 0
[top_block_22] __init__: gain: 0
[top_block_22] __init__: center_frequency: 0
Traceback (most recent call last):
File "/home/fit-pc/my_flask_app/virtualenv/Slider/app.py", line 175, in <module>
tb = top_block_22(0, 0, 0, 0, 0, 0, 0)
File "/home/fit-pc/my_flask_app/virtualenv/Slider/app.py", line 48, in __init__
channels=range(1),
File "/usr/lib/python2.7/dist-packages/gnuradio/uhd/__init__.py", line 122, in constructor_interceptor
return old_constructor(*args)
File "/usr/lib/python2.7/dist-packages/gnuradio/uhd/uhd_swig.py", line 3012, in make
return _uhd_swig.usrp_sink_make(*args)
RuntimeError: LookupError: KeyError: No devices found for ----->
Device Address:
b200:
[Finished in 85.7s with exit code 1]
[shell_cmd: python -u "/home/fit-pc/my_flask_app/virtualenv/Slider/app.py"]
[dir: /home/fit-pc/my_flask_app/virtualenv/Slider]
[path: /home/fit-pc/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
app.py code:
from __future__ import print_function
from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio.eng_option import eng_option
from gnuradio.filter import firdes
from optparse import OptionParser
from gnuradio import uhd
import time
class top_block_22(gr.top_block): # PEP8: CamelCaseName for classes
def __init__(self, sample_rate=0, amplitude=0, frequency=0, bandwidth=0, gain=0, center_frequency=0, USRPsamp_rate=0):
gr.top_block.__init__(self, "Top Block 22")
##################################################
# Variables
##################################################
self.sample_rate = sample_rate
print('[top_block_22] __init__: sample_rate:', self.sample_rate)
self.amplitude = amplitude
print('[top_block_22] __init__: amplitude:', self.amplitude)
self.frequency = frequency
print('[top_block_22] __init__: frequency:', self.frequency)
self.bandwidth = bandwidth
print('[top_block_22] __init__: bandwidth:', self.bandwidth)
self.USRPsamp_rate = USRPsamp_rate
print('[top_block_22] __init__: USRPsamp_rate:', self.USRPsamp_rate)
self.gain = gain
print('[top_block_22] __init__: gain:', self.gain)
self.center_frequency = center_frequency
print('[top_block_22] __init__: center_frequency:', self.center_frequency)
##################################################
# Blocks
##################################################
self.uhd_usrp_sink_0 = uhd.usrp_sink(
",".join(("b200", "")),
uhd.stream_args(
cpu_format="sc16",
channels=range(1),
),
)
# for mute_on, mute_off
#self.old_sample_rate = self.sample_rate
#self.old_ampliture = self.ampliture
#self.old_frequency = self.frequency
#self.old_bandwidth = self.bandwidth
##################################################
# Blocks
##################################################
self.blocks_add_xx = blocks.add_vff(1)
self.audio_sink = audio.sink(32000, '', True)
self.analog_sig_source_x_0 = analog.sig_source_f(sample_rate, analog.GR_COS_WAVE, frequency, amplitude, 0)
self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN, amplitude, -42)
self.uhd_usrp_sink_0.set_samp_rate(USRPsamp_rate)
self.uhd_usrp_sink_0.set_antenna('TX/RX', 0)
self.uhd_usrp_sink_0.set_center_freq(center_frequency, 0)
self.uhd_usrp_sink_0.set_gain(gain, 0)
self.uhd_usrp_sink_0.set_bandwidth(bandwidth, 0)
##################################################
# Connections
##################################################
self.connect((self.analog_noise_source_x_0, 0), (self.blocks_add_xx, 1))
self.connect((self.analog_sig_source_x_0, 0), (self.blocks_add_xx, 0))
self.connect((self.blocks_add_xx, 0), (self.audio_sink, 0))
self.connect((self.analog_noise_source_x_0, 0), (self.uhd_usrp_sink_0, 0))
def change_sample_rate(self, value=None):
if value is not None:
self.sample_rate = value
print('[top_block_22] change: sample_rate:', value)
self.analog_sig_source_x_0.set_sampling_freq(value)
def change_amplitude(self, value=None):
if value is not None:
value /= 10000.
self.amplitude = value
print('[top_block_22] change: amplitude:', value)
self.analog_sig_source_x_0.set_amplitude(value)
self.analog_noise_source_x_0.set_amplitude(value)
def change_frequency(self, value=None):
if value is not None:
self.frequency = value
print('[top_block_22] change: frequency:', value)
self.analog_sig_source_x_0.set_frequency(value)
#TODO: change some values
def change_bandwidth(self, value=None):
if value is not None:
self.bandwidth = value
print('[top_block_22] change: bandwidth:', value)
self.uhd_usrp_sink_0.set_bandwidth(value)
def change_gain(self, value=None):
if value is not None:
self.gain = value
print('[top_block_22] change: gain:', value)
self.uhd_usrp_sink_0.set_gain(value)
def change_center_frequency(self, value=None):
if value is not None:
self.center_frequency = value
print('[top_block_22] change: center_frequency:', value)
self.uhd_usrp_sink_0.set_center_freq(value)
def change_USRPsamp_rate(self, value=None):
if value is not None:
self.USRPsamp_rate = value
print('[top_block_22] change: USRPsamp_rate:', value)
self.uhd_usrp_sink_0.set_USRPsamp_rate(value)
def change(self, sample_rate=None, amplitude=None, frequency=None, bandwidth=None, gain=None, center_frequency=None, USRPsamp_rate=None):
#self.change_sample_rate(sample_rate)
#self.change_amplitude(amplitude)
#self.change_frequency(frequency)
#self.change_bandwidth(bandwidth)
#self.change_gain(gain)
#self.change_center_frequency(center_frequency)
#self.change_USRPsamp_rate(center_USRPsamp_rate)
if sample_rate is not None:
self.change_sample_rate(sample_rate)
if amplitude is not None:
self.change_amplitude(amplitude)
if frequency is not None:
self.change_frequency(frequency)
if bandwidth is not None:
self.change_bandwidth(bandwidth)
if gain is not None:
self.change_gain(gain)
if center_frequency is not None:
self.change_center_frequency(center_frequency)
if USRPsamp_rate is not None:
self.change_USRPsamp_rate(USRPsamp_rate)
def turn_off(self):
self.change(0, 0, 0, 0, 0, 0, 0)
#def mute_on(self):
# # remember values
# self.old_sample_rate = self.sample_rate
# self.old_ampliture = self.ampliture
# self.old_frequency = self.frequency
# self.old_ampliture = self.gain
# self.old_center_frequency = self.center_frequency
# self.old_USRPsamp_rate = self.USRPsamp_rate
# # turn off sound
# self.change(0, 0, 0, 0, 0, 0, 0)
#def mute_off(self):
# # set old values
# self.change(self.old_sample_rate, self.old_ampliture, self.old_frequency, self.old_gain, self.old_center_frequency, self.old_USRPsamp_rate)
# -----------------------------------------------------------------------------
from flask import Flask, request, jsonify
app = Flask(__name__)
# start with default values
#tb = top_block_22()
tb = top_block_22(0, 0, 0, 0, 0, 0, 0)
tb.start(True)
#app.route('/')
def index():
return '''<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GNURadio Slider Example</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/roundSlider/1.3.2/roundslider.min.js"></script>
<style>
.slider {
position: absolute;
align:center;
}
.row1 {top:100px;}
.row2 {top:450px;}
.row3 {top:750px;}
.col1 {left:75px;}
.col2 {left:470px;}
.col3 {left:870px;}
.col1 {left:75px;}
</style>
</head>
<body>
<div id="slider1" class='slider row1 col1'></div>
<!-- <p>Sample Rate Slider</p> -->
<div id="slider2" class='slider row1 col2'></div>
<!-- <p>Amplitude Slider2</p> -->
<div id="slider3" class='slider row1 col3'></div>
<!-- <p>Frequency Slider3</p> -->
<div id="slider4" class='slider row2 col1'></div>
<!-- <p>Bandwidth Slider4</p> -->
<div id="slider5" class='slider row2 col2'></div>
<!-- <p>Gain Slider5</p> -->
<div id="slider6" class='slider row2 col3'></div>
<!-- <p>Center Frequency Slider6</p> -->
<div id="slider7" class='slider row3 col1'></div>
<!-- <p>USRP Sample Rate Slider7</p> -->
<button id="turn_off_button">TURN OFF</button>
<script>
// create sliders
$("#slider1").roundSlider({
//sliderType: "min-range",
radius: 150,
min: 0,
max: 1000000000000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide1_val: event.value}); }
change: function(event) { $.getJSON('/set_sample_rate/' + event.value); }
});
$("#slider2").roundSlider({
//sliderType: "min-range",
radius: 150,
min: 0,
max: 1000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide2_val: event.value}); }
change: function(event) { $.getJSON('/set_amplitude/' + event.value); }
});
$("#slider3").roundSlider({
radius: 150,
min: 0,
max: 10000000000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide3_val: event.value}); }
change: function(event) { $.getJSON('/set_frequency/' + event.value); }
});
$("#slider4").roundSlider({
radius: 150,
min: 0,
max: 10000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide4_val: event.value}); }
change: function(event) { $.getJSON('/set_bandwidth/' + event.value); }
});
$("#slider5").roundSlider({
radius: 150,
min: 0,
max: 10000000000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide5_val: event.value}); }
change: function(event) { $.getJSON('/set_gain/' + event.value); }
});
$("#slider6").roundSlider({
radius: 150,
min: 0,
max: 10000000000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide6_val: event.value}); }
change: function(event) { $.getJSON('/set_center_frequency/' + event.value); }
});
$("#slider7").roundSlider({
radius: 150,
min: 0,
max: 10000000000,
value: 0, // default value at start
//change: function(event) { $.getJSON('/valueofslider', {slide7_val: event.value}); }
change: function(event) { $.getJSON('/set_USRPsamp_rate/' + event.value); }
});
$("#turn_off_button").click(function(){
// set sliders
$("#slider1").data("roundSlider").setValue(0);
$("#slider2").data("roundSlider").setValue(0);
$("#slider3").data("roundSlider").setValue(0);
$("#slider4").data("roundSlider").setValue(0);
$("#slider5").data("roundSlider").setValue(0);
$("#slider6").data("roundSlider").setValue(0);
$("#slider7").data("roundSlider").setValue(0);
// send to server
$.getJSON('/valueofslider', {
slide1_val: 0,
slide2_val: 0,
slide3_val: 0,
slide4_val: 0,
slide5_val: 0,
slide6_val: 0,
slide7_val: 0,
});
});
</script>
</body>
</html>'''
#app.route('/off')
def off():
"""Turn off sound."""
tb.turn_off()
#return jsonify({'val': 0})
return 'off'
#app.route('/set_sample_rate/<int:value>')
def set_sample_rate(value):
#sound(sample_rate=value)
tb.change_sample_rate(value)
#return jsonify({'sample_rate': value})
return str(value)
#app.route('/set_amplitude/<int:value>')
def set_amplitude(value):
#sound(amplitude=value)
tb.change_amplitude(value)
#return jsonify({'amplitude': value})
return str(value)
#app.route('/set_frequency/<int:value>')
def set_frequency(value):
#sound(frequency=value)
tb.change_frequency(value)
#return jsonify({'frequency': value})
return str(value)
#app.route('/set_bandwidth/<int:value>')
def set_bandwidth(value):
#sound(frequency=value)
tb.change_bandwidth(value)
#return jsonify({'frequency': value})
return str(value)
#app.route('/set_gain/<int:value>')
def set_gain(value):
#sound(frequency=value)
tb.change_gain(value)
#return jsonify({'frequency': value})
return str(value)
#app.route('/set_center_frequency/<int:value>')
def set_center_frequency(value):
#sound(frequency=value)
tb.change_center_frequency(value)
#return jsonify({'frequency': value})
return str(value)
#app.route('/set_USRPsamp_rate/<int:value>')
def set_USRPsamp_rate(value):
#sound(frequency=value)
tb.change_USRPsamp_rate(value)
#return jsonify({'frequency': value})
return str(value)
#app.route('/valueofslider')
def slide():
sample_rate = request.args.get('slide1_val', None)
amplitude = request.args.get('slide2_val', None)
frequency = request.args.get('slide3_val', None)
bandwidth = request.args.get('slide4_val', None)
gain = request.args.get('slide5_val', None)
center_frequency = request.args.get('slide6_val', None)
USRPsamp_rate = request.args.get('slide7_val', None)
sound(
sample_rate=sample_rate,
amplitude=amplitude,
frequency=frequency,
bandwidth=bandwidth,
gain=gain,
center_frequency=center_frequency,
USRPsamp_rate=USRPsamp_rate,
)
#return jsonify({
# 'sample_rate': sample_rate,
# 'amplitude': amplitude,
# 'frequency ': frequency ,
# 'bandwidth': bandwidth,
# 'gain': gain,
# 'center_frequency ': center_frequency ,
# 'USRPsamp_rate ': USRPsamp_rate ,
# })
return 'sample_rate: {}, amplitude: {}, frequency: {}, bandwidth: {}, gain: {}, center_frequency: {}, USRPsamp_rate: {}'.format(sample_rate, amplitude, frequency, bandwidth )
def sound(sample_rate=None, amplitude=None, frequency=None, bandwidth=None, gain=None, center_frequency=None, USRPsamp_rate=None):
"""version which uses `change()`"""
if sample_rate is not None:
sample_rate = int(sample_rate)
tb.change_sample_rate(sample_rate)
if amplitude is not None:
amplitude = int(amplitude)
tb.change_amplitude(amplitude)
if frequency is not None:
frequency = int(frequency )
tb.change_frequency(frequency )
if bandwidth is not None:
bandwidth = int(bandwidth )
tb.change_bandwidth(bandwidth )
if gain is not None:
gain = int(gain )
tb.change_gain(gain )
if center_frequency is not None:
center_frequency = int(center_frequency )
tb.change_center_frequency(center_frequency )
if USRPsamp_rate is not None:
USRPsamp_rate = int(USRPsamp_rate )
tb.change_USRPsamp_rate(USRPsamp_rate )
print('[sound] sample_rate:', sample_rate)
print('[sound] amplitude:', amplitude)
print('[sound] frequency:', frequency)
print('[sound] bandwidth:', bandwidth)
print('[sound] gain:', gain)
print('[sound] center_frequency:', center_frequency)
print('[sound] center_frequency:', USRPsamp_rate)
#if tb: # if tb is not None
# tb.change(sample_rate, amplitude, frequency, bandwidth, gain, center_frequency, USRPsamp_rate)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
Update:
Here is the USRP code that works without problems:
if __name__ == '__main__':
import ctypes
import sys
if sys.platform.startswith('linux'):
try:
x11 = ctypes.cdll.LoadLibrary('libX11.so')
x11.XInitThreads()
except:
print "Warning: failed to XInitThreads()"
from gnuradio import analog
from gnuradio import audio
from gnuradio import blocks
from gnuradio import eng_notation
from gnuradio import gr
from gnuradio import uhd
from gnuradio import wxgui
from gnuradio.eng_option import eng_option
from gnuradio.fft import window
from gnuradio.filter import firdes
from gnuradio.wxgui import fftsink2
from grc_gnuradio import wxgui as grc_wxgui
from optparse import OptionParser
import time
import wx
class broadband_noise(grc_wxgui.top_block_gui):
def __init__(self):
grc_wxgui.top_block_gui.__init__(self, title="Broadband Noise")
_icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png"
self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY))
##################################################
# Variables
##################################################
self.samp_rate = samp_rate = 16000000
self.gain = gain = 50
self.center_frequency = center_frequency = 88e6
self.bandwidth = bandwidth = 75000
##################################################
# Blocks
##################################################
self.wxgui_fftsink2_0 = fftsink2.fft_sink_f(
self.GetWin(),
baseband_freq=0,
y_per_div=10,
y_divs=10,
ref_level=0,
ref_scale=2.0,
sample_rate=samp_rate,
fft_size=1024,
fft_rate=15,
average=False,
avg_alpha=None,
title='FFT Plot',
peak_hold=False,
)
self.Add(self.wxgui_fftsink2_0.win)
self.uhd_usrp_sink_0 = uhd.usrp_sink(
",".join(("", "")),
uhd.stream_args(
cpu_format="sc16",
channels=range(1),
),
)
self.uhd_usrp_sink_0.set_samp_rate(samp_rate)
self.uhd_usrp_sink_0.set_center_freq(center_frequency, 0)
self.uhd_usrp_sink_0.set_gain(gain, 0)
self.uhd_usrp_sink_0.set_antenna('TX/RX', 0)
self.uhd_usrp_sink_0.set_bandwidth(bandwidth, 0)
self.blocks_add_xx_0 = blocks.add_vff(1)
self.audio_sink_0 = audio.sink(samp_rate, '', True)
self.analog_sig_source_x_0 = analog.sig_source_f(samp_rate, analog.GR_COS_WAVE, 1000, 1, 0)
self.analog_noise_source_x_0 = analog.noise_source_f(analog.GR_GAUSSIAN, 1, 0)
##################################################
# Connections
##################################################
self.connect((self.analog_noise_source_x_0, 0), (self.blocks_add_xx_0, 1))
self.connect((self.analog_sig_source_x_0, 0), (self.blocks_add_xx_0, 0))
self.connect((self.blocks_add_xx_0, 0), (self.audio_sink_0, 0))
self.connect((self.blocks_add_xx_0, 0), (self.uhd_usrp_sink_0, 0))
self.connect((self.blocks_add_xx_0, 0), (self.wxgui_fftsink2_0, 0))
def get_samp_rate(self):
return self.samp_rate
def set_samp_rate(self, samp_rate):
self.samp_rate = samp_rate
self.wxgui_fftsink2_0.set_sample_rate(self.samp_rate)
self.uhd_usrp_sink_0.set_samp_rate(self.samp_rate)
self.analog_sig_source_x_0.set_sampling_freq(self.samp_rate)
def get_gain(self):
return self.gain
def set_gain(self, gain):
self.gain = gain
self.uhd_usrp_sink_0.set_gain(self.gain, 0)
def get_center_frequency(self):
return self.center_frequency
def set_center_frequency(self, center_frequency):
self.center_frequency = center_frequency
self.uhd_usrp_sink_0.set_center_freq(self.center_frequency, 0)
def get_bandwidth(self):
return self.bandwidth
def set_bandwidth(self, bandwidth):
self.bandwidth = bandwidth
self.uhd_usrp_sink_0.set_bandwidth(self.bandwidth, 0)
def main(top_block_cls=broadband_noise, options=None):
tb = top_block_cls()
tb.Start(True)
tb.Wait()
if __name__ == '__main__':
main()
Update:
uhd_find_devices output:
fit-pc#fitpc-fitlet2:~$ uhd_find_devices
linux; GNU C++ version 7.3.0; Boost_106501; UHD_003.010.003.000-0-unknown
-- UHD Device 0
Device Address:
type: b200
name: B200mini
serial: 3164B8E
product: B200mini
Update:
uhd_find_devices output from/within Flask env.:
fit-pc#fitpc-fitlet2:~/my_flask_app/virtualenv$ uhd_find_devices
linux; GNU C++ version 7.3.0; Boost_106501; UHD_003.010.003.000-0-unknown
--------------------------------------------------
-- UHD Device 0
--------------------------------------------------
Device Address:
type: b200
name: B200mini
serial: 3164B8E
product: B200mini
Update:
Image of Error location
upon closer inspection, the console output indicates you're trying to create another USRP handler after the first one got created, and holds the access to the USRP.
This can easily happen in Server systems where multiple, potentially concurrent requests are made.
I don't know how intimately enough how flask works but you'll need to interact with only one instance of your USRP sink (or source). It says something about "restarting with..." and that won't work.
You'll need to construct the USRP-handling object once, and keep it between requests.
(also, your sampling rate won't work, but you probably know that already, it's in the console output, too)
b200 is not a valid device address. You're looking for type=b200 as address.