I was interested in coding a long time. So this year I got a job where I was supposed to scrape text from old event programs. The pictures where terrible quality and results with normal OCR where horrible. I checked the google vision api and tested it manually and the results where great, so I used this opportunity to learn about coding.( I did some python before but the lack of usefulness always drove me away).
I wrote this program, I know its walking on crouches but it worked and did exactly what I wanted for 3 months now. I dont use it regularly but today when I wanted to use it again, it didnt work any more it just jumps to the end of the program, and finishes without making the api requests, at least so it seems to me.
I am really mostly finished with my work and this request doesnt make sense in terms of efficiency but I am just curious why the program I created suddenly stopped working.
If somebody can hint me in the right direction I would highly appreciate it, also if somebody wants to use the program, if it works for them sure let it work instead of yourself :D
I am not sure but I am using linux mint and maybe it stopped working because of some updates of python or vision-api or something.
# coding=utf-8
from google.cloud import vision
import os
import io
import sys
reload(sys)
sys.setdefaultencoding('utf8')
directory = "/home/weareone/Documents/programming/test/here"
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="/home/weareone/Documents/programming/test/key.json"
def workinghard(page):
client = vision.ImageAnnotatorClient()
#file_name = os.path.join( os.path.dirname(__file__), page) # Loads the image into memory
#page_er = os.path.abspath(os.path.join(os.path.dirname(page))) <--- my improvisation
with io.open( page, 'rb') as image_file: # after io.open.(file_name <---exchanged with "page")
content = image_file.read()
request = {
"image": {
"content": content
},
"features": [
{
"type": "DOCUMENT_TEXT_DETECTION"
}
]
}
response = client.annotate_image(request)
storage = response.full_text_annotation.text
return storage
def listdirs(folder):
return [
d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder))
if os.path.isdir(d)
]
directories = listdirs(directory)
for year in directories:
logtxt = open(year + ".txt", "w+" )
for root, dirs, files in os.walk(year):
files.sort()
for file23 in files:
if file23.endswith('.jpg'):
pathparent = os.path.join(year,file23)
logtxt.write(workinghard(pathparent))
logtxt.write("-------------------------------------------------------------------------")
print(pathparent)
logtxt.close()
print("DONE")
Thank you very much dear internet
EDIT: I solved it by changing this line the statement apaprently equaled to FALSE.
if file23.endswith('.JPG'):
Related
I am making a text based video game with python, and I need a way to change the cursor type from inside python. Here is my code:
from os import system,getenv
from json import loads,dumps
import uuid
apd = getenv("LOCALAPPDATA")
pf = loads(open(rf"{apd}\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json").read())
pf['profiles']['list'].append({"guid":str(uuid.uuid4()),'name':"Game","commandline": "C:\\Windows\\System32\\cmd.exe","cursorShape": "vintage","font": {"face": "Consolas"},})
open(rf"{apd}\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json",'w').write(dumps(pf))
system('wt -F -d {{PATH TO FILE}} -p "Game" --title Game python game.py')
I'm not sure it's a great idea to place a dependency on Windows Terminal, but if you do go that route, the right way to do this is via the JSON fragment extension feature.
Don't risk modifying the user's Windows Terminal settings file directly via Python. Users will be quite (rightly) upset if you muck up their settings if something goes wrong.
JSON fragment extensions give you the ability to create a separate settings fragment that only applies to your application/profile.
For example, create a fragment:
{
"profiles": [
{
"name": "My Game",
"commandline": "python.exe /path/to/game.py",
"cursorShape": "vintage",
"font": {"face": "Consolas"}
}
]
}
Place this file in either:
C:\ProgramData\Microsoft\Windows Terminal\Fragments\{app-name}\{file-name}.json: For all users on the system
C:\Users\<user>\AppData\Local\Microsoft\Windows Terminal\Fragments\{app-name}\{file-name}.json: For only the current user
Here's some simple code for pycatia [PYCATIA site download],
but it seems to be seen not working in my computer.
it looks like File load is totally sucessful.
but all product/cgr is not activated,
becaused of "Do not activate default shapes on open" option in my catia.
Though 'activate_terminal_node' code is commanded, it doen't work properly.
and please let me know how to use 'add_components_from_files' method
thanks in advance
from pycatia import catia
from pycatia.enumeration.enumeration_types import cat_work_mode_type
from pycatia.product_structure_interfaces.product import Product
caa = catia()
documents = caa.documents
documents.open(r'D:\CATIA\test.CATProduct')
document = caa.active_document
product = document.product()
product.apply_work_mode(cat_work_mode_type.index("DESIGN_MODE"))
Product.activate_terminal_node(product.get_products())
Pretty new to APIs and Python for that matter. I am need to grab images from Scryfall using their API. Here is the link to the API documentation. https://scryfall.com/docs/api
They are using json and the code looks like this. (https://api.scryfall.com/cards/cn2/78?format=json&pretty=true)
This is the part that contains the URIs to the images.
"image_uris": {
"small": "https://img.scryfall.com/cards/small/en/cn2/78.jpg?1517813031",
"normal": "https://img.scryfall.com/cards/normal/en/cn2/78.jpg?1517813031",
"large": "https://img.scryfall.com/cards/large/en/cn2/78.jpg?1517813031",
"png": "https://img.scryfall.com/cards/png/en/cn2/78.png?1517813031",
"art_crop": "https://img.scryfall.com/cards/art_crop/en/cn2/78.jpg?1517813031",
"border_crop": "https://img.scryfall.com/cards/border_crop/en/cn2/78.jpg?1517813031"
},
How would I grab the images at those URIs and download them?
I found this on github but I'm not really sure where to begin with it.
https://github.com/NandaScott/Scrython
I am using the "Default Cards" file on this page
https://scryfall.com/docs/api/bulk-data
You need to download the image data and save it locally. Step 1, getting the image data using Python:
import requests as req
img_uris = {
"small": "https://img.scryfall.com/cards/small/en/cn2/78.jpg?1517813031",
"normal": "https://img.scryfall.com/cards/normal/en/cn2/78.jpg?1517813031",
"large": "https://img.scryfall.com/cards/large/en/cn2/78.jpg?1517813031",
"png": "https://img.scryfall.com/cards/png/en/cn2/78.png?1517813031",
"art_crop": "https://img.scryfall.com/cards/art_crop/en/cn2/78.jpg?1517813031",
"border_crop": "https://img.scryfall.com/cards/border_crop/en/cn2/78.jpg?1517813031"
}
img_request = req.get(img_uris['normal'])
# Always test your response obj before performing any work!
img_request.raise_for_status()
The function raise_for_status() will raise whatever exception requests had while making the request. If nothing happens, that means we received a 200 response code indicating our request was good! Now step 2, saving the data:
import os
img_file = "queen_marchesa_norm.jpg"
with open(os.path.join(os.getcwd(), img_file), 'w') as f:
f.write(img_request.content)
Here we declare a filename, use that filename to make a writeable file object, and then write all the data from our img_request to our file object. If you want to learn more about requests check the documentation.
My Script downloads a zipfile, exctracts the relevant parts replaced files and folders etc. It used to work flawlessly, for some reason its has now decided to stop working and only partly downloads the zipfile, and of course, as the zipfile is incomplete I get an error, saying the downloaded file is not a zipfile. my script is as follows.
def downloadupdate():
xbmcgui.Dialog().ok(
"[B][COLOR white]Daily Updater[/B][/COLOR]",
"Favourites and some software will now update",
"Elements of your system will be cleaned",
"Daily Update will take at most 2 minutes")
#ONLY HAVE THE SUPER FAVOURITES FOLDER IN THE ZIPFILE!!
url = 'http://x.com/x/x/Super Favourites.zip'
destination = xbmc.translatePath('special://home/userdata/addon_data/iupdatefix/Super Favourites.zip')
favzip = urllib.urlopen(url)
xbmc.executebuiltin("Notification(Downloading new updates, PLEASE WAIT,()")
with open(xbmc.translatePath('special://home/userdata/addon_data/iupdatefix/Super Favourites.zip'), "wb") as zipFile:
zipFile.write(favzip.read())
xbmc.executebuiltin("Notification(Download Complete, Please wait,()")
time.sleep(5)
xbmc.executebuiltin("Notification(Updating Click and Play channels, Please wait,()")
updatezip = xbmc.translatePath('special://home/userdata/addon_data/iupdatefix/Super Favourites.zip')
extractupdate = xbmc.translatePath('special://home/userdata/addon_data/plugin.program.super.favourites/')
oldfav = xbmc.translatePath('special://home/userdata/addon_data/plugin.program.super.favourites/Super Favourites')
yeszip = os.path.exists(updatezip)
time.sleep(5)
if yeszip:
xbmc.executebuiltin("Notification(Removing previous, Please wait,()")
shutil.rmtree(oldfav, ignore_errors=False)
xbmc.executebuiltin("Notification(Updating, now,()")
gh = open(updatezip, 'rb')
zp = zipfile.ZipFile(gh)
zp.extractall(extractupdate)
gh.close()
time.sleep(3)
xbmc.executebuiltin("Notification(updated, Now Checking sd,()")
# put this command at the end of whole script --->>>os.remove(updatezip)
else:
xbmc.executebuiltin("Notification(Update file Corrupt, Please try again,()")
The problem has been solved, It was not the code. It was the hosting service, I had to reset the File permissions on the server and after that all works perfectly again.
I need to use SSML to play an audio file with the tag in my Alexa Skill (as per Amazon's instructions).
Problem is, I don't know how to use SSML with Python. I know I can use it with Java but I want to build my skills with Python. I've looked all over, but haven't found any working examples of SSML in a Python script/program - does anyone know?
This was asked two years ago but maybe someone will benefit from the below.
I've just checked and if you use Alexa Skills Kit SDK for Python you can simply add SSML to your response, for example:
#sb.request_handler(can_handle_func=is_request_type("LaunchRequest"))
def launch_request_handler(handler_input):
speech_text = "Wait for it 3 seconds<break time="3s"/> Buuuu!"
return handler_input.response_builder.speak(speech_text).response
Hope this helps.
SSML audio resides in the response.outputSpeech.ssml attribute. Here is an
example obj with other required parameters removed:
{
"response": {
"outputSpeech": {
"type": "SSML",
"ssml": "<speak>
Welcome to Car-Fu.
<audio src="https://carfu.com/audio/carfu-welcome.mp3" />
You can order a ride, or request a fare estimate. Which will it be?
</speak>"
}
}
Further reference:
JSON Interface Reference for Custom Skills
Speech Synthesis Markup Language (SSML) Reference
Install ssml-builder "pip install ssml-builder", and use it:
from ssml_builder.core import Speech
speech = Speech()
speech.add_text('sample text')
ssml = speech.speak()
print(ssml)
These comments really helped a lot in figuring out how to make SSML works using the ask-sdk-python. Instead of
speech_text = "Wait for it 3 seconds<break time="3s"/> Buuuu!" - from wmatt's comment
I defined variables that represents the start and end of every tags that I'm using
ssml_start = '<speak>'
speech_text = ssml_start + whispered_s + "Here are the latest alerts from MMDA" + whispered_e
using single quotes and concatenate those strings to the speech output and it worked! Thanks a lot guys! I appreciate it a lot!
This question was somewhat vague, however I did manage to figure out how to incorporate SSML into a Python script. Here's a snippet that plays some audio:
if 'Item' in intent['slots']:
chosen_item = intent['slots']['Item']['value']
session_attributes = create_attributes(chosen_item)
speech_output = '<speak> Here is something to play' + \
chosen_item + \
'<audio src="https://s3.amazonaws.com/example/example.mp3" /> </speak>'
The ssml package for python exists.
you can install like below by pip
$ pip install pyssml
or
$ pip3 install pyssml
so example is link below
http://blog.naver.com/chandong83/221145083125
sorry. it is korean.
# -*- coding: utf-8 -*-
# for amazon
import re
import os
import sys
import time
from boto3 import client
from botocore.exceptions import BotoCoreError, ClientError
import vlc
from pyssml.PySSML import PySSML
# amazon service fuction
# if isSSML is True, SSML format
# else Text format
def aws_polly(text, isSSML = False):
voiceid = 'Joanna'
try:
polly = client("polly", region_name="ap-northeast-2")
if isSSML:
textType = 'ssml'
else:
textType = 'text'
response = polly.synthesize_speech(
TextType=textType,
Text=text,
OutputFormat="mp3",
VoiceId=voiceid)
# get Audio Stream (mp3 format)
stream = response.get("AudioStream")
# save the audio Stream File
with open('aws_test_tts.mp3', 'wb') as f:
data = stream.read()
f.write(data)
# VLC play audio
# non block
p = vlc.MediaPlayer('./aws_test_tts.mp3')
p.play()
except ( BotoCoreError, ClientError) as err:
print(str(err))
if __name__ == '__main__':
# normal pyssml
#s = PySSML()
# amazon speech ssml
s = AmazonSpeech()
# normal
s.say('i am normal')
# speed is very slow
s.prosody({'rate':"x-slow"}, 'i am very slow')
# volume is very loud
s.prosody({'volume':'x-loud'}, 'my voice is very loud')
# take a one sec
s.pause('1s')
# pitch is very high
s.prosody({'pitch':'x-high'}, 'my tone is very high')
# amazone
s.whisper('i am whispering')
# print to convert to ssml format
print(s.ssml())
# request aws polly and play
aws_polly(s.ssml(), True)
# Wait while playback.
time.sleep(50)