[Tutor] SYS Long File Names?

2010-02-07 Thread FT

Hi!

I was looking at the sys.argv(1) file name and it is the short 8 char
name. How do you place it into the long file name format? I was reading
music files and comparing the name to the directory listing and always comes
back as not found because the name was shortened.

So, how do you get it to read long file names?

Bruce

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Sorting Dictionary Keys

2008-05-13 Thread FT

Jim,

OK, use the example below for sorting dictionary keys and placing them in a
list. Note that an error will happen if the format on the print statement
does not correspond to the type of sort.


#THIS SORTS A DICTIONARY BY USING SET THEORY AND DIC ITEMS!
import random
dic = {}
print "Randomizing!"
for i in range(20):
dic[ random.randrange(100)] = random.randrange(100, 1000)
print "Dic:"
j=0
list=[]
for k,i in dic.items():
print "K=%d I=%d" % (k,i)
list.append("K=%d I=%d" % (k,i))
j+=1

j=0
print "Sorted Dic By Set:"
print "Num: Old,  Sorted"
for k in sorted(set(dic)):
print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,dic[k])
j+=1

j=0
print "Sorted Dic By Items:"
print "Num: Old,  Sorted"
for k,i in sorted(dic.items()):
print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,i)
j+=1


--- On Tue, 5/13/08, James Hartley <[EMAIL PROTECTED]> wrote:

  From: James Hartley <[EMAIL PROTECTED]>
  Subject: [Tutor] sorting dictionary keys?
  To: tutor@python.org
  Date: Tuesday, May 13, 2008, 11:06 AM


I suspect this is a brain-dead question...

Given the following code, output is as expected:

$ cat test.py
d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 }

for i in d.keys():
print "%s\t%s" % (i, d[i])
$ python test.py
a   1
c   0
b   3
d   2
$

But if the keys are sorted, I get an error:
$ cat test1.py
d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 }

for i in d.keys().sort():
print "%s\t%s" % (i, d[i])
$ python test1.py
Traceback (most recent call last):
  File "test.py", line 3, in 
for i in d.keys().sort():
TypeError: 'NoneType' object is not iterable
$

What is the correct manner to iterate through sorted dictionary keys?

Thanks.

Jim

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Pythoncom Tutorial

2008-05-19 Thread FT

Hi!

I noticed that when wanting to learn Pythoncom there is no real good
accessible tutorial for it.
Does anyone know where a good structured tutorial exists for the Com
utilities so I can write my own screen reader program?

When trying to understand all the needed variables and such for the
windows commands and variables it gets confusing. I want to learn how to get
the objects and its methods so I can use a python program to read and
verbalize the objects as you focus on them and such. The only explanations I
found either have the descriptions scattered and no examples or structure on
how to use any of the com stuff.

How to use the Makepy and when not to use it. How to get the objects and
its list of methods to be able to work with it for screen reading purposes.

Thanks in advance.

Bruce

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Pythoncom Tutorial

2008-05-19 Thread FT

> Hi!
>
> I noticed that when wanting to learn Pythoncom there is
> no real good
> accessible tutorial for it.
> Does anyone know where a good structured tutorial exists
> for the Com
> utilities so I can write my own screen reader program?
>

Python Programming on Win32 might help. There's also a couple of
articles on OnLamp.

http://www.oreilly.com/catalog/9781565926219/index.html

Mike

Hi!

A book is nice if you can see to read it. Still searching for the best
way to go on this. It was suggested to go to the API of windowes or ctypes.
I confress that I have not used ctypes when just hoping to find a python
format to get such things as the focus information when jumping from window
to window. Or tag along saying what is going on at the moment and location
you are in. The name fo the object, and the variable or data info at the
moment in time...

Bruce


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] IDE

2008-06-10 Thread FT

From: "jordan halsey" <[EMAIL PROTECTED]>
Sent: Tuesday, June 10, 2008 1:40 PM
Any one here using cutter... http://www.fundza.com

Free Java based ide with many built in functions and bindings. This is an
especially useful tool if you are doing 3d or any kind of shader writing.


Also, try this editor:
http://www.contexteditor.org/

ConTEXT
Text Editor Features
unlimited open files
unlimited editing file size, 4kB line length
powerful syntax highlighting for:
C/C++
Delphi/Pascal
Java
Java Script
Visual Basic
Perl/CGI
HTML
CSS
SQL
FoxPro
80x86 assembler
Python
PHP
Tcl/Tk
XML
Fortran
Foxpro
InnoSetup scripts
powerful custom defined syntax highlighter
multilanguage support
English
German
French
Croatian
Chinese
Czech
Danish
Dutch
Estonian
Esperanto
Spanish
Galego
Italian
Hungarian
Portuguese (Brazil)
Russian
Slovakian
Polish
Lithuanian
Latvian
Slovenian
Turkish
project workspaces support
unicode UTF8 support
code templates
customizable help files for each file type
file explorer with favorites list
file compare
export to HTML/RTF
conversion DOS->UNIX->Macintosh file formats
editing position remembering across files
macro recorder
commenting/uncommenting code
text sort
normal and columnar text selection
bookmarks
search and replace with regular expressions
search and replace text in all open files
incremental search with text emphasizing
C/Java-style block auto indent/outdent
customizable color printing with print preview
exporting configuration stored in registry
customizable syntax highlighter colors, cursors, margin, gutter, line
spacing...
user definable execution keys, depending on file type
capturing console applications standard output
compiler output parser for positioning on error line
powerful command line handler

Powerful Python Editor
Edit, create, and navigate Python code easily. Free


Email:
[EMAIL PROTECTED]

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] If You Wish Microsoft Voices For Your Programming

2008-06-15 Thread FT

Hi!
Below is the settings to use the built in SAPI 5 voices. It will also
read any other voices loaded into the SAPI 5 and stores the list of all of
them.
You can change the names of the methods if you so desire. I am giving
you an example of how to set up your voices.
NOTE:
The pitch of the voices has to be an XML command and it is built into
the speech or Speak method. You will need to understand the XML commands if
you wish to use the added XML features. Pitch is just one and there is one
for spell, bookmarks, and so on...

Bruce

#DRIVERS FOR SAPI 5 AND VOICES!
#NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE
VALUES.
from comtypes.client import CreateObject
import _winreg

class constants4tts:
Wait = -1
Sync = 0
Async = 1
Purge = 2
Is_filename = 4
XML = 8
Not_XML = 16
Persist = 32
Punc = 64

class SynthDriver():
name="sapi5"
description="Microsoft Speech API version 5 (sapi.SPVoice)"
_pitch = 0
_voices = []
_wait = -1 #WAIT INDEFINITELY
_sync = 0 #WAIT UNTIL SPEECH IS DONE.
_async = 1 #DO NOT WAIT FOR SPEECH
_purge = 2 #CLEAR SPEAKING BUFFER
_is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE
_xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER.
_not_xml = 16 #NO XML COMMANDS
_persist_xml = 32 #Changes made in one speak command persist to other
calls to Speak.
_punc = 64 #PRONOUNCE ALL PUNCTUATION!
def check(self):
try:
r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice")
r.Close()
return True
except:
return False
#INITIALIZE ENGINE!
def init(self):
try:
self.tts = CreateObject( 'sapi.SPVoice')
self._voice=1
self._voiceCount = len(self.tts.GetVoices())
for v in range(self._voiceCount):
self._voices.append( self.tts.GetVoices()[v])
return True
except:
return False
#TERMINATE INSTANCE OF ENGINE!
def terminate(self):
del self.tts
#NUMBER OF VOICES FOR ENGINE!
def getVoiceCount(self):
return len(self.tts.GetVoices())
#NAME OF A VOICE NUMBER!
def getVoiceName(self, num):
return self.tts.GetVoices()[num-1].GetDescription()
#WHAT IS VOICE RATE?
def getRate(self):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
return (self.tts.rate)
#WHAT IS THE VOICE PITCH?
def getPitch(self):
"PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!"
return self._pitch
#GET THE ENGINE VOLUME!
def getVolume(self):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
return self.tts.volume
#GET THE VOICE NUMBER!
def getVoiceNum(self):
return self._voice
#SET A VOICE BY NAME!
def setVoiceByName(self, name):
"VOICE IS SET BY NAME!"
for i in range( self._voiceCount):
vp = self.tts.GetVoices()[ i].GetDescription().find( name)
if vp>0:
self.tts.Voice = self._voices[i]
#self.tts.Voice = self.tts.GetVoices()[i]
self.tts.Speak( "%s Set!" % name)
self._voice=i+1
break
if i >= self._voiceCount:
self.tts.Speak( "%s Not Found!" % name)
#USED FOR BOOKMARKING AND USE LATER!
def _get_lastIndex(self):
bookmark=self.tts.status.LastBookmark
if bookmark!="" and bookmark is not None:
return int(bookmark)
else:
return -1
#NOW SET ENGINE PARMS!
#SET THE VOICE RATE!
def setRate(self, rate):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
if rate > 10: rate = 10
if rate < -10: rate = -10
self.tts.Rate = rate
#SET PITCH OF THE VOICE!
def setPitch(self, value):
"MICROSOFT SAPI 5 pitch is really controled with xml around speECH
TEXT AND IS -10 TO 10"
if value > 10: value = 10
if value < -10: value = -10
self._pitch=value
#SET THE VOICE VOLUME!
def setVolume(self, value):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
self.tts.Volume = value
#CREATE ANOTHER INSTANCE OF A VOICE!
def createVoice(self, value=1):
if value > self.getVoiceCount:
value = self.getVoiceCount
if value < 1:
value = 1
new_tts = CreateObject( 'sapi.SPVoice')
return (new_tts.GetVoices()[ value-1])
#SPEAKING TEXT!
#SPEAK TEXT USING BOOKMARKS AND PITCH!
def SpeakText(self, text, wait=False, index=None):
"SPEAK TEXT AND XML FOR PITCH MUST REPLACE ANY <> SYMBOLS BEFORE
USING XML BRACKETED TEXT"
flags = constants4tts.XML
text = text.replace( "<", "<")
pitch = ((self._pitch*2)-100)/10
if isinstance(index, int):
bookmarkXML = "" % index #NOTE \" FOR
XML FORMAT CONVERSION!
else:
bookmarkXML = ""
flags = constants4tts.XML
if wait is False:
flags += constants4tts.Async
self.

