def model_to_json(file_path) -> str: """ Converts a `.fwd` Frew model to a `.json` Frew model. Parameters ---------- file_path : str Absolute file path to the '.fwd' Frew model. Returns ------- json_path : str The new file path of the json file. """ _check_frew_path(file_path) json_path: str = f'{file_path.rsplit(".", 1)[0]}.json' try: model = CreateObject("frewLib.FrewComAuto") except OSError: os.remove(file_path) raise FrewError("Failed to create a COM object.") try: model.Open(file_path) except COMError: raise FrewError("Failed to open the Frew model.") model.SaveAs(json_path) model.Close() return json_path
def analyse(self) -> None: """ Analyse the model using the COM interface to open Frew. This method requires greater than Frew 19.4 Build 24. """ num_stages: int = get_num_stages(self.json_data) folder_path: str = os.path.dirname(self.file_path) temp_file_path: str = os.path.join(folder_path, f"{uuid4()}.json") self.save(temp_file_path) try: model = CreateObject("frewLib.FrewComAuto") except OSError: os.remove(temp_file_path) raise FrewError("Failed to create a COM object.") try: model.Open(temp_file_path) except COMError: os.remove(temp_file_path) raise FrewError("Failed to open the Frew model.") model.DeleteResults() model.Analyse(num_stages) model.SaveAs(temp_file_path) model.Close() new_data: Dict[str, list] = load_data(temp_file_path) os.remove(temp_file_path) self._clear_json_data() self._refill_json_data(new_data)
class SpeechToWav: def __init__(self,pause,engineRate): self.engine = CreateObject("SAPI.SpVoice") self.stream = CreateObject("SAPI.SpFileStream") self.SSML_generator = SSML_Generator(pause) # This import has to be done in a specific order, otherwise Windows is not happy from comtypes.gen import SpeechLib # Because of that, below is a work around to use its functions throughout the object. self.SpeechLib = SpeechLib self.engine.Rate = engineRate def __call__(self,text,outputFile): # https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms723606(v%3Dvs.85) self.stream.Open(outputFile + ".wav", self.SpeechLib.SSFMCreateForWrite) self.engine.AudioOutputStream = self.stream text = self._text_processing(text) text = self.SSML_generator(text) text = ET.tostring(text,encoding='utf8', method='xml').decode('utf-8') # Replace with SSML file and flag self.engine.speak(text) self.stream.Close() def _text_processing(self,text): """ Used to remove side effects from columns, the new lines add bizzare pauses """ return re.findall(r"[\w']+", text) #text.replace("\n", "").split(",")
def dictado(request): if request.session['id'] is not 0: grade = request.GET.get('grado') if request.method == 'POST': key = request.POST.get('key') textoPalabras = Palabras.objects.filter(dificultad = int(grade)) pal = [] for palabra in textoPalabras: pal.append(palabra.palabra) pythoncom.CoInitialize() text = pal[int(key)] src = "/static/audio/audio.m4a" engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib #Gracias Chuy path = os.path.join(BASE_DIR, "PyStudent\\static\\audio\\audio.m4a") #stream.Open("C:/Users/sasuk/Desktop/PyStudent/PyStudent/static/audio/audio.m4a", SpeechLib.SSFMCreateForWrite) stream.Open(path, SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream engine.speak(text) stream.Close() return HttpResponse(src) return render(request, 'dictadoPalabras.html') else: return redirect('/pystudent/')
def audioWise(): File = open("text/loadedFile.svcg", 'r') text = File.read() engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") stream.Open('media/AudioBook.wav', SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream engine.speak(text) stream.Close()
def set_power_supply_voltage(voltage=12.6, current=5): ps = CreateObject("LambdaGenPS.LambdaGenPS") ps.Initialize("COM3", True, True,'DriverSetup=SerialAddress=6, BaudRate=9600') ps.Output.VoltageLimit = voltage ps.Output.CurrentLimit = current ps.Output.Enabled = True time.sleep(2) mes_vol = ps.Output.MeasureVoltage() ps.Close() return mes_vol
def power_supply(input_voltage=6): ps2 = CreateObject("LambdaGenPS.LambdaGenPS") ps2.Initialize("COM3", True, True, "DriverSetup=SerialAddress=6,BaudRate=9600") ps2.Output.VoltageLimit = input_voltage ps2.Output.CurrentLimit = 5 ps2.Output.Enabled = True time.sleep(2) mes_vol = ps2.Output.MeasureVoltage() ps2.Close() return mes_vol
def do_TTS(msg, req_type): print('starting tts') engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") stream.Open('temp.wav', SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream # need to parse request to find requested message if (req_type == 0): print(msg) word = msg else: ind = msg.find(': ') ind1 = msg.find('\r\n') word = msg[ind + 2:ind1] engine.speak(word, 0) stream.Close() # # need to change this to temp if i want it to be overwritten each time f = wave.open("temp.wav", 'rb') frames = f.readframes(f.getnframes()) frames = [ struct.unpack("<h", frames[i] + frames[i + 1])[0] for i in range(0, len(frames), 2) ] # change samp rate by changing last argument, 4 means 5.5 kHz frames = [ np.uint8(((frames[i] + 2**15) >> 9) + 32) for i in range(0, len(frames), 4) ] ind = -1 for i in range(len(frames)): # whatever value zero is encoded as if frames[i] != 96: ind = i break #frames = frames[ind-10:] for i in range(len(frames)): if (frames[len(frames) - i - 1] != 96): ind = i break # frames = frames[:ind+20] #t = np.linspace(0, 10000, f.getnframes()) # 7-bit ascii character offset by 32 to avoid control bits assert max(frames) <= 159 and min(frames) >= 32 z = [] for i in range(len(frames)): # if (i%4 != 0): z.append(Bits('uint:8=' + str(frames[i]))) # not sure if \n is helpful # u8_str = ''.join(a.bin+'\n' for a in z) #u8_str = ''.join(str(a)+'\n' for a in frames) ascii_str = ''.join(chr(a) for a in frames) cltskt.send(ascii_str)
def tta(txt): from comtypes.client import CreateObject engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib outfile = "splits/my_tta.wav" stream.Open(outfile, SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream #f = open(infile, 'r') #txt = f.read() #f.close() engine.speak(txt) stream.Close()
class Sapi(object): def __init__(self, profile): try: self.profile = profile self.tokenName = self.profile.getTokenName() self.engine = CreateObject("SAPI.SpVoice") self.stream = CreateObject("SAPI.SpFileStream") # stereo = add 1 # 16-bit = add 2 # 8KHz = 4 # 11KHz = 8 # 12KHz = 12 # 16KHz = 16 # 22KHz = 20 # 24KHz = 24 # 32KHz = 28 # 44KHz = 32 # 48KHz = 36 self.stream.Format.Type = self.profile.getFormat() self.engine.Voice = self.getToken(self.tokenName) except Exception as e: logger.error(e) def createFileTts(self, text): self.filename = None try: comtypes.CoInitialize() self.ts = time.time() self.filename = '%s.wav' % self.ts self.path = self.profile.getFilePath() self.stream.Open(self.path + self.filename, 3) #SSFMCreateForWrite self.engine.AudioOutputStream = self.stream self.engine.speak(text) self.stream.Close() except Exception as e: logger.error(e) return self.filename def getVoices(self): return self.engine.GetVoices() def getToken(self, tokenName): tokens = self.getVoices() for token in tokens: logger.info(token.Id) if token.Id == tokenName: break return token
class MainApplication(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) """application configuration""" menu = tk.Menu() root.grid_rowconfigure(2, weight=2) style = ttk.Style() style.configure("TLabel", relief="raised", foreground="black", background="lightgreen") style.configure("TButton", foreground="grey", background="lightgreen", width=30) root.config(menu=menu) root.resizable(0, 0) root.title("my converter") root.geometry("500x200") menu.add_command(label="exit", command=root.quit) menu.add_command(label="help", command=self.showhelp) menu.add_command(label="about", command=self.about) root.configure(background="lightgreen") menu.configure(background="white") self.basic = ttk.Label(text="please click the help menu button first before you use the application \n" ) self.basic.pack() self.Linput = ttk.Label(root, text="input file", width=30) self.Linput.pack() self.inputentry = ttk.Entry(root, width=30) self.inputentry.pack() self.Loutput = ttk.Label(text="output file", width=30) self.Loutput.grid_rowconfigure(4, weight=2) self.Loutput.pack() self.OutputEntry = ttk.Entry(width=30) self.OutputEntry.pack() self.Convert = ttk.Button(text="convert", command=self.ConverterToAudio) self.Convert.pack(side="top") """sets up main function""" def ConverterToAudio(self): try: self.engine = CreateObject("SAPI.SpVoice") self.stream = CreateObject("SAPI.SpFileStream") self.infile = self.inputentry.get() self.outfile = self.OutputEntry.get() self.stream.Open(self.outfile, SpeechLib.SSFMCreateForWrite) self.engine.AudioOutputStream = self.stream with open(self.infile, "r") as text: self.content = text.read() self.engine.speak(self.content) self.stream.Close() mbx.showinfo("output", f" conversion of {self.infile} {self.outfile}") except Exception as e: mbx.showwarning("error", e)
def test(self, dynamic=False): engine = CreateObject("SAPI.SpVoice", dynamic=dynamic) stream = CreateObject("SAPI.SpFileStream", dynamic=dynamic) from comtypes.gen import SpeechLib fd, fname = tempfile.mkstemp(suffix=".wav") os.close(fd) stream.Open(fname, SpeechLib.SSFMCreateForWrite) # engine.AudioStream is a propputref property engine.AudioOutputStream = stream self.assertEqual(engine.AudioOutputStream, stream) engine.speak("Hello, World", 0) stream.Close() filesize = os.stat(fname).st_size self.assertTrue(filesize > 100, "filesize only %d bytes" % filesize) os.unlink(fname)
def txtToWav(inputFile, outputFile, voice=0): if not os.path.exists(outputFile[0:outputFile.rfind('\\')]): os.makedirs(outputFile[0:outputFile.rfind('\\')]) engine = CreateObject("SAPI.SpVoice") engine.Voice = engine.GetVoices()[voice] stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib stream.Open(outputFile, SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream f = open(inputFile, 'r') text = f.read() f.close() engine.speak(text) stream.Close()
def getLength(text, wavfn): '''Get the length, in seconds, of a wav file produced by applying a text-to-speech engine to the given text.''' with tempfile.NamedTemporaryFile() as f: wavfn = f.name engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") stream.Open(wavfn, comtypes.gen.SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream engine.speak(text) stream.Close() with contextlib.closing(wave.open(wavfn, 'r')) as f: frames = f.getnframes() rate = f.getframerate() duration = frames / float(rate) os.remove(wavfn) return duration
def txt_zu_wav(eingabe, ausgabe, text_aus_datei=True, geschwindigkeit=2, Stimmenname="Zira"): from comtypes.client import CreateObject engine = CreateObject("SAPI.SpVoice") engine.rate = geschwindigkeit # von -10 bis 10 for stimme in engine.GetVoices(): if stimme.GetDescription().find(Stimmenname) >= 0: engine.Voice = stimme break else: print("Fehler Stimme nicht gefunden -> Standard wird benutzt") if text_aus_datei: datei = open(eingabe, 'r') text = datei.read() datei.close() else: text = eingabe stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib stream.Open(ausgabe, SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream engine.speak(text) stream.Close() # reads from a file named test.txt and converts to a .wav file #txt_zu_wav("test.txt", "test_1.wav")
mixer.music.load(wav_file) mixer.music.play() #windows system play and convert wav file if (operatingSystem == 'win32'): from comtypes.client import CreateObject engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib stream.Open(wav_file, SpeechLib.SSFMCreateForWrite) # ERRORS NEAR HERE engine.AudioOutputStream = stream # MAYBE HERE :( engine.speak(quote) stream.Close() import win32com.client as wincl speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(quote) #print ("Playing: " + wav_file) #This went to quickyl and slowed down the CPU while mixer.music.get_busy(): time.sleep(0.1) mixer.quit() #print ("Done Playing") #Beginning of the twilio and Flask
class Driver(InstrumentWorker): """ This class implements the Agilent 5230 PNA driver""" @cached_property def cData(self): return {} #self.acquire_data() @cached_property def t0(self): return self.StartFrequency.receive() @cached_property def dt(self): return (self.StopFrequency.receive()-self.StartFrequency.receive())/(self.Points.receive()-1) @cached_property def S_enabled(self): return {name[:3] : self.getValue(name) for name in self.S_enabled_names} @cached_property def S_enabled_names(self): return tuple('{0} - Enabled'.format(name) for name in self.measDict) #@property #def eSweepType(self): # return self.getValue('Sweep type') #@property #def fStartFrequency(self): # startFreq = self.getValue("Start frequency") # if self.eSweepType == 'Log': # return log10(startFreq) # return startFreq #@property #def fStopFrequency(self): # stopFreq=self.getValue("Stop frequency") # if self.eSweepType == 'Log': # return log10(stopFreq) # return stopFreq #@property #def bWaitTrace(self): # return self.getValue('Wait for new trace') #@property #def bAverage(self): #return self.ch1.Averaging # return self.getValue('Average') def writeVNA(self, input_str): self.log("WriteString: {0}".format(input_str)) self.VNA.System2.WriteString(input_str) def readVNA(self): value=self.VNA.System2.ReadString() self.log("ReadString: {0}".format(value)) return value def askVNA(self, input_str): self.writeVNA(input_str) return self.readVNA() def acquire_data(self): self.ch1.ClearAverage() if self.Averaging.value: numTriggers=self.AveragingFactor.value else: numTriggers=1 self.log(numTriggers) for n in range(numTriggers): #if self.needs_abort: # break self.log(n) self.log(self.ch1.TriggerSweep(1000)) self.log(self.VNA.System2.WaitForOperationComplete(10000)) for key in self.measDict: self.log((key, self.S_enabled[key])) if self.S_enabled[key]: data=array(self.measDict[key].FetchComplex()) self.cData[key]=data[0]+1.0j*data[1] if 0: self.measDict[key].FetchX() self.measDict[key].Trace.AutoScale() #self.needs_abort=False def VNAabort(self): self.VNA.Channels.Abort() self.VNA.Status.Clear() self.writeVNA("CALC:PAR:DEL:ALL") self.ch1.TriggerMode=TriggerModeDict['Hold'] #self.needs_abort=True def performOpen(self, options={}): """Perform the operation of opening the instrument connection. Initializes a measurement param dictionary and calls the generic VISA_Driver open Calls an IVI-COM driver. importing of library is delayed""" CoInitialize() self.VNA=CreateObject('AgilentNA.AgilentNA') self.log("VNA object created") self.VNA.Initialize( "TCPIP::129.16.115.134::5025::SOCKET", False, False, "") self.log("VNA Initialized") self.ch1=self.VNA.Channels["Channel1"] self.VNAabort() #self.needs_abort=False self.measDict=dict(S11=self.ch1.Measurements["Measurement1"], S21=self.ch1.Measurements["Measurement2"], S12=self.ch1.Measurements["Measurement3"], S22=self.ch1.Measurements["Measurement4"]) #sAll=self.askVNA("CALC:PAR:CAT:EXT?") #t=sAll[1:-1].split(",") #self.log({t[i]:t[i+1] for i in range(0, len(t), 2)}) # #self.ch1.TriggerMode=TriggerModeDict['Hold'] #self.prop_dict={} self.Averaging=Prop(self.ch1, 'Averaging') self.IFBandwidth=Prop(self.ch1, 'IFBandwidth') self.Points=Prop(self.ch1, "Points", coercer=int) self.AveragingFactor=Prop(self.ch1, "AveragingFactor", coercer=int) self.StopFrequency=Prop(self.ch1.StimulusRange, "Stop") self.StartFrequency=Prop(self.ch1.StimulusRange, "Start") self.Span=Prop(self.ch1.StimulusRange, "Span") self.CenterFrequency=Prop(self.ch1.StimulusRange, "Center") self.OutputPower=Prop(self.ch1.SourcePower, "Level", 1) #self.OutputPower2=Prop(self.ch1.SourcePower, "Level", 2) self.prop_dict=get_prop_dict(self) for key in self.prop_dict: getattr(self, key).value=self.getValue(key) #self.prop_mapping=get_mapping(prop_dict) #self.log(self.prop_dict) #VNA.Channels["Channel1"].SweepTimeAuto #VNA.Channels["Channel1"].SweepType #VNA.Channels["Channel1"].SweepMode #VNA.Channels["Channel1"].SweepTime # # meas.Create(1,1) # meas.Format=0 # # VNA.Channels["Channel1"].TriggerMode def performClose(self, bError=False, options={}): self.VNAabort() self.VNA.Close( ) self.log("VNA Closed") self.VNA.Release() self.log("VNA object released") def performSetValue(self, quant, value, sweepRate=0.0, options={}): """Perform the Set Value instrument operation. This function should return the actual value set by the instrument. Runs standard VISA set except for enabling S parameters and wait for new trace""" attr=getattr(self, quant.name, None) if attr is not None: return attr.send(value) elif quant.name == "Output enabled": if value: self.writeVNA(":OUTP 1") else: self.writeVNA(":OUTP 0") elif quant.name in self.S_enabled_names: key=quant.name[:3] if value: ReceiverPort=int(key[1]) SourcePort=int(key[2]) self.log((ReceiverPort, SourcePort)) self.measDict[key].Create(ReceiverPort, SourcePort) self.measDict[key].Format=0 else: if self.S_enabled[key]: self.measDict[key].Delete() self.S_enabled[key]=value elif quant.name == "Abort": self.abort() # old-type handling of traces #if param in self.dMeasParam: # clear old measurements for this parameter # for name in self.dMeasParam[param]: # self.writeVNA("CALC:PAR:DEL '{0}'".format(name)) # create new measurement, if enabled is true #if value: # newName = 'LabC_{0}'.format(param) # self.writeVNA("CALC:PAR:EXT '{0}','{1}'".format(newName, param)) # iTrace = 1 + ['S11', 'S21', 'S12', 'S22'].index(param) # self.writeVNA("DISP:WIND:TRAC{0}:FEED '{1}'".format(iTrace, newName)) # self.dMeasParam[param] = [newName] # self.hw_write("DISP:WINDow1:TRACe:DELete") # self.hw_write("CALCulate1:PARameter:DEFine 'MyMag', {}".format(self.measurement_type)) # self.hw_write("DISPlay:WINDow1:TRACe1:FEED 'MyMag'") # self.hw_write("CALCulate1:PARameter:SELect 'MyMag'") # self.hw_write("CALCulate1:FORMat MLOG") # self.hw_write("CALCulate1:PARameter:DEFine 'MyPhase', {}".format(self.measurement_type)) # self.hw_write("DISPlay:WINDow1:TRACe2:FEED 'MyPhase'") # self.hw_write("CALCulate1:PARameter:SELect 'MyPhase'") # self.hw_write("CALCulate1:FORMat PHASe") #elif quant.name in ("Wait for new trace",): # self.log(options) #elif quant.name not in ('Wait for new trace',): # run standard VISA case # value = VISA_Driver.performSetValue(self, quant, value, sweepRate, options) return value def performGetValue(self, quant, options={}): """Perform the Get Value instrument operation""" self.log(options) self.log(self.isFirstCall(options)) attr=getattr(self, quant.name, None) if attr is not None: return attr.receive() elif quant.name == "Output enabled": return bool(int(self.askVNA(":OUTP?"))) elif quant.name in self.S_enabled_names: key=quant.name[:3]#('S11 - Enabled', 'S21 - Enabled', 'S12 - Enabled', 'S22 - Enabled'): return self.S_enabled[key] #return self.getValue(quant.name) # update list of channels in use #self.getActiveMeasurements() # get selected parameter #param = quant.name[:3] #value = param in self.dMeasParam elif quant.name in self.measDict: #('S11', 'S21', 'S12', 'S22'): if self.isFirstCall(options): #resets cData on first call self.cData=None if quant.name not in self.cData: #resets cData if parameter not in data self.acquire_data() data=self.cData.get(quant.name, []) #if data==[]: # return InstrumentQuantity.getTraceDict() #if quant.name in self.cData: self.log(InstrumentQuantity.getTraceDict.__doc__) return InstrumentQuantity.getTraceDict(data, t0=self.t0, dt=self.dt) #else: # not enabled, return empty array # value = InstrumentQuantity.getTraceDict([]) #return self.cData[quant.name] #if options.get("call_no", 0)==0: #self.dMeasParam={} # check if channel is on #if quant.name not in self.dMeasParam: # get active measurements again, in case they changed # self.getActiveMeasurements() #if quant.name in self.dMeasParam: # if self.getModel() in ('E5071C',): # new trace handling, use trace numbers # self.writeVNA("CALC:PAR%d:SEL" % self.dMeasParam[quant.name]) # else: # old parameter handing, select parameter (use last in list) # sName = self.dMeasParam[quant.name][-1] # self.writeVNA("CALC:PAR:SEL '%s'" % sName) # if not in continous mode, trig from computer # bWaitTrace = self.getValue('Wait for new trace') # bAverage = self.getValue('Average') # wait for trace, either in averaging or normal mode # if bWaitTrace: # if bAverage: # set channels 1-4 to set event when average complete (bit 1 start) # self.writeVNA(':SENS:AVER:CLE;:STAT:OPER:AVER1:ENAB 30;:ABOR;:SENS:AVER:CLE;') # else: # self.writeVNA(':ABOR;:INIT:CONT OFF;:INIT:IMM;') # self.writeVNA('*OPC') # wait some time before first check # self.thread().msleep(30) # bDone = False # while (not bDone) and (not self.isStopped()): # check if done # if bAverage: # sAverage = self.askVNA('STAT:OPER:AVER1:COND?') # bDone = int(sAverage)>0 # else: # stb = int(self.askVNA('*ESR?')) # bDone = (stb & 1) > 0 # if not bDone: # self.thread().msleep(100) # if stopped, don't get data # if self.isStopped(): # self.writeVNA('*CLS;:INIT:CONT ON;') # return [] # get data as float32, convert to numpy array # if self.getModel() in ('E5071C',): # # new trace handling, use trace numbers # self.writeVNA(':FORM:DATA REAL32;:CALC:SEL:DATA:SDAT?')#, bCheckError=False) # else: # old parameter handing # self.writeVNA(':FORM REAL,32;CALC:DATA? SDATA')#, bCheckError=False) # sData = self.readVNA()#ignore_termination=True) # self.log(sData) # if bWaitTrace and not bAverage: # self.writeVNA(':INIT:CONT ON;') # strip header to find # of points # i0 = sData.find('#') # nDig = int(sData[i0+1]) # nByte = int(sData[i0+2:i0+2+nDig]) # nData = nByte/4 # nPts = nData/2 # get data to numpy array # vData = np.frombuffer(sData[(i0+2+nDig):(i0+2+nDig+nByte)], # dtype='>f', count=nData) # data is in I0,Q0,I1,Q1,I2,Q2,.. format, convert to complex # mC = vData.reshape((nPts,2)) # vComplex = mC[:,0] + 1j*mC[:,1] # # get start/stop frequencies # startFreq = self.fStartFrequency #self.readValueFromOther('Start frequency') # stopFreq = self.fStopFrereadValueFromOther('Stop frequency') # sweepType = self.readValueFromOther('Sweep type') # # if log scale, take log of start/stop frequencies # if sweepType == 'Log': # startFreq = np.log10(startFreq) # stopFreq = np.log10(stopFreq) # # create a trace dict # value = InstrumentQuantity.getTraceDict(vComplex, t0=startFreq, # dt=(stopFreq-startFreq)/(nPts-1)) # else: # # not enabled, return empty array # value = InstrumentQuantity.getTraceDict([]) #elif quant.name in ('Wait for new trace',): # do nothing, return local value # value = quant.getValue() #else: # for all other cases, call VISA driver # value = VISA_Driver.performGetValue(self, quant, options) return value
class MainApplication(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) """application configuration""" menu = tk.Menu() Font = "helevetica 10" root.grid_rowconfigure(2, weight=2) style = ttk.Style() style.configure("TLabel", relief="flat", foreground="black", background="lightgreen") style.configure("TButton", relief="grooved", foreground="#800", background="lightgreen", width=30) root.config(menu=menu) root.resizable(0, 0) root.title("Text To Audio Converter") root.geometry("500x200") menu.add_command(label="Exit", command=root.quit) menu.add_command(label="Help", command=self.showhelp) menu.add_command(label="About", command=self.about) root.configure(background="lightgreen") menu.configure(background="white") self.basic = ttk.Label(text="Please click the help button on the menu to learn how to use program \n", font=Font) self.basic.pack() self.Linput = ttk.Label(root, text="Input file", width=30) self.Linput.pack() self.inputentry = ttk.Entry(root, width=30) self.inputentry.pack() self.Loutput = ttk.Label(text="Output file", width=30) self.Loutput.grid_rowconfigure(4, weight=2) self.Loutput.pack() self.OutputEntry = ttk.Entry(width=30) self.OutputEntry.pack() self.Lspeed = ttk.Label(text="Set voice rate", width=30) self.Lspeed.pack() self.Setrate = ttk.Entry(width=30) self.Setrate.pack() self.Convert = ttk.Button(text="Convert Text", command=self.ConverterToAudio) self.Convert.pack(side="top") """sets up main root nction""" def ConverterToAudio(self): try: self.engine = CreateObject("SAPI.SpVoice") self.stream = CreateObject("SAPI.SpFileStream") self.infile = self.inputentry.get() self.outfile = self.OutputEntry.get() self.stream.Open(self.outfile, SpeechLib.SSFMCreateForWrite) self.engine.AudioOutputStream = self.stream with open(self.infile, "r") as text: self.content = text.read() self.engine.rate = int(self.Setrate.get()) self.engine.pitch =int(self.Setrate.get()) self.engine.GetVoices("microsoft zira") self.engine.speak(self.content) self.stream.Close() mbx.showinfo("output", f" conversion of source file {self.infile} to destination{self.outfile}") with open("converter-conversions-log.txt","a") as C: C.write(f"output: conversion of {self.infile} {self.outfile} completed") #mbx.showinfo("Output", "Conversion of {} to {}".format(self.infile, self.outfile))# except Exception as e: mbx.showwarning("error", e) with open("converter-error-log.txt", "a") as E: E.write(f"\n error: {e}") def showhelp(self):mbx.showinfo("Help", "To use this application make sure you type in the file or directory you need converted in the input entry and output\n entru for example text.txt and\n then in the output entry do text.mp3 you can also tab to the next entry\nthe new feature you can is set the rate of the scale from -10 to 10 in the rate entry box but there must be a number, i will add voices as I go. if you have a problem email [email protected] or notify me at my github. amke sure to send the logs you ahve when you find a error pelse send converter-error-log and converter-conversions-log as well ") def about(self): mbx.showinfo("About", "\n\n created by austin heisley-cook\ndate 2/1/2018 original year is 2013 this program the idea is credited to past boss because I am making the idea becomes a reality.\n I have spent years creating this.")
class AgilentNetworkAnalyzer(COM_Instrument): base_name = "E8354B" @private_property def S_names(self): return ('S11', 'S21', 'S12', 'S22') @private_property def main_params(self): return [ "doS11", "doS21", "doS12", "doS22", "trigger_mode", "VNA_abort", "start_freq", "stop_freq", "points", "averaging", "averages", 'timeout', "power", 'clear_average', 'acquire_data', 'error_query' ] #::inst0::INSTR" #enable SICL in system settings #"TCPIP::129.16.115.134::5025::SOCKET" address = Unicode("TCPIP::129.16.115.134").tag(sub=True, no_spacer=True) simulate = Bool(False).tag(sub=True) VNA = Value().tag(private=True, desc="a link to the session of the instrument.") ch1 = Value().tag(private=True, desc="link to main instrument channel") measS11 = Value().tag(private=True, desc="link to measurement S11") measS12 = Value().tag(private=True, desc="link to measurement S12") measS21 = Value().tag(private=True, desc="link to measurement S21") measS22 = Value().tag(private=True, desc="link to measurements S22") trace_plot = Typed(Plotter).tag(private=True) def update_trace_plot(self): self.trace_plot.plot_dict["trace_mag S21"].clt.set_xdata(self.freq) S21dB = absolute(self.S21) #20.0*log10(absolute(self.S21)) print shape(self.freq) print shape(S21dB) if self.simulate: S21dB = absolute(self.S21) self.trace_plot.plot_dict["trace_mag S21"].clt.set_ydata(S21dB) if min(self.freq) != max(self.freq): self.trace_plot.set_xlim(min(self.freq), max(self.freq)) if min(S21dB) != max(S21dB): self.trace_plot.set_ylim(min(S21dB), max(S21dB)) self.trace_plot.draw() def _default_trace_plot(self): tp = Plotter(name=self.name + ' trace plot') print self.freq print absolute(self.S21) print shape(self.freq) print shape(self.S21) tp.line_plot('trace_mag S21', self.freq, absolute(self.S21)) #S20.0*log10(absolute(self.S21))) return tp doS11 = Bool(False) doS21 = Bool(False) doS12 = Bool(False) doS22 = Bool(False) do_freq = Bool(False) timeout = Int(10000) #clear_average=Bool(True).tag(sub=True) @observe("doS11", "doS21", "doS21", "doS22") def observe_doSs(self, change): log_debug(change) if change['type'] == 'update': Sname = change["name"][2:] if change.get("oldvalue", False): log_debug('del old meas') log_debug(getattr(self, 'meas' + Sname).Delete()) self.error_query() elif change["value"]: ReceiverPort = int(Sname[1]) SourcePort = int(Sname[2]) log_debug(ReceiverPort, SourcePort) if Sname not in self.query_measurements().values(): self.writer("CALC:PAR:DEF:EXT MEAS{0},{0}".format(Sname)) log_debug( getattr(self, 'meas' + Sname).Create(ReceiverPort, SourcePort)) self.error_query() print self.query_measurements() sleep(1) getattr(self, 'meas' + Sname).Format = 0 #self.error_query() def query_measurements(self): sAll = self.asker("CALC:PAR:CAT:EXT?")[1:-1] if self.simulate: sAll = 'NO CATALOG' if sAll == 'NO CATALOG': return {} t = sAll.split(",") return {t[i]: t[i + 1] for i in range(0, len(t), 2)} @reader def reader(self): """calls VNA ReadString""" return self.VNA.System2.ReadString() @writer def writer(self, VNA_string): """calls VNA WriteString using string formatting by kwargs""" self.VNA.System2.WriteString(VNA_string) @asker def asker(self, VNA_string): """calls VNA WriteString followed by VNA ReadString""" self.writer(VNA_string) return self.reader() @tag_Callable(do=True) def VNA_abort(self): self.VNA.Channels.Abort() self.writer("CALC:PAR:DEL:ALL") self.VNA.Status.Clear() #self.ch1.TriggerMode=TriggerModeDict['Hold'] @booter def booter(self, address): self.VNA = CreateObject("AgilentNA.AgilentNA") init_list = [ 'Simulate={0}'.format(self.simulate), #'QueryInstrStatus=true' ] init_str = ','.join(init_list) print init_str log_debug(self.VNA.Initialize(self.address, False, False, init_str)) self.ch1 = self.VNA.Channels["Channel1"] if not self.simulate: print self.VNA.System2.IO.IO.LockRsrc() if get_tag(self, 'abort', 'do', False): self.VNA_abort() #self.VNA_write("CALC:PAR:DEL:ALL") self.error_query() #log_debug(self.VNA.System2.WaitForOperationComplete(self.timeout)) #self.error_query() self.measS11 = self.ch1.Measurements["Measurement1"] self.measS21 = self.ch1.Measurements["Measurement2"] self.measS12 = self.ch1.Measurements["Measurement3"] self.measS22 = self.ch1.Measurements["Measurement4"] if self.simulate: self.stop_freq = 4.0e9 #sleep(1) #self.measS11.Create(1, 1) #self.error_query() #sleep(1) #self.measS11.Delete() #self.synchronize() self.error_query() def synchronize(self): self.receive('points') @tag_Callable() def error_query(self): for n in range(11): err_query = self.VNA.Utility.ErrorQuery() log_debug(err_query, n=3) if err_query[0] == 0: break def clear_all_traces(self): self.VNA.System2.WriteString("CALC:PAR:DEL:ALL") # def close_measurement(self, key): # try: # self.meas_dict[key].Delete() # except COMError as e: # log_debug(e) # # def close_all_measurements(self): # for key in self.meas_dict: # self.close_measurement(key) @closer def closer(self): for key in self.S_names: if getattr(self, 'do' + key): getattr(self, 'meas' + key).Delete() #self.VNA_abort() if not self.simulate: print self.VNA.System2.IO.IO.UnlockRsrc() log_debug(self.VNA.Close()) for n in self.loop(10): if self.VNA.Release() == 0: break #VNA.Channels["Channel1"].StimulusRange.Span #VNA.Channels["Channel1"].StimulusRange.Center #VNA.System2.WriteString(":OUTP 0") @tag_Callable() def clear_average(self): self.ch1.ClearAverage() # def acq2(self): # log_debug('acq2 started') # self.ch1.TriggerMode=1 # self.ch1.ClearAverage() # for n in range(self.averages): # self.ch1.TriggerSweep(1000) # self.VNA.System2.WaitForOperationComplete(10000) # log_debug('acq2 stopped') # # def acq(self): # log_debug('acq started') # self.VNA_write("SENSE:SWE:GRO:COUN {}".format(self.averages)) # # self.ch1.ClearAverage() # self.VNA.System2.WriteString("SENSE:SWE:MODE GROUPS") # getattr(self, 'meas'+'S21').Trace.AutoScale() # try: # log_debug(self.VNA.System2.WaitForOperationComplete(30000)) # #print self.error_query() # except Exception as e: # raise Exception(str(e)) # log_debug('acq stopped') @tag_Callable() def acquire_data(self): self.send(trigger_mode='Hold') #if get_tag(self, "clear_average", "do"): self.clear_average() if self.averaging: numTriggers = self.averages else: numTriggers = 1 for n in self.loop(numTriggers): self.ch1.TriggerSweep(1000) self.VNA.System2.WaitForOperationComplete(self.timeout) if n == 9: for key in self.S_names: if getattr(self, "do" + key): getattr(self, 'meas' + key).Trace.AutoScale() for key in self.S_names: if getattr(self, "do" + key): data = array(getattr(self, 'meas' + key).FetchComplex()) setattr(self, key, data[0] + 1.0j * data[1]) #log_debug(getattr(self, key)) if self.do_freq: self.freq = getattr(self, 'meas' + key).FetchX() if not self.do_freq: self.freq = linspace(self.start_freq, self.stop_freq, self.points) self.update_trace_plot() #print list(frq)==list(self.freq) start_freq = Float(4.0e9).tag(high=50.0e9, low=10.0e6, label='VNA start frequency', unit2='GHz', aka="self.ch1.StimulusRange.Start", show_value=True) stop_freq = Float(5.0e9).tag(low=10.0e6, high=50.0e9, label='VNA stop frequency', unit2='GHz', aka="self.ch1.StimulusRange.Stop", show_value=True) points = Int(1601).tag(low=1, high=20001, aka="self.ch1.Points") averages = Int(1).tag(low=1, high=50000, aka="self.ch1.AveragingFactor") averaging = Bool(True).tag(aka="self.ch1.Averaging") power = Float(-27.0).tag(low=-27.0, high=0.0, display_unit='dBm', aka="self.ch1.SourcePower.Level[1]") #electrical_delay = Float(0).tag(label='VNA electrical delay', unit = 's', # GPIB_writes=":CALCulate1:CORRection:EDELay:TIME {electrical_delay}") #subtract_background = Bool(False) #measurement_type = Enum('S11', 'S12', 'S21', 'S22') #start = Button() #adjust_electrical_delay = Button() #acquire_background = Button() freq = Array().tag(label='Frequency', sub=True) S11 = Array().tag(sub=True) S12 = Array().tag(sub=True) S21 = Array().tag(sub=True) S22 = Array().tag(sub=True) trigger_mode = Enum('Continuous', 'Hold').tag(mapping=TriggerModeDict, aka="self.ch1.TriggerMode")
print VNA.Channels["Channel1"].IFBandwidth #print help(VNA) #print VNA.Identity.InstrumentModel #>>> PS2.Output.VoltageLimit = 5 #>>> PS2.Output.CurrentLimit = 1 #>>> PS2.Output.Enabled = True #>>> PS2.Output.MeasureVoltage( ) #5.0019999999999998 #>>> PS2.Identity.InstrumentModel #u'GEN30-25-IEMD' #>>> PS2.Utility.Reset( ) #0 VNA.Close( ) VNA.Release( ) #import visa #VNA = visa.instrument("TCPIP::129.16.115.134::5025::SOCKET") #print(keithley.ask("*IDN?")) #import visa #rm = visa.ResourceManager() #keithley = rm.open_resource("TCPIP::129.16.115.134::5025::SOCKET") #print dir(keithley) #keithley.read_termination="\r\n" #visa.CR+visa.LF #keithley.write_termination="\r\n" # #print keithley.resource_info #print keithley.open()
def textToSpeechBot(): #This program starts off by webscraping a random quotation #It then sends that program from text to speech #It then will convert that speech back to text and speak to itself #Similar to the way humans play telephone #After doing this, it will call a list of people (only can call one person) #Twilio free trial limited us ot only calling one person :( #Always more random features to incorporate #table number 29 import contextlib #To supress output of pygame import with contextlib.redirect_stdout(None): #Supress output of pygame import from pygame import mixer #Playing music import pygame from gtts import gTTS import time import lxml import urllib.request from bs4 import BeautifulSoup import random import speech_recognition as sr from pathlib import Path import os import contextlib with contextlib.redirect_stdout(None): import moviepy.editor as mpy from pydub import AudioSegment #from pocketsphinx import AudioFile import wave from gtts import gTTS pygame.init() #ffmpeg debugger #import logging #Grab the quote from the web url = "http://www.quotationspage.com/random.php" request = urllib.request.Request(url) html = urllib.request.urlopen(request) soup = BeautifulSoup(html, 'lxml') links = soup.findAll( 'a', {"title": "Click for further information about this quotation"}) quotes = [] for a in links: quotes.append(str(a)[str(a).find('>') + 1:str(a).rfind('<')]) quote = random.choice(quotes) print("Random Web Quote: " + quote) #pause = input("Press any key to continue\n") file = "quote.mp3" wav_file = "quote.wav" #print(file, wav_file) import os import platform import sys #Determine what operating system the user has in order to play audio properly operatingSystem = sys.platform #print ("Operating System: " + operatingSystem) #Have to create the files and initialize mixers for both OS's from gtts import gTTS tts = gTTS(text=quote, lang='en') tts.save(file) mixer.init(frequency=22050, size=-16, channels=2, buffer=-4096) #linux play and convert wav file if (operatingSystem == 'linux'): #sound = AudioSegment.from_mp3(file) #sound.export(wav_file, format="wav") file = "./" + file sound = AudioSegment.from_mp3(file) sound.export(wav_file, format="wav") #mixer.init() mixer.music.load(wav_file) mixer.music.play() #windows system play and convert wav file if (operatingSystem == 'win32'): from comtypes.client import CreateObject engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib stream.Open(wav_file, SpeechLib.SSFMCreateForWrite) # ERRORS NEAR HERE engine.AudioOutputStream = stream # MAYBE HERE :( engine.speak(quote) stream.Close() import win32com.client as wincl speak = wincl.Dispatch("SAPI.SpVoice") speak.Speak(quote) #print ("Playing: " + wav_file) #This went to quickyl and slowed down the CPU while mixer.music.get_busy(): time.sleep(0.1) mixer.quit() #print ("Done Playing") #Beginning of the twilio and Flask from flask import Flask from twilio.twiml.voice_response import VoiceResponse from twilio.rest import Client app = Flask(__name__) lastTelephone = quote phoneNumberToCall = input("What is your phone number ?") query = ''.join(quote.split()) phoneNumberToCall = phoneNumberToCall.replace(' ', '').replace( '-', '').replace('(', '').replace(')', '') print(phoneNumberToCall) account_sid = 'AC7119e83de9a686d0d56bc8491d80526a' auth_token = 'fcf3e5c1691051282836a49d26ff38c4' client = Client(account_sid, auth_token) call = client.calls.create( url= 'https://handler.twilio.com/twiml/EH06f621851a96b743015a43371effcf68?Message=' + query, to='+1' + phoneNumberToCall, from_='+17207704132') print("Calling:", call.sid) @app.route("/voice", methods=['GET', 'POST']) def voice(): """Respond to incoming phone calls with a 'Hello world' message""" # Start our TwiML response resp = VoiceResponse() # Read a message aloud to the caller resp.say(query) return str(resp)
class MainApplication(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) """application configuration""" menu = tk.Menu() root.grid_rowconfigure(2, weight=2) style = ttk.Style() style.configure("TLabel", relief="raised", foreground="black", background="lightgreen") style.configure("TButton", foreground="grey", background="lightgreen", width=30) root.config(menu=menu) root.resizable(0, 0) root.title("my converter") root.geometry("500x200") menu.add_command(label="exit", command=root.quit) menu.add_command(label="help", command=self.showhelp) menu.add_command(label="about", command=self.about) root.configure(background="lightgreen") menu.configure(background="white") self.basic = ttk.Label( text= "please click the help menubutton first you use the application \n" ) self.basic.pack() self.Linput = ttk.Label(root, text="input file", width=30) self.Linput.pack() self.inputentry = ttk.Entry(root, width=30) self.inputentry.pack() self.Loutput = ttk.Label(text="output file", width=30) self.Loutput.grid_rowconfigure(4, weight=2) self.Loutput.pack() self.OutputEntry = ttk.Entry(width=30) self.OutputEntry.pack() self.Lspeed = ttk.Label(text="set voice rate", width=30) self.Lspeed.pack() self.Setrate = ttk.Entry() self.Setrate.pack() self.Convert = ttk.Button(text="convert", command=self.ConverterToAudio) self.Convert.pack(side="top") """sets up main function""" def ConverterToAudio(self): try: self.engine = CreateObject("SAPI.SpVoice") self.stream = CreateObject("SAPI.SpFileStream") self.infile = self.inputentry.get() self.outfile = self.OutputEntry.get() self.stream.Open(self.outfile, SpeechLib.SSFMCreateForWrite) self.engine.AudioOutputStream = self.stream with open(self.infile, "r") as text: self.content = text.read() self.engine.rate = int(self.Setrate.get()) self.engine.pitch = int(self.Setrate.get()) self.engine.speak(self.content) self.stream.Close() #mbx.showinfo("output", f" conversion of {self.infile} {self.outfile}") mbx.showinfo( "output", "conversion of {} to {}".format(self.infile, self.outfile)) except Exception as e: mbx.showwarning("error", e) def showhelp(self): mbx.showinfo( "help", "to use this application make sure you type in the file or directory you need converted in the input and output entries for example text.txt and then in the output entry do text.mp3 you can also tab to the tnext entry" ) def about(self): mbx.showinfo("about", "\n\n created by austin heisley-cook\ndate 2/1/2018")
def generate(lang): global output_name text = random_page(lang) engine = CreateObject("SAPI.SpVoice") stream = CreateObject("SAPI.SpFileStream") from comtypes.gen import SpeechLib stream.Open('audio.mp3', SpeechLib.SSFMCreateForWrite) engine.AudioOutputStream = stream engine.speak(text) stream.Close() RESOLUTION = {800, 600} images = [] for filename in glob.glob('./images/*.jpg'): images.append(filename) IMAGE_NUMBER = len(images) audioclip = AudioFileClip("audio.mp3") duration = audioclip.duration seconds = duration print(seconds) fps = 30 total_frames = int(seconds * fps) FRAMES_PER_IMAGE = (total_frames) / IMAGE_NUMBER color_percentage_for_each_frame = (100 / total_frames) / 100 write_to = 'output/{}.mp4'.format('project') # have a folder of output where output files could be stored. writer = imageio.get_writer(write_to, format='mp4', mode='I', fps=fps) current_image = 0 next_change = FRAMES_PER_IMAGE for i in range(total_frames): if i < total_frames: im = Image.open(images[current_image]) im = im.resize(RESOLUTION) if (i >= next_change): current_image += 1 next_change += FRAMES_PER_IMAGE if (i >= len(images)): i = 0 processed = ImageEnhance.Color(im).enhance( color_percentage_for_each_frame * i) writer.append_data(np.asarray(processed)) else: writer.append_data(np.asarray(im)) writer.close() videoclip = VideoFileClip("./output/project.mp4") new_audioclip = CompositeAudioClip([audioclip]) videoclip.audio = new_audioclip videoclip = videoclip.subclip(0, duration) videoclip.write_videofile('./' + output_name + ".mp4") import os, shutil folder = './images' for filename in os.listdir(folder): file_path = os.path.join(folder, filename) try: if os.path.isfile(file_path) or os.path.islink(file_path): os.unlink(file_path) elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print('Failed to delete %s. Reason: %s' % (file_path, e)) return output_name + ".mp4"
class ThermoRawReaderUtility(object): def __init__(self, pathToFile): self.xrf = CreateObject('Xrawfile.Xrawfile') self.xrf.Open(szFileName=pathToFile) self.xrf.SetCurrentController(nControllerType=0, nControllerNumber=1) def call_Close(self): self.xrf.Close() def call_GetNumSpectra(self): numSpec = c_long(0) p_numSpec = pointer(numSpec) silence = self.xrf.GetNumSpectra(p_numSpec) return numSpec.value def call_RTFromScanNum(self, scanNumber): rt = c_double(0) p_rt = pointer(rt) silence = self.xrf.RTFromScanNum(nScanNumber=scanNumber, pdRT=p_rt) return rt.value def call_GetFilterForScanNum(self, scanNumber): filterEntry = BSTR() p_filterEntry = pointer(filterEntry) silence = self.xrf.GetFilterForScanNum(scanNumber, p_filterEntry) return filterEntry.value def call_GetInstMethod(self): instrMethod = BSTR() p_instrMethod = pointer(instrMethod) silence = self.xrf.GetInstMethod(0, p_instrMethod) return instrMethod.value def call_GetFilters(self): filters = VARIANT() p_filters = pointer(filters) silence = self.xrf.GetFilters(p_filters, pointer(c_int())) return filters.value def call_GetMassListFromScanNum(self, scanNum): scanNum = c_long(scanNum) p_scanNum = pointer(scanNum) centroidPeakWidth = c_double(0.0) # unused ?? p_centroidPeakWidth = pointer(centroidPeakWidth) massList = VARIANT() p_massList = pointer(massList) peakFlags = VARIANT() p_peakFlags = pointer(peakFlags) arraySize = c_int(0) p_arraySize = pointer(arraySize) silence = self.xrf.GetMassListFromScanNum( pnScanNumber=p_scanNum, bstrFilter='', nIntensityCutoffType=0, nIntensityCutoffValue=0, nMaxNumberOfPeaks=0, bCentroidResult=0, pdCentroidPeakWidth=p_centroidPeakWidth, pvarMassList=p_massList, pvarPeakFlags=p_peakFlags, pnArraySize=p_arraySize) return massList.value