Unicode to Kruti Dev 010 - python

How to convert unicode to Kruti Dev 010?
I'm using python speech recognition library to convert speech to text and
displaying it using tkinter Text widget but it's not displaying in Kruti Dev.
# class variable
__thisTextArea = Text(__root)
Font_tuple = font.Font(family='Kruti Dev 010', size=16)
# inside constructor
self.__thisTextArea.config(font = self.Font_tuple, yscrollcommand=self.__thisScrollBar.set)
# inside speech recognition function
self.__thisTextArea.insert(INSERT, text_obtained)
self.__thisTextArea.insert(END,' ')
Also, on saving the file speech recognized text is not saving however typed text is saving.
KrutiDev to Unicode Converter.

I'm not familiar enough with either tkinter or devanagari to tell whether this is at all helpful, but I found another project with a pair of functions which map both ways; is this what you are looking for?
The code at https://github.com/jmcmanu2/python_practice/blob/master/Unicode%20KrutiDev%20converter.py doesn't have an explicit license, so I am not comfortable publishing it here, but I have a slightly updated version for Python 3 in a gist at https://gist.github.com/tripleee/b82a79f5b3e57dc6a487ae45077cdbd3 for the time being. (The original was almost Python 3 already so the tweaking required was minimal, though I ripped out unrelated parts which dealt with Excel files.)
With that code available as an import, does this do what you are asking?
from unicode2krutidev import Unicode_to_KrutiDev
# ...
class something:
__thisTextArea = Text(__root)
Font_tuple = font.Font(family='Kruti Dev 010', size=16)
def __init__(self, ...):
# ...
self.__thisTextArea.config(font = self.Font_tuple, yscrollcommand=self.__thisScrollBar.set)
# ...
def recognize_speech(self, ...):
# ...
text_converted = Unicode_to_KrutiDev(text_obtained)
self.__thisTextArea.insert(INSERT, text_converted)
self.__thisTextArea.insert(END,' ')
# ...
self.save_to_database(text_obtained)

Related

Can python-docx add a picture that is a link to an external image file?