[Tutor] Using SAPI 5 Voices and Methods

2008-06-16 Thread FT



Hi!

I am resending this SAPI examples for speech, I guess in some cases the 
email message gets messed up so I attached the
SAPI 5 test for voices along with an HTML version using Java Script. It also
has the methods and a voice by name assignment since the voices are an array
list by element. So I use the description to find the name. It also lists
the voice names in the console field.

I guess you could also use the pyTTS version as well. I did have one
problem and that was the isfilename flag seems to get an error. But, also my
spell tag did not work on my tower computer, but did work on my Lap Top. Do
not know why, but it could be a version issue. Yet the isfilename also does
not work on the Lap Top, so who knows.

Anyway, have fun and install if for either your games or web pages...

Bruce

#THE NEXT TO LAST TEST IS THE ISFILE AND I COMMENTED IT OUT FOR THERE IS AN 
ERROR!
import Sapi5, time, os

av = Sapi5.SynthDriver()
av.init()
SYNC = av._sync
ASYNC = av._async
PURGE = av._purge
ISFILE = av._is_filename
XML = av._xml
NOT_XML = av._not_xml
PERSIST = av._persist_xml
PUNC = av._punc
WAIT = av._wait

av.Speak("Hello!")
av.Speak( "I am speaking in the default voice!")
av.Speak( "Number of voices is: %d" % av.getVoiceCount())
av.Speak( "Hello! Now saying the punctuation in this sentence.", PUNC)
time.sleep(.5)
av.setVoiceByName( "Mike")
av.setVolume( 100)
av.Speak( " The Volume Is Set At Speaker Volume!")
av.setRate( 5)
av.setPitch(0)
av.setVoiceByName( "Mary")
av.setPitch(5)
av.Speak( "Set To Voice Mary and Pitch 5 or 75% of maximum pitch!")
time.sleep(1)
av.setPitch(0)
av.setRate(0)
av.Speak( "The rate and pitch are now set for normal!")
time.sleep(1)
av.read_Voices()
av.setVoiceByName( "Mary")
av.Speak( "Hit enter key to stop speaking!")
av.setPitch(10)
av.Speak("Pitch 100%", ASYNC)
av.setPitch(5)
av.Speak("Pitch 75%", ASYNC)
av.setPitch(0)
av.Speak("Pitch 50%", ASYNC)
av.setPitch( -5)
av.Speak("Pitch 25%", ASYNC)
av.setPitch( -10)
av.Speak("Pitch 0%", ASYNC)
av.setPitch(0)
av.Speak( "Hit enter key!", ASYNC)
hit = raw_input("Hit enter key >")
#av.SpeakFile( "readthis.txt", ASYNC, ISFILE)   
av.Speak(" Now Good bye", ASYNC, PURGE)
av.setVoiceByName( "Sam")
av.Speak( " goodbye")

#DRIVERS FOR SAPI 5 AND VOICES!
#NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES.
from comtypes.client import CreateObject
import _winreg

class constants4tts:
Wait = -1
Sync = 0
Async = 1
Purge = 2
Is_filename = 4
XML = 8
Not_XML = 16
Persist = 32
Punc = 64

class SynthDriver():
name="sapi5"
description="Microsoft Speech API version 5 (sapi.SPVoice)"
_pitch = 0
_voices = []
_wait = -1 #WAIT INDEFINITELY
_sync = 0 #WAIT UNTIL SPEECH IS DONE.
_async = 1 #DO NOT WAIT FOR SPEECH
_purge = 2 #CLEAR SPEAKING BUFFER
_is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE
_xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER.
_not_xml = 16 #NO XML COMMANDS
_persist_xml = 32 #Changes made in one speak command persist to other calls 
to Speak.
_punc = 64 #PRONOUNCE ALL PUNCTUATION!
def check(self):
try:
r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice")
r.Close()
return True
except:
return False
#INITIALIZE ENGINE!
def init(self):
try:
self.tts = CreateObject( 'sapi.SPVoice')
self._voice=1
self._voiceCount = len(self.tts.GetVoices())
for v in range(self._voiceCount):
self._voices.append( self.tts.GetVoices()[v])
return True
except:
return False
#TERMINATE INSTANCE OF ENGINE!
def terminate(self):
del self.tts
#NUMBER OF VOICES FOR ENGINE!
def getVoiceCount(self):
return len(self.tts.GetVoices())
#NAME OF A VOICE NUMBER!
def getVoiceName(self, num):
return self.tts.GetVoices()[num-1].GetDescription()
#WHAT IS VOICE RATE?
def getRate(self):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
return (self.tts.rate)
#WHAT IS THE VOICE PITCH?
def getPitch(self):
"PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!"
return self._pitch
#GET THE ENGINE VOLUME!
def getVolume(self):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
return self.tts.volume
#GET THE VOICE NUMBER!
def getVoiceNum(self):
return self._voice
#SET A VOICE BY NAME!
def setVoiceByName(self, name):
"VOICE IS SET BY NAME!"
for i in range( self._voiceCount):
vp = self.tts.GetVoices()[ i].GetDescription().find( name)
if vp>0:
self.tts.Voice = self._voices[i]
#self.tts.Voice = self.tts.GetVoices()[i]
self.tts.Speak( "%s Set!" % name)
self._voice=i+1
break
if i >= self._voiceCount:
self.tts.Speak( "%s Not Found!" % name)
#USED FOR BOOKMARKING 

Re: [Tutor] Using SAPI 5 Voices and Methods

2008-06-18 Thread FT

As a note to this message post: 
the error I was getting for both the spell and the isfilename was traced 
down to simple factors. One problem is finding clear explanations and then 
checking the erroor codes. I found both on the issues mentioned about the SAPI 
5 issues. The test I was running and encountered an error with the spell 
command came from using 2 different type voice packages as one. What I am 
saying is that I had the 3 Microsoft voices Sam, Mike, and Mary loaded in with 
6 eSpeak voices and the error came when I did a test using the eSpeak voice. 
Once I used the Microsoft voice the error went away. 
The error I traced to being a unsupported operator type in the ctypes error 
list:
WorkflowConditionOperatorNotSupported
-2147201006
"Condition operator not supported for specified type."

Error List:
http://msdn.microsoft.com/en-us/library/cc151248.aspx


The other error came from the open file command, which when using XML 
commands it is an Internet, Navigator error. When trying to understand the 
commands and the formats I could not truely understand what was being said, so 
I thought it could read a text.txt file but it does not. The isfilename comand 
is for reading a .wav file only. So I got rid of an flags except the isfilename 
flag, or 4 on the list and it worked. It will also work for sync or async, but 
you have to understand what each flat means and what it blocks. So this is the 
error description when using a wrong file type in the sapi XML ISFILENAME flag:

List Of Error Codes:
http://msdn.microsoft.com/en-us/library/aa768365(VS.85).aspx

NavigateError Event Status Codes
This page lists the possible values for the StatusCode parameter of the
DWebBrowserEvents2::NavigateError

-2146697203
INET_E_UNKNOWN_PROTOCOL
 (0x800C000DL or -2146697203)

There a lot of error codes on both lists and you just have to search the 
code number you wish to find. I am posting this for anyone that may encounter 
such errors when using SAPI 5 commands.

Sent: Monday, June 16, 2008 11:40 PM
Subject: [Tutor] Using SAPI 5 Voices and Methods!

Hi!
I guess in some cases the email message gets messed up so I attached the
SAPI 5 test for voices along with an HTML version using Java Script. It also
has the methods and a voice by name assignment since the voices are an array
list by element. So I use the description to find the name. It also lists
the voice names in the console field.

I guess you could also use the pyTTS version as well. I did have one
problem and that was the isfilename flag seems to get an error. But, also my
spell tag did not work on my tower computer, but did work on my Lap Top. Do
not know why, but it could be a version issue. Yet the isfilename also does
not work on the Lap Top, so who knows.

Anyway, have fun and install if for either your games or web pages...

Bruce
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] File Stream Assignment?

2008-06-20 Thread FT

Hi!

I would like to know how a file can be open for a stream event?

I ask this question because of the SAPI 5 save a wave file and the only
way to do that is with a file stream. The file read is simple and uses the
isfilename flag, but the save file I can not find in all my searches, at
least for python.

Bruce

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File Stream Assignment?

2008-06-21 Thread FT

On: Friday, June 20, 2008 11:47 PM
Kent Johnson Wrote:
On Fri, Jun 20, 2008 at 5:47 PM, FT <[EMAIL PROTECTED]> wrote:

>I would like to know how a file can be open for a stream event?

What is a stream event?

>I ask this question because of the SAPI 5 save a wave file and the only
> way to do that is with a file stream. The file read is simple and uses the
> isfilename flag, but the save file I can not find in all my searches, at
> least for python.

I have no idea what you are talking about.

Kent


Kent,

This is what I got from the Microsoft SAPI web site. They have only code
for C and VB and below is the VB version. I am trying to figure out where
the stram gets assigned to the speak method for SAPI so a file can be saved.

The following code illustrates how to speak a text file in a specific voice
in Visual
Basic. This example assumes a text file (ttstemp.txt) containing the text to
be spoken
already exists. ISpeechVoice.SpeakStream is used here to speak an
SpFileStream that
has been bound to the file.
Dim FileName As String
Dim FileStream As New SpFileStream
Dim Voice As  SpVoice
'Create SAPI voice
Set Voice = New SpVoice
'Assume that ttstemp.txt exists
FileName = "c:\ttstemp.txt"
'Open the text file
FileStream.Open FileName, SSFMOpenForRead, True
'Select Microsoft Sam voice
Set Voice.voice = voice.GetVoices("Name=Microsoft Sam",
"Language=409").Item(0)
'Speak the file stream
Voice.SpeakStream FileStream
'Close the Stream
FileStream.Close
'Release the objects
Set FileStream = Nothing
Set Voice = Nothing

So, in this example it assigns a file stream to the file opened then
connects to the SAPI Speak method to save it. But when I do that like they
did above I get only the data spoken and the file with 0 bytes in it.

I have tried looking everywhere for the file stream connection and can
not seem to find the method to do so.

Bruce

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File Stream Assignment?

2008-06-21 Thread FT



Alan Gauld Wrote:
"FT" <[EMAIL PROTECTED]> wrote

Caveat: I know nothing about MS SAPI.

> The following code illustrates how to speak a text file
> in a specific voice in Visual Basic. This example
Notice this says nothing about writing to a file.

> Dim FileName As String
> Dim FileStream As New SpFileStream
> Dim Voice As  SpVoice
> 'Create SAPI voice
And the code nowhere writes to a file. The only file
mentioned is the one read.

No, it calls the Speak method to speak it.
It never saves anything so far as I can see.

> did above I get only the data spoken and the file with 0 bytes in
> it.

I'm not sure which file has zero bytes. I hope not the one being
spoken!
But it sounds to me like your code is doing what the VB code does.

I'm confused about why you think it should be saving anything?

--
Alan Gauld
Author of the Learn to Program web site


Alan,

Sorry about that, I copied over to quickly and actually took the example
just below the one I wanted. This is the example and of course I looked back
after sending it and discovered the very same conclusion you came up with.

Below is the one I am talking about. How to connect the audio stream to
an open file for writing is what I am trying to do.

Speak to a wav file in automation
The following example is written in Visual Basic. It has the same
functionality as
the above in C++. After the creation of an SpFileStream object, a default
format,
SAFT22kHz16BitMono, is assigned to the object so that user does not need to
explicitly
assign a wav format to it unless a specific wav format is needed. In this
example,
ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the
FileStream
to the file. The third parameter of ISpeechFileStream.Open is the Boolean,
DoEvents.
The default of this parameter is set to False. However, the user should
always set
it to True to display SAPI events while playing back the wav file. If the
parameter
is set to False, no engine events will be stored in the file, resulting in
that no
engine events will be fired during the wav file play back.
Dim FileName As String
Dim FileStream As New SpFileStream
Dim Voice As  SpVoice
'Create a  SAPI voice
Set Voice = New SpVoice
'The output audio data will be saved to ttstemp.wav file
FileName = "c:\ttstemp.wav"
'Create a file; set DoEvents=True so TTS events will be saved to the file
FileStream.Open FileName, SSFMCreateForWrite, True
'Set the output to the FileStream
Set Voice.AudioOutputStream = FileStream
'Speak the text
Voice.Speak "hello world"
'Close the Stream
FileStream.Close
'Release the objects
Set FileStream = Nothing
Set Voice = Nothing

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File Stream Assignment?

2008-06-21 Thread FT

Alan,

This is what I wrote in python. The onlyu thing I did not do is a
declaration of a filestream as the VB example does. I get no errors, just
the Speak method just speaks. The saved file has no data, 0 Bytes.
Now the note they mentioned was the True flag and I inserted that.

import Sapi5, time, os
av = Sapi5.SynthDriver()
av.init()#AN ASSIGNMENT I COULD PLACE IN FIRST CALL AND CALL THE METHOD
.Create()
SYNC = av._sync
ASYNC = av._async
PURGE = av._purge
ISFILE = av._is_filename
XML = av._xml
NOT_XML = av._not_xml
PERSIST = av._persist_xml
PUNC = av._punc
WAIT = av._wait

av.Speak("Hello!")
av.Speak( "I am speaking in the default voice!")
av.Speak( "Number of voices is: %d" % av.getVoiceCount())
av.Speak( "Hello! Now saying the punctuation in this sentence.", PUNC)
time.sleep(.5)

file4tts = open('test.wav', 'w', True)
av.AudioOutputStream = file4tts
av.Speak( "Hello World!", ASYNC)
file4tts.close

Microsoft Example:
Speak to a wav file in automation
The following example is written in Visual Basic. It has the same
functionality as
the above in C++. After the creation of an SpFileStream object, a default
format,
SAFT22kHz16BitMono, is assigned to the object so that user does not need to
explicitly
assign a wav format to it unless a specific wav format is needed. In this
example,
ISpeechFileStream.Open creates a wav file, ttstemp.wav, and binds the
FileStream
to the file. The third parameter of ISpeechFileStream.Open is the Boolean,
DoEvents.
The default of this parameter is set to False. However, the user should
always set
it to True to display SAPI events while playing back the wav file. If the
parameter
is set to False, no engine events will be stored in the file, resulting in
that no
engine events will be fired during the wav file play back.
Dim FileName As String
Dim FileStream As New SpFileStream
Dim Voice As  SpVoice
'Create a  SAPI voice
Set Voice = New SpVoice
'The output audio data will be saved to ttstemp.wav file
FileName = "c:\ttstemp.wav"
'Create a file; set DoEvents=True so TTS events will be saved to the file
FileStream.Open FileName, SSFMCreateForWrite, True
'Set the output to the FileStream
Set Voice.AudioOutputStream = FileStream
'Speak the text
Voice.Speak "hello world"
'Close the Stream
FileStream.Close
'Release the objects
Set FileStream = Nothing
Set Voice = Nothing

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] File Stream Assignment?

2008-06-21 Thread FT


Alan Gauld Wrote:
"FT" <[EMAIL PROTECTED]> wrote

Caveat: I know nothing about MS SAPI.

> The following code illustrates how to speak a text file
> in a specific voice in Visual Basic. This example assumes
> a text file (ttstemp.txt) containing the text to be spoken
> already exists. ISpeechVoice.SpeakStream is used here
> to speak an SpFileStream that
> has been bound to the file.

Snip
I have no idea what you mean by this.
Where are you looking? This is a COM object which is in the MS
library.
You will need to access it via PythonWin or ctypes or a Python
wrapper of some sort. But the fact you are getting it to speak
suggests
you have succeeded in that already.

I'm confused about why you think it should be saving anything?

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

Hi Alan,

I did a search and I think it was about the 30'th search or more and
finally came out with the exact code. Interesting enough it was on the win32
site and a person did not want to use the working code for something more
like I was originally searching for, but it works.

Below is the method I placed it into. I use the same Create function but
the added feature is the lib and it was inside the Create assignment itself.
You were correct in it needed to be in the com stuff. I do not know all that
I need to know about this for there is so much to search and read to tie it
all together. So I do it one piece at a time. I also used the same naming
convention as the built in Speak method and I did not have to use C code to
get it runnhing, instead used the same imports I already had.