I am using the python-docx library ( https://python-docx.readthedocs.io/ ) to write a Word document.
Embed a picture
I can add a picture that is embedded in the document, using the API of the python-docx library. For example:
from docx import Document
doc = Document()
par = doc.add_paragraph( 'Embed picture:' )
run = par.add_run()
run.add_picture( 'puppy.png' )
doc.save( 'test.docx' )
The picture becomes an ImagePart that is stored within the document:
word/
media/
image1.png
And the Relationship that points to that Image part is:
<Relationships ...>
...
<Relationship Id="rId4" Type=".../image" Target="media/image1.png"/>
Link a picture
I would prefer to add a picture that links to an external image file. This is something that you can do within Microsoft Word. The python-docx library does not have a convenient API for that. However, some of the underlying code seems to have support for linking to an external file
Therefore, I started my own utility function to link a picture to an external file. For example:
from docx import Document
doc = Document()
par = doc.add_paragraph( 'Link picture:' )
run = par.add_run()
Util.Run_add_picture( run, 'puppy.png', is_external = True )
doc.save( 'test.docx' )
Which would lead to the Relationship for the picture being something like the following:
<Relationships ...>
...
<Relationship Id="rId4" Type=".../image" Target="file:///C:\work\puppy.png" TargetMode="External"/>
I was encouraged that some of the underlying code seems to have support for linking to an external file. For example, docx.opc.part.Part.relate_to() has an is_external parameter that defaults to false. It seemed reasonable to invent my own utility wrappers for Run.add_picture(), and the functions that calls, so that I could pass along an is_external parameter with a value of true.
For another example, docx.oxml.shape.CT_Blip has embed and link properties, and if you assign the relationship ID to the latter instead of the former, that should percolate into other places and generate the desired markup in the document. It seemed reasonable to invent a utility wrapper for docx.oxml.shape.CT_Picture.new(), and the functions that call it, so that I could pass along an is_external parameter with a value of true, and then do something like the following:
#staticmethod
def CT_Picture_new( pic_id, filename, relationship_id, cx, cy, is_external ):
pic = parse_xml( CT_Picture._pic_xml() )
pic.nvPicPr.cNvPr.id = pic_id
pic.nvPicPr.cNvPr.name = filename
# The important change that pays attention to given is_external parameter.
if is_external:
pic.blipFill.blip.link = relationship_id
else:
pic.blipFill.blip.embed = relationship_id
pic.spPr.cx = cx
pic.spPr.cy = cy
return pic
So far, I have utility functions that take the place of, and provide a way to specify an is_external parameter, for:
docx.text.run.Run.add_picture()
docx.parts.story.BaseStoryPart.new_pic_inline()
docx.parts.story.BaseStoryPart.get_or_add_image()
docx.oxml.shape.CT_Inline.new_pic_inline()
docx.oxml.shape.CT_Picture.new()
Too many rabbit holes
Alas, I still get an exception when I save the document.
TypeError: Argument must be bytes or unicode, got 'ImagePart'
I think the next thing that I must change is how a Relationship object is populated; the target_ref property needs to be assigned just a sting path to the external image file, not an ImagePart object.
I must give up for awhile. Are there any plans to support linking a picture to an external image file? Or, a simpler workaround?

How to reuse completions from PathCompleter in prompt_toolkit

I am creating a REPL tool for my project that (simplified for clarity) either directly executes entered commands or (if a command ".x some/path/to/file" is entered) reads and executes them from file. My question is related to auto-completing the user input (using prompt_toolkit).
I have something like (minimum executable example):
import prompt_toolkit
from prompt_toolkit.completion import Completer, Completion
from prompt_toolkit.document import Document
from prompt_toolkit.contrib.completers import PathCompleter
class CommandCompleter(Completer):
def __init__(self):
self.path_completer = PathCompleter()
self.commands = [".x", "command1", "command2"]
def get_completions(self, document, complete_event):
if document.text.startswith(".x "):
sub_doc = Document(document.text[3:])
yield from (Completion(cmd.text, -document.cursor_position)
# ???????? ?????????????????????????
for cmd
in self.path_completer.get_completions(sub_doc, complete_event))
# ???????
else:
yield from (Completion(cmd, -document.cursor_position)
for cmd in self.commands
if cmd.startswith(document.text))
if __name__ == "__main__":
while True:
other_args = {}
input = prompt_toolkit.prompt(">>> ", completer=CommandCompleter(), **other_args)
# Do something with input (omitted)
The second if-branch (for commands) works correctly but I don't know how to properly call the PathCompleter.get_completions() method and reconstruct the Completion objects from its result (where the ???'s are) in the first branch. The trick is that I am using the completion only for a part of the input and various sub-stringing, position calculations etc. did not (yet) lead to the satisfactory behaviour (i.e. offering the paths and constructing the correct input line).
I will definitely go on searching but if anyone knows how to rewrite this, it would be very useful.
Note: yield from self.path_completer.get_completions(document, complete_event) would be used if the whole input would be just the path (and this works correctly).
Probably the following should fix it:
sub_doc = Document(document.text[3:])
yield from (Completion(completion.text, completion.start_position, display=completion.display)
for completion
in self.path_completer.get_completions(sub_doc, complete_event))
completion.text contains the text that is going to be inserted;
completion.start_position contains the place where the text is going to be inserted, relative to the cursor position (in this particular example we can take the value from the nested completer).
completion.display is the value displayed in the pop-up menu. (In this case, the whole filename, rather than only the inserted string.
Feel free to open a GitHub issue if you have any more questions.

python dragonfly to recognize similar words

I am doing a program with dragon fly using wsr,where it has to analyse a word,any voice matching that word should output 'yes it matches'
If i say 'czechoslovakia' then it must print true even for all the similar matches of this world ,like words for 'circle slovakia, cat on slavia,seko vakia...'
What specific methods,should i use for this?
My program
from dragonfly.all import *
import pythoncom
import time
# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
spec = "czechoslovakia|circle slovalia|sceko bakia|cat on ania" # Spoken form of command.
def _process_recognition(self, node, extras): # Callback when command is spoken.
print "Voice command spoken."
# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar") # Create a grammar to contain the command rule.
grammar.add_rule(ExampleRule()) # Add the command rule to the grammar.
grammar.load() # Load the grammar.
while True:
pythoncom.PumpWaitingMessages()
time.sleep(.1)
There is nothing built into Dragonfly to allow you to do this, but you have some other options.
If you're looking to dynamically generate the spec, you might want
to look at Fuzzy. You could give it a word and use it to generate
other similar sounding words from that word. Then you could create
the spec from them.
Here is the WSR engine class in Dragonfly.
I don't know much about SAPI5, but you might be able to ask it for
alternatives. If you can, you might be able to extend the
Dragonfly GrammarWrapper to expose the alternatives, and then use a
catchall grammar to save all utterances and then filter out what you
want (possibly using Fuzzy).
If you were using Natlink, I would recommend
looking at the results object. As you can see here, the results
object has access to all of Dragon's different hypotheses for what
you said in a given utterance. Just as with my second suggestion,
you could catch everything and then filter what you wanted:
.
from natlinkutils import GrammarBase
class CatchAll(GrammarBase):
# this spec will catch everything
gramSpec = """
<start> exported = {emptyList};
"""
def initialize(self):
self.load(self.gramSpec, allResults=1)
self.activateAll()
def gotResultsObject(self, recogType, resObj):
for x in range(0, 100):
try:
possible_interpretation = resObj.getWords(x)
# do whatever sort of filtering you want here
except Exception:
break
c = CatchAll()
c.initialize()
def unload():
global c
if c:
c.unload()
c = None

Python: binary string error simulation

I am currently writing a test for validating some error-correcting code:
inputData1 = "1001011011"
inputData2 = "1001111011"
fingerPrint1 = parityCheck.getParityFingerprint(inputData1)
# Expected: fingerPrint1=0
fingerPrint2 = parityCheck.getParityFingerprint(inputData2)
# Expected: fingerPrint2=1
if fingerPrint1 == fingerPrint2:
print "Test failed: errorCorrectingAlgo1 failed to detect error"
else:
print "Test success: errorCorrectingAlgo1 successfully detected error"
Is there a python class I can use to automatically generate error(burst error, single event, reordering, etc) on a binary string? Eg:
inputData1 = "1001011011"
inputData1BurstError = applyBurstError(inputData1) # Eg: inputData1BurstError =
("1011111011", or "1001000000", or etc.)
inputData1RandomError = applyRandomError(inputData1)# Eg: inputData1RandomError =
("0001101011", or "0111101101", or etc.)
inputData1Reordering = applyReordering(inputData1) # Eg: inputData1Reordering =
("0101110011", or "1101101001", or etc.)
inputData1SingleEvent = applySingleEvent(inputData1)# Eg: inputData1SingleEvent =
("1001011011", or "1000011011", or etc.)
I know that such a class could be easily implementable for binary check validation. However, I need a more complete class to test more complex error detecting code such as CRC. I have already used Netem (http://www.linuxfoundation.org/collaborate/workgroups/networking/netem) in the past to modify packets entering and leaving interfaces in a telecom lab. However, I doubt Netem would be a good solution to my problem this time as my whole test is planned to be run on my desktop computer only. Also, I am working on Windows 7 this time. Moreover, Netem does not provide a complete/complex enough set of functions for my test implementation.
Any help/suggestion would be greatly appreciated.
Thanks!
Related question: How to shuffle a list with Gaussian distribution

Python: Networked IDLE/Redo IDLE front-end while using the same back-end?

Is there any existing web app that lets multiple users work with an interactive IDLE type session at once?
Something like:
IDLE 2.6.4
Morgan: >>> letters = list("abcdefg")
Morgan: >>> # now, how would you iterate over letters?
Jack: >>> for char in letters:
print "char %s" % char
char a
char b
char c
char d
char e
char f
char g
Morgan: >>> # nice nice
If not, I would like to create one. Is there some module I can use that simulates an interactive session? I'd want an interface like this:
def class InteractiveSession():
''' An interactive Python session '''
def putLine(line):
''' Evaluates line '''
pass
def outputLines():
''' A list of all lines that have been output by the session '''
pass
def currentVars():
''' A dictionary of currently defined variables and their values '''
pass
(Although that last function would be more of an extra feature.)
To formulate my problem another way: I'd like to create a new front end for IDLE. How can I do this?
UPDATE: Or maybe I can simulate IDLE through eval()?
UPDATE 2: What if I did something like this:
I already have a simple GAE Python chat app set up, that allows users to sign in, make chat rooms, and chat with each other.
Instead of just saving incoming messages to the datastore, I could do something like this:
def putLine(line, user, chat_room):
''' Evaluates line for the session used by chat_room '''
# get the interactive session for this chat room
curr_vars = InteractiveSession.objects.where("chatRoom = %s" % chat_room).get()
result = eval(prepared_line, curr_vars.state, {})
curr_vars.state = curr_globals
curr_vars.lines.append((user, line))
if result:
curr_vars.lines.append(('SELF', result.__str__()))
curr_vars.put()
The InteractiveSession model:
def class InteractiveSession(db.Model):
# a dictionary mapping variables to values
# it looks like GAE doesn't actually have a dictionary field, so what would be best to use here?
state = db.DictionaryProperty()
# a transcript of the session
#
# a list of tuples of the form (user, line_entered)
#
# looks something like:
#
# [('Morgan', '# hello'),
# ('Jack', 'x = []'),
# ('Morgan', 'x.append(1)'),
# ('Jack', 'x'),
# ('SELF', '[1]')]
lines = db.ListProperty()
Could this work, or am I way off/this approach is infeasible/I'm duplicating work when I should use something already built?
UPDATE 3: Also, assuming I get everything else working, I'd like syntax highlighting. Ideally, I'd have some API or service I could use that would parse the code and style it appropriately.
for c in "characters":
would become:
<span class="keyword">for</span> <span class="var">c</span> <span class="keyword">in</span> <span class="string>"characters"</span><span class="punctuation">:</span>
Is there a good existing Python tool to do this?
I could implement something like this pretty quickly in Nevow. Obviously, access would need to be pretty restricted since doing something like this involves allowing access to a Python console to someone via HTTP.
What I'd do is create an Athena widget for the console, that used an instance of a custom subclass of code.InteractiveInterpreter that is common to all users logged in.
UPDATE: Okay, so you have something chat-like in GAE. If you just submit lines to a code.InteractiveInterpreter subclass that looks like this, it should work for you. Note that the interface is pretty similar to the InteractiveSession class you describe:
class SharedConsole(code.InteractiveInterpreter):
def __init__(self):
self.users = []
def write(self, data):
# broadcast output to connected clients here
for user in self.users:
user.addOutput(data)
class ConnectedUser(object):
def __init__(self, sharedConsole):
self.sharedConsole = sharedConsole
sharedConsole.users.append(self) # reference look, should use weak refs
def addOutput(self, data):
pass # do GAE magic to send data to connected client
# this is a hook for submitted code lines; call it from GAE when a user submits code
def gotCommand(self, command):
needsMore = self.sharedConsole.runsource(command)
if needsMore:
pass # tell the client to change the command line to a textarea
# or otherwise add more lines of code to complete the statement
The closest Python interpreter I know of to what you are looking for, in terms of interface, is DreamPie. It has separate input and output areas, much like a chat interface. Also, DreamPie runs all of the code in a subprocess. DreamPie also does completion and syntax coloring, much like IDLE, which means it doesn't just pipe input and output to/from the subprocess -- it has implemented the abstractions which you are looking for.
If you wish to develop a desktop application (not a web-app), I recommend basing your work on DreamPie and just adding the multiple-frontend functionality.
Update: For syntax highlighting (including HTML) see the Pygments project. But that is a completely different question; please ask one question at a time here.
As a proof of concept, you may be able to put something together using sockets and a command-line session.
this is likely possible with the upcoming implimentation of IPython using a 0MQ backend.
I would use ipython and screen. With this method, you would have to create a shared login, but you could both connect to the shared screen session. One downside would be that you would both appear as the same user.

Categories

Resources