I attached the complete speech class module I am developing and the
methods I am using at the moment.

Here is the method:
from comtypes.client import CreateObject #NEEDED IF THIS METHOD IS A STAND
ALONE!
#SET AUDIO STREAM FOR OUTPUT TO A FILE!
def SpeakToWav(self, filename, text):
"""THIS METHOD ASSUMES THE IMPORT OF COMTYPES.CLIENT createObject SO
A VOICE AND FILE STREAM OBJECT ARE CREATED WITH THE PASSING IN
OF
THE FILE NAME TO SAVE THE VOICE INTO AND THE TEXT DATA TO SPEAK
AND STORE
ONCE THE TEXT IS SPOKEN INTO THE FILE IT IS CLOSED AND THE
OBJECTS DESTROYED!"""
stream = CreateObject("SAPI.SpFileStream")
tts4file = CreateObject( 'sapi.SPVoice')
from comtypes.gen import SpeechLib
stream.Open( filename, SpeechLib.SSFMCreateForWrite)
tts4file.AudioOutputStream = stream
tts4file.Speak( text, 0)
stream.Close()
del tts4file
del stream

#DRIVERS FOR SAPI 5 AND VOICES!
#NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES.
from comtypes.client import CreateObject
import _winreg

class constants4tts:
Wait = -1
Sync = 0
Async = 1
Purge = 2
Is_filename = 4
XML = 8
Not_XML = 16
Persist = 32
Punc = 64

class SynthDriver():
name="sapi5"
description="Microsoft Speech API version 5 (sapi.SPVoice)"
_pitch = 0
_voices = []
_wait = -1 #WAIT INDEFINITELY
_sync = 0 #WAIT UNTIL SPEECH IS DONE.
_async = 1 #DO NOT WAIT FOR SPEECH
_purge = 2 #CLEAR SPEAKING BUFFER
_is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE
_xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER.
_not_xml = 16 #NO XML COMMANDS
_persist_xml = 32 #Changes made in one speak command persist to other calls 
to Speak.
_punc = 64 #PRONOUNCE ALL PUNCTUATION!
def check(self):
try:
r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice")
r.Close()
return True
except:
return False
#INITIALIZE ENGINE!
def init(self):
try:
self.tts = CreateObject( 'sapi.SPVoice')
self._voice=1
self._voiceCount = len(self.tts.GetVoices())
for v in range(self._voiceCount):
self._voices.append( self.tts.GetVoices()[v])
return True
except:
return False
#TERMINATE INSTANCE OF ENGINE!
def terminate(self):
del self.tts
#NUMBER OF VOICES FOR ENGINE!
def getVoiceCount(self):
return len(self.tts.GetVoices())
#NAME OF A VOICE NUMBER!
def getVoiceName(self, num):
return self.tts.GetVoices()[num-1].GetDescription()
#WHAT IS VOICE RATE?
def getRate(self):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
return (self.tts.rate)
#WHAT IS THE VOICE PITCH?
def getPitch(self):
"PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!"
return self._pitch
#GET THE ENGINE VOLUME!
def getVolume(self):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
return self.tts.volume
#GET THE VOICE NUMBER!
def getVoiceNum(self):
re

[Tutor] A SAPI Module With Pitch and Create

2008-06-22 Thread FT

Hi!

I have reduced down and added a few features into the SAPI 5 speech
module I have created. You can now save and read wav files.

The test module tests most of the features I have in it at the moment.

I added the ability inside the Create method to set all the voice
parameters. You can change the voice, volume, rate, and pitch in the Create
method. They are dict values and just assign the values you want. Pitch and
rate are from -10 to 10 with 0 the norm. Where the volume is from 0% to 100%
but do not use the (%) symbol, just the integer number.

The default for change is 0 for any of the values and the default voice
will be the first on the list, which is Sam if you are using the Microsoft
SAPI 5 voices.

The names are listed in the test. So assignment depends on what you have
installed onto your machine. I have not changed any usage of eSpeak voices
to allow pitch adjustment yet. An error comes up for those voices because I
have not looked into what it wants.

This SAPI 5 engine will at least allow you to get started and includes
the methods saving and reading a wav file.

The wav methods are .SpeakToWav and SpeakFromWav so you could use it for
other possible things, such as web sites and games.

Enjoy testing it. I have not played with the bookmark method yet.

Bruce

#DRIVERS FOR SAPI 5 AND VOICES!
#NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES.
from comtypes.client import CreateObject
import _winreg

class constants4tts:
Wait = -1
Sync = 0
Async = 1
Purge = 2
Is_filename = 4
XML = 8
Not_XML = 16
Persist = 32
Punc = 64

class SynthDriver():
name="sapi5"
description="Microsoft Speech API version 5 (sapi.SPVoice)"
_voice = 0
_pitch = 0
_voices = []
_wait = -1 #WAIT INDEFINITELY
_sync = 0 #WAIT UNTIL SPEECH IS DONE.
_async = 1 #DO NOT WAIT FOR SPEECH
_purge = 2 #CLEAR SPEAKING BUFFER
_is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE
_xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER.
_not_xml = 16 #NO XML COMMANDS
_persist_xml = 32 #Changes made in one speak command persist to other calls 
to Speak.
_punc = 64 #PRONOUNCE ALL PUNCTUATION!
def check(self):
try:
r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice")
r.Close()
return True
except:
return False
#INITIALIZE ENGINE!
def init(self):
try:
self.tts = CreateObject( 'sapi.SPVoice')
self._voice=0
self._voiceCount = len(self.tts.GetVoices())
for v in range(self._voiceCount):
self._voices.append( self.tts.GetVoices()[v])
return True
except:
return False
#TERMINATE INSTANCE OF ENGINE!
def terminate(self):
del self.tts
#NUMBER OF VOICES FOR ENGINE!
def getVoiceCount(self):
return len(self.tts.GetVoices())
#NAME OF A VOICE BY NUMBER!
def getVoiceNameByNum(self, num):
return self.tts.GetVoices()[num-1].GetDescription()
#NAME OF A VOICE!
def getVoiceName(self):
return self.tts.GetVoices()[ self._voice].GetDescription()
#WHAT IS VOICE RATE?
def getRate(self):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
return (self.tts.rate)
#WHAT IS THE VOICE PITCH?
def getPitch(self):
"PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!"
return self._pitch
#GET THE ENGINE VOLUME!
def getVolume(self):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
return self.tts.volume
#GET THE VOICE NUMBER!
def getVoiceNum(self):
return self._voice
#SET A VOICE BY NAME!
def setVoiceByName(self, name):
"VOICE IS SET BY NAME!"
for i in range( self._voiceCount):
if self.tts.GetVoices()[ i].GetDescription().find( name) >= 0:
self.tts.Voice = self._voices[i]
#self.tts.Speak( "%s Set!" % name)
self._voice=i
break
if i >= self._voiceCount:
self.tts.Speak( "%s Not Found!" % name)
#USED FOR BOOKMARKING AND USE LATER!
def _get_lastIndex(self):
bookmark=self.tts.status.LastBookmark
if bookmark!="" and bookmark is not None:
return int(bookmark)
else:
return -1
#NOW SET ENGINE PARMS!
#SET THE VOICE RATE!
def setRate(self, rate):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
if rate > 10: rate = 10
if rate < -10: rate = -10
self.tts.Rate = rate
#SET PITCH OF THE VOICE!
def setPitch(self, value):
"MICROSOFT SAPI 5 pitch is really controled with xml around speECH TEXT 
AND IS -10 TO 10"
if value > 10: value = 10
if value < -10: value = -10
self._pitch=value
#SET THE VOICE VOLUME!
def setVolume(self, value):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
self.tts.Volume = value
#CREATE ANOTHER INSTANCE OF A VOICE!
  

[Tutor] Transporting Voices For Sapi

2008-06-25 Thread FT


Hi!

I am sending the latest version of my voice package and 2 different
tests. When compiling the Voice2.py you may get an error if you do not have
MSVcp.dll copied into your setup.py file. In other words a copy command to
copy the dll from your system32 folder. For if you do not, some computers it
is run on will fail if they do not have that dll installed.

I noticed that when compiling the Voice2 using py2exe and sending it to
someone else that it does not take the voices with it. I was wondering if
anyone knows how that can be done? How to wrap the voices you have installed
into the py2exe compiled version?

Sincerely
Bruce

#DRIVERS FOR SAPI 5 AND VOICES!
#NOTE THE CONSTANTS AND IN THE SPEAK FUNCTION AND THE ADDING/OR OF THE VALUES.
from comtypes.client import CreateObject
import _winreg

class constants4tts:
Wait = -1
Sync = 0
Async = 1
Purge = 2
Is_filename = 4
XML = 8
Not_XML = 16
Persist = 32
Punc = 64

class SynthDriver():
name="sapi5"
description="Microsoft Speech API version 5 (sapi.SPVoice)"
_voice = 0
_pitch = 0
_voices = []
_wait = -1 #WAIT INDEFINITELY
_sync = 0 #WAIT UNTIL SPEECH IS DONE.
_async = 1 #DO NOT WAIT FOR SPEECH
_purge = 2 #CLEAR SPEAKING BUFFER
_is_filename = 4 #OPEN WAV FILE TO SPEAK OR SAVE TO WAV FILE
_xml = 8 #XML COMMANDS, PRONUNCIATION AND GRAMMER.
_not_xml = 16 #NO XML COMMANDS
_persist_xml = 32 #Changes made in one speak command persist to other calls 
to Speak.
_punc = 64 #PRONOUNCE ALL PUNCTUATION!
def check(self):
try:
r=_winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT,"SAPI.SPVoice")
r.Close()
return True
except:
return False
#INITIALIZE ENGINE!
def init(self):
try:
self.tts = CreateObject( 'sapi.SPVoice')
self._voice=0
self._voiceCount = len(self.tts.GetVoices())
for v in range(self._voiceCount):
self._voices.append( self.tts.GetVoices()[v])
return True
except:
return False
#TERMINATE INSTANCE OF ENGINE!
def terminate(self):
del self.tts
#NUMBER OF VOICES FOR ENGINE!
def getVoiceCount(self):
return len(self.tts.GetVoices())
#NAME OF A VOICE BY NUMBER!
def getVoiceNameByNum(self, num):
return self.tts.GetVoices()[ num].GetDescription()
#NAME OF A VOICE!
def getVoiceName(self):
return self.tts.GetVoices()[ self._voice].GetDescription()
#WHAT IS VOICE RATE?
def getRate(self):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
return (self.tts.rate)
#WHAT IS THE VOICE PITCH?
def getPitch(self):
"PITCH FOR MICROSOFT SAPI 5 IS AN XML COMMAND!"
return self._pitch
#GET THE ENGINE VOLUME!
def getVolume(self):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
return self.tts.volume
#GET THE VOICE NUMBER!
def getVoiceNum(self):
return self._voice
#SET A VOICE BY NAME!
def setVoiceByName(self, name):
"VOICE IS SET BY NAME!"
for i in range( self._voiceCount):
if self.tts.GetVoices()[ i].GetDescription().find( name) >= 0:
self.tts.Voice = self._voices[i]
#self.tts.Speak( "%s Set!" % name)
self._voice=i
break
if i >= self._voiceCount:
self.tts.Speak( "%s Not Found!" % name)
#USED FOR BOOKMARKING AND USE LATER!
def _get_lastIndex(self):
bookmark=self.tts.status.LastBookmark
if bookmark!="" and bookmark is not None:
return int(bookmark)
else:
return -1
#NOW SET ENGINE PARMS!
#SET THE VOICE RATE!
def setRate(self, rate):
"MICROSOFT SAPI 5 RATE IS -10 TO 10"
if rate > 10: rate = 10
if rate < -10: rate = -10
self.tts.Rate = rate
#SET PITCH OF THE VOICE!
def setPitch(self, value):
"MICROSOFT SAPI 5 pitch is really controled with xml around speECH TEXT 
AND IS -10 TO 10"
if value > 10: value = 10
if value < -10: value = -10
self._pitch=value
#SET THE VOICE VOLUME!
def setVolume(self, value):
"MICROSOFT SAPI 5 VOLUME IS 1% TO 100%"
self.tts.Volume = value
#CREATE ANOTHER INSTANCE OF A VOICE!
def createVoice(self, name):
num = 0
for i in range( self._voiceCount):
if self.tts.GetVoices()[ i].GetDescription().find( name) >= 0:
num=i
break
new_tts = CreateObject( 'sapi.SPVoice')
new_tts.Voice = self._voices[ num]
return (new_tts)
#SPEAKING TEXT!
#SPEAK TEXT USING BOOKMARKS AND PITCH!
def SpeakText(self, text, wait=False, index=None):
"SPEAK TEXT AND XML FOR PITCH MUST REPLACE ANY <> SYMBOLS BEFORE USING 
XML BRACKETED TEXT"
flags = constants4tts.XML
text = text.replace( "<", "<")
pitch = ((self._pitch*2)-100)/10
if isinstance(index

Re: [Tutor] Transporting Voices For Sapi and DLL Correction

2008-06-25 Thread FT




Hi!

I am sending the latest version of my voice package and 2 different
tests. When compiling the Voice2.py you may get an error if you do not have
MSVcp71.dll copied into your setup.py file. In other words a copy command to
copy the dll from your system32 folder. For if you do not, some computers it
is run on will fail if they do not have that dll installed.

I noticed that when compiling the Voice2 using py2exe and sending it to
someone else that it does not take the voices with it. I was wondering if
anyone knows how that can be done? How to wrap the voices you have installed
into the py2exe compiled version?

Sincerely
Bruce







___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] addressbook program

2008-06-28 Thread FT

Hi Alan,

You said:
> #DO TEXT INPUT WITH ENTRY ON NEXT LINE!
> def text_Input(prompt):
> print prompt
> return (raw_input(">> "))

Just use:

raw_input(prompt + "\n>> " )

Yes, that is OK if you are sighted, for the screen reader program does
not say the message in the prompt unless there is some kind of a change in
the screen.
I have to place it there for only a sightless programmer. Maybe once in
a while it would say it, but that is if the key stroke is fast and the kill
speech is quick. Like the purge command inside the example, when that is set
for all key strokes in a screen reader, it can erase any saying of text
displayed fast onto the screen, just a timing issue between keyboard and
screen reader capture.
So, my example is just accommodating that.

The other examples are true, I sent it without making the needed
changes. Probably too many try statements only because I wrote an input for
my Trek program that entered values of a given type and kind of left it
there if the wrong type is entered. Which brings up the other dictionary
list of keys. Just left it there when sending the example to fast. Just like
the last method which uses pygame, but it is never called and would fail
since I did not import pygame.

So, sending an outdated example is not good, but does lead to showing
the correct sample in a tutorial when you point out errors or sloppy work.

Thanks, Bruce

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Mixer and Busy Flag Never Working?

2008-07-03 Thread FT


A Question:

Has anyone ever played with Pygame and the sound mixer? If so, has
anyone ever had the busy flag, and the problem below ever work?

Subject: Re: [pygame] Mixer Quit / Restart

This appears to get the total number of channels, not the number of active
channels.  However, I tried using get_busy(), but it still does not seem to
work.

See the following modifications to my original code:

import pygame, time

for x in range(10):
print("Starting iteration " + str(x))
print("Initializing mixer")
pygame.mixer.init()

print("Loading sound")
sound = pygame.mixer.Sound("foo.wav")
print("Finding free channel")
channel = pygame.mixer.find_channel()

print("Channel object: " + str(channel))

print("Setting volume")
channel.set_volume(0.7)

print("Playing sound")
channel.play(sound)

print("Sleeping until sound is finished playing...")
while pygame.mixer.get_busy():
time.sleep(1)

print("Quitting mixer\n\n")
pygame.mixer.quit()



This displays the same behaviour.

In response to a previous comment about using channel.stop() before quitting
the mixer: this does not work either, as can be seen by adding
channel.stop() after the get_busy loop above.


Has anyone tried running this code themselves?  I am wondering if I am
experiencing some obscure bug, possibly platform specific.  I am running on
OS X, but don't have access to other systems for troubleshooting.  If
someone else has access to a Windows or Linux box, and is able to prove if
this fails on those systems as well, that may be useful.

Cheers

Ian Mallett wrote:
  On 7/2/08, Wyatt Olson <[EMAIL PROTECTED]> wrote:
Is there anything which can return a list of all currently active
channels?
  pygame.mixer.get_num_channels()
  This returns 0 if none are playing and > 0 if there are.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] open-file GUI

2008-07-04 Thread FT

Hi!
My demo is from wspython.



Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to MATLAB.

I need a simple GUI that can help me to open files and save file i.e. something 
similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse 
through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile and 
similar commands.
After I process the data I want a similar GUI that enables choosing the path 
and name for saving the results file.

Are scripts of this type available ?

Thanks
Eli Brosh


This method allows you to either display the last file name or change the fn to 
"" for an open command so it does not display the file name. Then fn assignment 
commented out...



def setFilePath(self, type4file=""):
" Search directory for path and file name!"
fn=self.filename
t4f = wx.OPEN
if type4file[0] in "sS":
t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#fn = self.filename
dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
dlg.Destroy()

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] open-file GUI

2008-07-04 Thread FT



Hi!
My demo is from wspython.



Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to MATLAB.

I need a simple GUI that can help me to open files and save file i.e. something 
similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse 
through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile and 
similar commands.
After I process the data I want a similar GUI that enables choosing the path 
and name for saving the results file.

Are scripts of this type available ?

Thanks
Eli Brosh
 

This method allows you to either display the last file name or change the fn to 
"" for an open command so it does not display the file name. Then fn assignment 
commented out... 

self.dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
self.filename="" 

def setFilePath(self, type4file=""):
" Search directory for path and file name!"
fn=self.filename
t4f = wx.OPEN
if type4file[0] in "sS":
t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#fn = self.filename
dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
dlg.Destroy()

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] open-file GUI

2008-07-04 Thread FT

Hi!
My demo is from wspython. The Hebrew window messed up my reading and now
I have included the imports and the initial assignment. You can place them
in caps for global vars, but place them inside a class so they are
self...calls.



Hello,
I am starting to use Python+NumPy+SciPy+Matplotlib as a substitute to
MATLAB.

I need a simple GUI that can help me to open files and save file i.e.
something similar to uigetfile in MATLAB.
Is there a simple script that opens a window with a possibility to browse
through the file system and pick an ASCII file ?
After the file is spcified using the GUI, I want to read it using fromfile
and similar commands.
After I process the data I want a similar GUI that enables choosing the path
and name for saving the results file.

Are scripts of this type available ?

Thanks
Eli Brosh



This method allows you to either display the last file name or change the fn
to "" for an open command so it does not display the file name. Then fn
assignment commented out...

import wx
import os


dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
filename=""

def setFilePath(self, type4file=""):
" Search directory for path and file name!"
fn=self.filename
t4f = wx.OPEN
if type4file[0] in "sS":
t4f = wx.SAVE|wx.FD_OVERWRITE_PROMPT
#fn = self.filename
dlg = wx.FileDialog(self, self.filename +" or Choose a file",
self.dirname, fn, "*.*", t4f)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
dlg.Destroy()


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Voice Text To Speech and Wav File Make and Save

2008-07-05 Thread FT

Hi!

I got my text to speech to work better, will in the future remove the
buttons and only have the file menu.
It seems to work fine and now use sub menu's for voice settings.

What will be needed as an event to capture the cursor movement inside
the text box. How do I get the key and cursor events so I can speak when
doing ctrl cursor or up/down cursor events to say lines, words, and letters?
I have tried getting the key event but gets ignored, so I need the
proper kind and location to catch the text box key events. I erased my test,
but below and attached are the complete setup.

Bruce



desc="""Using two nested sizers, the main one with vertical layout
and the embedded one with horizontal layout
For setting voice parms:"""
#Editor.py
import wx
import os
import Sapi5
tts = Sapi5.Create( {"name":"Mary"})
purge = tts._purge
async = tts._async
punc = tts._punc
MN=0
ID=1
HK=2
KD=3
MF=4
MF2=5
DW_ID=1000
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
self.dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
self.filename=""
self.items4menu = {"File": [
{MN:"Open", ID:102, HK:"&Open", KD:" Open a file to edit",
MF:self.OnOpen},
{MN:"Save", ID:103, HK:"&Save", KD:" save file to disk",
MF:self.OnSave},
{MN:"Edit", ID:104, HK:"&Edit", KD:" Do editing",
MF:self.OnEdit},
{MN:"About", ID:101, HK:"&About", KD:" Information about this
program", MF:self.OnAbout},
{MN:"Exit", ID:109, HK:"E&xit", KD:" Terminate the program",
MF:self.OnExit}
],  #END OF FILE MENU!
"Voice": [
{MN:"Read", ID:202, HK:"&Read", KD:" Open a file to read",
MF:self.OnWav2Read},
{MN:"Save", ID:203, HK:"&Save", KD:" save text to audio file",
MF:self.OnSave2Wav},
{MN:"Text", ID:204, HK:"Te&xt", KD:" read text field",
MF:self.OnRead},
{MN:"Quit", ID:205, HK:"&Quit", KD:" Stop Reading",
MF:self.OnQuitRead}
],  #END OF VOICE MENU!
"Settings": [
{MN:"Voice", ID:302, HK:"&Speaker", KD:" Name for voice.",
MF:self.OnVoice, MF2:self.OnClick},
{MN:"Rate", ID:303, HK:"&Rate", KD:" Rate for voice.",
MF:self.OnVoice, MF2:self.OnClick},
{MN:"Pitch", ID:304, HK:"&Pitch", KD:" Pitch for voice.",
MF:self.OnVoice, MF2:self.OnClick},
{MN:"Volume", ID:305, HK:"&Volume", KD:" Volume for voice.",
MF:self.OnVoice, MF2:self.OnClick}
],  #END OF SETTINGS MENU!
"Down": [
{MN:"Down", ID:DW_ID, HK:"&Down", KD:" Lower Setting.",
MF:self.OnVoice, MF2:self.OnClick}
]  #END OF DOWN MENU!
}  #END OF ITEMS FOR MENU!
self.buttons4voice = [
{MN:"Voice", ID:111, HK:"&Voice", KD:" Voice Change",
MF:self.OnEnter, MF2:self.OnClick},
{MN:"Rate", ID:112, HK:"&Rate", KD:" Rate For Voice Adjust",
MF:self.OnEnter, MF2:self.OnClick},
{MN:"Pitch", ID:113, HK:"&Pitch", KD:" Pitch Of Voice Adjust",
MF:self.OnEnter, MF2:self.OnClick},
{MN:"Volume", ID:114, HK:"&Loudness", KD:" Volume Loudness
Adjust", MF:self.OnEnter, MF2:self.OnClick}
]  #END OF ITEM FOR BUTTONS!
wx.Frame.__init__(self, parent, wx.ID_ANY, title)
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
self.CreateStatusBar()  #A Statusbar in the bottom of the window
#Setting up the menu.
filemenu = wx.Menu()
for o in self.items4menu["File"]:
filemenu.Append( o[ID], o[HK], o[KD])
filemenu.AppendSeparator()
voicemenu = wx.Menu()
for o in self.items4menu["Voice"]:
voicemenu.Append( o[ID], o[HK], o[KD])
voicemenu.AppendSeparator()
setting_menu = wx.Menu()
for o in self.items4menu["Settings"]:
down_menu = wx.Menu()
down_menu.Append( o[ID], o[HK], o[KD])
d = self.items4menu["Down"][0]
down_menu.Append( d[ID]+o[ID], d[HK], d[KD])
setting_menu.AppendMenu( o[ID], o[HK]+" Setting", down_menu)
setting_menu.AppendSeparator()
voicemenu.AppendMenu(-1, "&VoiceSettings", setting_menu)
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append( filemenu,"&File") # Adding the "filemenu" to the
MenuBar
menuBar.Append( voicemenu,"&Voice") # Adding the "voicemenu" to the
MenuBar
self.SetMenuBar(menuBar)  # Adding the MenuBar to the Frame content.
self.data4menu = {}
for o in self.items4menu["File"]:
wx.EVT_MENU(self, o[ID], o[MF])
self.data4menu[ o[ID]] = o
for o in self.items4menu["Voice"]:
wx.EVT_MENU(self, o[ID], o[MF])
self.data4menu[ o[ID]] = o
for o in self.items4menu["Settings"]:
wx.EVT_MENU(self, o[ID], o[MF])
self.data4menu[ o[ID]] = o
wx.EVT_MENU(self, o[ID]+DW_ID, o[MF])
self.data4menu[ o[ID]+DW_ID] = o

Re: [Tutor] New to pythong

2008-07-07 Thread FT

Hi!


Yes, Mark had something to say, and so did Alan. Games are a good start, 
also a home need, or a business need. 
The way I started Python was games. The Yhatzee game, then my Star Trek 
game, converted over from the original basic game. Then the battleship game, 
the board game, which required people to call out grid places to see if a ship 
was hit...
Since I am visually impaired, and sounds are all I need, then the first 
games are all sound effects and voices. Then the need for a sighted person to 
understand, then the visual, buttons and menu's come in. Then the rest is your 
imagination.

For when learning each level of python a new need arises. I solved the 
event issue I raised last by playing with the details of events, understanding 
what is needed, and reading the formats and playing with them to see the 
results. Many commands, just select which works best.

For when writing python programs you must understand the dictionary and 
list formats. They come in handy. As does the list comprehension idea and it's 
format.

Many things to try and do. Just have to come up with a need, or fun. The 
rest of the imagination is yours.

Just remember that at first the program is large, bulky, then once other 
formats and commands are learned, the program gets smaller, then larger to fit 
more options, then smaller...

Think of a game to play and then expand on it.

Bruce




Thanks for the info on the Think Python book, and thanks Jeremiah, for posing 
this question. That book is one of the best Python learning resources I've yet 
found! Makes it really easy to understand!

Nick



On Mon, Jul 7, 2008 at 12:43 PM, Marc Tompkins <[EMAIL PROTECTED]> wrote:

  On Mon, Jul 7, 2008 at 9:40 AM, Jeremiah Stack <[EMAIL PROTECTED]> wrote:



Hello everybody:

I am new to this mailing list, and it said that i could the simplest of 
questions. So i was wondering if anyone could be so kind as to e-mail me a 
project idea or something to go out an learn to do in python. I don't know any 
languages, but i am definitely not computer illiterate. i have read so many 
tutorial about getting started but so far that is where the tutorial have left 
me ( how to print  "Hello World") and such. 

Any ideas great thanks.



  First of all, I mean no offense to the OP.  However, this question comes up a 
lot on this list, and it always bugs me.  People decide they want to learn 
Python, and then ask strangers to give them a reason to do it.  I may be 
totally wrong about this, but it doesn't seem like a good way to learn 
_anything_, let alone a programming language.  The most important element for 
success is enthusiasm, and how can you generate any enthusiasm working on 
somebody else's homework project?  Unless you learn best under external 
discipline, in which case I suggest you take a class...

  My advice to all potential Pythonistas who want to learn on their own: think 
of a problem you need to solve, or a cool game you've wanted to implement, or a 
tool you want but don't have.  In my own case, I had a project I needed to do 
(printing mailing labels from records in an old proprietary database) that was 
going to suck if I used only the tools I already had.  I'd been wanting to get 
into Python, and I decided to use Python to do the job and learn as I went.  It 
was WONDERFUL, and I've been in love with Python ever since.  (Yes, I've used 
it for fun stuff since then, but my first experience was of Python saving me 
hours and hours of pain.)

  If you don't have a professional task that you could apply Python to, just 
look around your environment for a day or so looking for problems to solve.  
(My favorite example of this, although it's a very silly program and written in 
JavaScript besides, is Roast Beef's "Eggs and Milk Minder" from Achewood.)  

  Just my €0.0075...


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] New to pythong

2008-07-07 Thread FT

Hello everybody:

I am new to this mailing list, and it said that i could the simplest of 
questions. So i was wondering if anyone could be so kind as to e-mail me a 
project idea or something to go out an learn to do in python. I don't know any 
languages, but i am definitely not computer illiterate. i have read so many 
tutorial about getting started but so far that is where the tutorial have left 
me ( how to print  "Hello World") and such. 

Any ideas great thanks.

Hi!

Someone posted the description on how to fid and list files. This is one 
you could look at, study, and then expand on it. I added the file search as 
well.

In each module you can expand and do much more with it, but when dealing 
with files and directories you must remember that you can erase a lot of stuff 
if you're not careful.


Enjoy, Bruce



import sys, os   # imports all the functions in the os module (operating system 
functions)
cwd = os.getcwd()   # gets the current working directory and places it in the 
variable cwd
print "Enter file to search for: "
file2find = str(raw_input("__>"))
if file2find=="":
sys.exit()
dirFiles = open( "filelist.txt","w")  # creates the file filelist.txt ready for 
writing using the variable dirFiles
# the walk function returns the current directory in root, the directories in 
dirs
# and the files in root in files. By using the for loop it traverses every 
folder
# from the starting folder.
c=0  #Count the files found!
for root, dirs, files in os.walk(cwd):
#dirFiles.write(root + "\n")   # writes to dirFiles.txt the current 
directory name
i=0   #file count for directory to save directory path if found!
for theFiles in files:  # will iterate all the files in the current 
directory
if file2find in theFiles:
i+=1
c+=1
if i==1:
dirFiles.write(root + "\n")   # writes to dirFiles.txt the 
current directory name
dirFiles.write( "___ " + theFiles + "\n") # writes the 
filename to dirlist.txt. the
dirFiles.close() # Cleanly saves and closes the file dirlist.txt
# Note: the "\n" in the write lines adds the newline character so that the next 
write starts on a newline



import sys, os   # imports all the functions in the os module (operating system 
functions)
cwd = os.getcwd()   # gets the current working directory and places it in the 
variable cwd
print "Enter file to search for: "
file2find = str(raw_input("__>"))
if file2find=="":
sys.exit()
dirFiles = open( "filelist.txt","w")  # creates the file filelist.txt ready for 
writing using the variable dirFiles
# the walk function returns the current directory in root, the directories in 
dirs
# and the files in root in files. By using the for loop it traverses every 
folder
# from the starting folder.
c=0  #Count the files found!
for root, dirs, files in os.walk(cwd):
#dirFiles.write(root + "\n")   # writes to dirFiles.txt the current 
directory name
i=0   #file count for directory to save directory path if found!
for theFiles in files:  # will iterate all the files in the current 
directory
if file2find in theFiles:
i+=1
c+=1
if i==1:
dirFiles.write(root + "\n")   # writes to dirFiles.txt the 
current directory name
dirFiles.write( "___ " + theFiles + "\n") # writes the 
filename to dirlist.txt. the
dirFiles.close() # Cleanly saves and closes the file dirlist.txt
# Note: the "\n" in the write lines adds the newline character so that the next 
write starts on a newline

import os   # imports all the functions in the os module (operating system 
functions)
cwd = os.getcwd()   # gets the current working directory and places it in the 
variable cwd
dirFiles = open( "dirlist.txt","w")  # creates the file dirlist.txt ready for 
writing using the variable myfiles
# the walk function returns the current directory in root, the directories in 
dirs
# and the files in root in files. By using the for loop it traverses every 
folder
# from the starting folder.
for root, dirs, files in os.walk(cwd):
dirFiles.write(root + "\n")   # writes to dirlist.txt the current directory 
name
for theFiles in files:  # will iterate all the files in the current 
directory
dirFiles.write( "___ " + theFiles + "\n") # writes the filename 
to dirlist.txt. the
dirFiles.close() # Cleanly saves and closes the file dirlist.txt
# Note: the "\n" in the write lines adds the newline character so that the next 
write starts on a newline
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Text Editor With Speech

2008-07-09 Thread FT

Hi!

I am coming closer to the talking editor and voice adjustments inside my
editor/talking module.

When reading the events over and over again I am slowly understanding
who wants what. Inside an editor there are key commands that do certain
things and I try to give some voice to them.

Below I do not use the OnKey function yet, but will erase the comments
and such and only have a say key inside with a toggle on/off for key typing.
Before this was the only event call with keys, now it is only for say key
pressed in the future.

At the moment I use the KEY_UP event to look at what was done by the
editor after the key is released. This allows no need for location
calculations since the move has been made and the final position in most
cases has been done.

So, I moved the values for all line parms over to the OnKey_Up function
so I know where the pointer is at.

I do a word forward and back inside of this function so the word forward
and back are pronounced.

You may replace the speech engine with the pyTTS if you so desire. But I
have not added the method for pitch to there module, so the pitch adjustment
would not work.

I mention this because I have not done a dictionary for the engine, so
some things get pronounced a little different. Like AM for the time does not
come out as A.M. nor am, but likes to take the m out for something else.
Little things like that.

Anyway, this is the latest using events and have removed the button
list. I left the textctrl control methods in the 2 function calls for future
usage and reference.

Enjoy.

Bruce

#Editor.py
import wx
import os
import Sapi5
tts = Sapi5.Create( {"name":"Mary"})
purge = tts._purge
async = tts._async
punc = tts._punc
ID=0
HK=1
KH=2
MK=3
MF=4
MF2=5
DW_ID=1000
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
self.dirname=os.getcwd()  #SEARCH FROM PRESENT DIRECTORY!
self.filename=""
self.items4menu = {"File": [
{ID:102, HK:"&Open", KH:" Open a file to edit", MF:self.OnOpen},
{ID:103, HK:"&Save", KH:" save file to disk", MF:self.OnSave},
{ID:104, HK:"&Edit", KH:" Do editing", MF:self.OnEdit},
{ID:101, HK:"&About", KH:" Information about this program",
MF:self.OnAbout},
{ID:109, HK:"E&xit", KH:" Terminate the program",
MF:self.OnExit}
],  #END OF FILE MENU!
"Voice": [
{ID:202, HK:"&Read", KH:" Open a file to read",
MF:self.OnWav2Read},
{ID:203, HK:"&Save", KH:" save text to audio file",
MF:self.OnSave2Wav},
{ID:204, HK:"Te&xt", KH:" read text field", MF:self.OnRead},
{ID:205, HK:"&Quit", KH:" Stop Reading", MF:self.OnQuitRead}
],  #END OF VOICE MENU!
"Settings": [
{ID:302, HK:"&Speaker", KH:" Name for voice.", MF:self.OnEnter,
MF2:self.OnVoice},
{ID:303, HK:"&Rate", KH:" Rate for voice.", MF:self.OnEnter,
MF2:self.OnVoice},
{ID:304, HK:"&Pitch", KH:" Pitch for voice.", MF:self.OnEnter,
MF2:self.OnVoice},
{ID:305, HK:"&Volume", KH:" Volume for voice.", MF:self.OnEnter,
MF2:self.OnVoice}
],  #END OF SETTINGS MENU!
"Down": [
{ID:DW_ID, HK:"&Down", KH:" Lower Setting.", MF:self.OnEnter,
MF2:self.OnVoice}
]  #END OF DOWN MENU!
}  #END OF ITEMS FOR MENU!
wx.Frame.__init__(self, parent, wx.ID_ANY, title)
self.control = wx.TextCtrl(self, 1, style=wx.TE_MULTILINE)
self.control.Bind( wx.EVT_KEY_UP, self.OnKey_Up) #, self.control)
#self.control.Bind( wx.EVT_CHAR, self.OnKey) #, self.control)
self.CreateStatusBar()  #A Statusbar in the bottom of the window
#Setting up the menu.
filemenu = wx.Menu()
for o in self.items4menu["File"]:
filemenu.Append( o[ID], o[HK], o[KH])
filemenu.AppendSeparator()
voicemenu = wx.Menu()
for o in self.items4menu["Voice"]:
voicemenu.Append( o[ID], o[HK], o[KH])
voicemenu.AppendSeparator()
self.setting_menu = wx.Menu()
for o in self.items4menu["Settings"]:
down_menu = wx.Menu()
down_menu.Append( o[ID], o[HK], o[KH])
d = self.items4menu["Down"][0]
down_menu.Append( d[ID]+o[ID], d[HK], d[KH])
self.setting_menu.AppendMenu( o[ID], o[HK], down_menu)
self.setting_menu.AppendSeparator()
voicemenu.AppendMenu(-1, "&VoiceSettings", self.setting_menu)
# Creating the menubar.
menuBar = wx.MenuBar()
menuBar.Append( filemenu,"&File") # Adding the "filemenu" to the
MenuBar
menuBar.Append( voicemenu,"&Voice") # Adding the "voicemenu" to the
MenuBar
self.SetMenuBar( menuBar)  # Adding the MenuBar to the Frame
content.
self.data4menu = {}
for o in self.items4menu["File"]:
wx.EVT_MENU(self, o[ID], o[MF])
self.data4menu[ o[ID]] = o

Re: [Tutor] How to populate a dictionary

2008-07-17 Thread FT

Dates = {}
def read_Dates (Dates):
if os.path.exists(FILE_NAME):
store = open(FILE_NAME,'r')
for line in store:
name = line.rstrip()
entry = store.next().rstrip()
Dates[name] = entry
store.close()

def save_Dates (Dates):
store = open(FILE_NAME, 'w')
for name,entry in Dates.items():
store.write(name + '\n')
store.write(entry + '\n')
store.close()
print "%s File Saved and Closed!" % FILE_NAME

- Original Message - 
From: [EMAIL PROTECTED] 
To: tutor@python.org 
Sent: Thursday, July 17, 2008 8:07 AM
Subject: [Tutor] How to populate a dictionary


Hello, I am taking python this summer, and have run into a problem.

The assignment is to create a dictionary from a text file:

"12/07/0526 = St Felix IV begins his reign as Catholic Pope"
"12/07/1109 = Crusaders capture Syria's harbor city of Tripoli"
"12/07/1191 = Richard Coeur de Lion and Crusaders defeat Saracens in Palestine"
"12/07/1290 = Jews are expelled from England by order of King Edward I"
"12/07/1442 = King Alfonso V of Arag¢n becomes king of Naples"

"Create a dictionary of dates. Each date you have in there should have a 
special event. An example would be that the dictionary would contain the 
following
NOTE: You must have at least 100 different dates. You can get this from lists 
on the internet if you like, but it must be something real, not just garbage or 
something just made up.
12/28/1929: My Birthday
1/1/1948: New Years Day 48
9/11: the big one




Your program should start by creating an empty dictionary called dates. Then 
your program will get an array of ALL the keys for that dictionary and then 
write a loop that will display all the key/value pairs.
BUT: The dictionary setup file should exist OUTSIDE of the program, you should 
have lines in it that say something like "12/28/1948=Starting Day" or something 
like that. Your strategy will be to open that file, read it, split it into 
lines, then for each line, you will split that line by the equals = sign. The 
left side value is the Key and the Right Hand Side is the value.
You will read this whole files, splitting each key/value pair and store them in 
a dictionary. Then write the loop which will get all the keys, SORT those keys 
and print out the key/value pairs. 

here is a sample of my code:

#!python
myDictionary = { }
inputLines = open ("dates.txt") .read() .split ("\n")
for i in range ( len(inputLines) ) :
if (inputLines [i] != "") :
leftHandSide = inputLines [i].split ("=")
 rightHandSide = inputLines [i].split ("=")
 myDictionary [leftHandSide] = rightHandSide
theKeys = myDictionary.keys ()
theKeys.sort ()
for i in range (len (theKeys) ):
print theKeys[i], myDictionary[ theKeys[i] ]

Can anyone help?







___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor






No virus found in this incoming message.
Checked by AVG. 
Version: 7.5.524 / Virus Database: 270.5.0/1557 - Release Date: 7/17/2008 5:36 
AM
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Writing Python Script to read battery level

2011-01-17 Thread FT

Allan,

Is there a way to read the battery level using Python?

I am totally blind and want to write a script to capture the battery level 
and send it through the voice activeX so I can speak it...

Bruce

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Battery Level Monitoring and Voice

2011-01-19 Thread FT

Hello everyone,

Since I got a simple answer on the Python Win32 web site I decided to post 
it here for those who would want that information, especially those who can not 
see.

The first 2 lines are all that is needed along with the battery level 
instances using that object,
( BatteryPercentage = wmi.InstancesOf('win32_battery'))

This program uses the computer voices and will list them if the specified 
one is not found. In this case I used Karen. When the list is displayed you do 
not need to insert everything in the name, just the obvious part of the name, 
like Karen. Just make sure you spell it correctly or you will always get the 
list printed on the screen.

this also will sound off every minute because of the sleep amounts I use. 
It can also be changed to voice the percentage every percent change, just do 
what you want to do.

Bruce

#BatteryLevel.py
import win32com.client
wmi=win32com.client.GetObject('winmgmts:')
from random import randint, uniform
import msvcrt #INPUT KEYBOARD COMMANDS!
import sys
import time
import pyTTS

#VOICE SETUP!

tts = pyTTS.Create()
purge = pyTTS.tts_purge_before_speak
async = pyTTS.tts_async
PITCH=0
tts.Volume = 100
tts.Rate = 2
VOICECOUNT = len(tts.GetVoiceNames())
VOICES=[]
for v in range( VOICECOUNT):
 VOICES.append( tts.GetVoiceNames()[v])

def setVoice2Name( name):
"SET VOICE BY NAME!"
t=-1
for v in range( VOICECOUNT):
if name in VOICES[ v]:
tts.SetVoiceByName( VOICES[v])
t=v
if t==-1:
tts.Speak( " %d Voices with %s Name Not Found! " % (VOICECOUNT, name))
print " %d Voices with %s Name Not Found! " % (VOICECOUNT, name)
print "Voices:"
for v in range( VOICECOUNT):
print "%d= %s" % (v, VOICES[ v])

def Speak(text, pitch=999):
if pitch==999:
pitch=PITCH
tts.Speak( " %s" % (pitch, text), async, purge)

def SpeakNext(text, pitch=999):
if pitch==999:
pitch=PITCH
tts.Speak( " %s" % (pitch, text), async)

def setRate( rate):
tts.Rate= rate

if __name__ == '__main__':
setVoice2Name( "Karen")
PITCH=3
setRate( 2)
# clear the keyboard buffer
while msvcrt.kbhit():
ch = msvcrt.getch()
ch=""; ch1=""; sch=""
while ch != chr(27) and ch != chr(13):
while msvcrt.kbhit():
ch1 = msvcrt.getch()
ch = ch1
if ch1 == chr(0) or ch1 == chr(224):
ch = msvcrt.getch()
sch = ch1+ch #SAVE ANY MULTIKEYS!
if ch != chr(27) and ch != chr(13):
BatteryPercentage = wmi.InstancesOf('win32_battery')
print (" %d Percent battery charge remaining! " % 
BatteryPercentage[0].EstimatedChargeRemaining)
print "Hay! Battery power is getting low! Plug in the power cord:"
print "Please Press Enter To Exit This Battery Alert!"
SpeakNext(" %d Percent battery charge remaining! " % 
BatteryPercentage[0].EstimatedChargeRemaining)
SpeakNext( "Hay! Battery power is getting low! Plug in the power 
cord:")
SpeakNext( "Please Press Enter To Exit This Battery Alert!")
#time.sleep(10)
c = 0
while c < 30:
if msvcrt.kbhit():
SpeakNext( "Key Was Hit!")
c = 100
time.sleep(1)
else:
time.sleep(2)
c += 1
#if msvcrt.kbhit():
#SpeakNext( "Key Was Hit!")
#time.sleep(1)
#else:
#time.sleep(5)
SpeakNext( "OK, Goodbye!")
time.sleep(2)
#RELEASE VOICE INSTANCE FROM MEMORY!
del tts
sys.exit()

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor