Notice: This forum has been recovered from an old backup, so some content, links, and dates may be outdated. The forum is currently read-only while we restore sign-in and registration functionality. Details

If you find this forum valuable and would like to help keep it online, donations to help cover hosting and domain costs are greatly appreciated, but never expected. You can support the forum through Buy Me a Coffee or Ko-fi. Thank you for helping preserve the EventGhost community.

Parsing global variable

Do you have questions about writing plugins or scripts in Python? Meet the coders here.
Post Reply
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Parsing global variable

Post by nathan323 »

Used EventGhost for a while, though just GUI. I am brand new to python.

I have the following macro set up to show media title in VLC in fullscreen.

Code: Select all

<?xml version="1.0" encoding="UTF-8" ?>
<EventGhost Version="1722">
    <Macro Name="VLC - Show Title  2" Expanded="True">
        <Event Name="vlc_show_title" />
        <Action>
            Window.FindWindow(u'vlc.exe', None, None, None, None, None, False, 0.0, 0)
        </Action>
        <Action>
            TextGrabPlugin.GrabText()
        </Action>
        <Action>
            EventGhost.ShowOSD(u'{eg.globals.grabbedText}', u'0;-48;0;0;0;400;0;0;0;0;3;2;1;34;Arial', (255, 255, 255), None, 6, (0, 0), 0, 2.0, False)
        </Action>
    </Macro>
</EventGhost>
Find Window plugin finds the VLC title bar text.
TextGrab plugin to put the text found into eg.globals.grabbedText
Show OSD plugin flashes it on the screen.

Works well. Only thing is, it obviously shows full title eg. 30 Rock (S01E01) - VLC Media Player.
I want to remove the " - VLC Media Player".

I thought I could either:

1. Insert a Python Script action in between TextGrab and Show OSD, and put python code in that would parse text accordingly

or
2. put more code into Show OSD "Text to display" box - at the moment it just has {eg.globals.grabbedText} - that would parse on the fly.

I have found assorted EG/parsing threads, but none that detail what syntax I could use, and how to do it (plugins etc)

Thanks, Nathan
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
User avatar
kgschlosser
Site Admin
Posts: 5190
Joined: Fri Jun 05, 2015 5:43 am
Location: Rocky Mountains, Colorado USA

Re: Parsing global variable

Post by kgschlosser »

this should do the trick for you.

disable the current macro.

make a new macro with a python script

in the python script put the following code in it

Code: Select all

eg.plugins.Window.FindWindow(u'vlc.exe', None, None, None, None, None, False, 0.0, 0)
eg.plugins.TextGrabPlugin.GrabText()
text = eg.globals.grabbedText.replace(' - VLC Media Player', '')
eg.plugins.EventGhost.ShowOSD(text, u'0;-48;0;0;0;400;0;0;0;0;3;2;1;34;Arial', (255, 255, 255), None, 6, (0, 0), 0, 2.0, False)
then copy the event from the disabled marco into the new macro.

and see if it works
If you like the work I have been doing then feel free to Image
User avatar
kgschlosser
Site Admin
Posts: 5190
Joined: Fri Jun 05, 2015 5:43 am
Location: Rocky Mountains, Colorado USA

Re: Parsing global variable

Post by kgschlosser »

or if you like having all the little icons you can do this


make a new action in that macro for a python command

put this line in the config dialog

Code: Select all

eg.globals.grabbedText = eg.globals.grabbedText.replace(' - VLC Media Player', '')
position the new action between the TextGrab Action and the ShowOSD action
If you like the work I have been doing then feel free to Image
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Excellent!

I do like the little icons, so I went with option 2 :) Thankyou.

But thanks kgschlosser, that really helps get a grasp at what the equivalent python looks like for a macro I'm familiar with, will help to get more comfortable with EG/python.

** for anyone else that wants copy/paste the python command: I misspoke with "VLC Media Player", its VLC media player (lowercase on media player), so it didnt work at first until I realised the script is case-sensitive.
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Ok now I'm getting greedy.

Can I also take out the inevitable ".mp4"? Obviously the problem is, sometimes it's .mkv or .avi - I was thinking something along the lines of:

Code: Select all

eg.globals.grabbedText = eg.globals.grabbedText.replace('.*', '')
that would take out anything after the dot..

I've put this into a second Python Command action, to keep it simple.

I've searched online for the syntax, haven't found anything consistent; a lot talking about regex - do I need a Python Script action instead of command for something more detailed?

The other option I thought would work is to delete 23 characters counting from end of variable - that comprises of ".mp4 - VLC media player" that is an ever-consistent number of characters at the end of every title. Not sure if this is possible, just seems cleanest..
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Ok got it :p

Code: Select all

eg.globals.grabbedText = eg.globals.grabbedText[:-23]
http://stackoverflow.com/questions/5092 ... e-notation
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
User avatar
kgschlosser
Site Admin
Posts: 5190
Joined: Fri Jun 05, 2015 5:43 am
Location: Rocky Mountains, Colorado USA

Re: Parsing global variable

Post by kgschlosser »

ok here i have something i just made up for ya


I think you may like it. :D :twisted:


these lines


LINELENGTH = 50
TRANSPARENCY = 220
FADESTEPS = 50
OSDTIMEOUT = 30
MONITOR = 0
DISPLAYSIZE = 0.60

you can change

LINELENGTH is how long the display text should be. use this is you have text overrun on the OSD. make the number smaller
TRANSPARENCY is how see through the OSD is set this number from 40 to 230 nothing higher or lower
FADESTEPS this all depends on the computer its running on, if things are running slow then shrink the number
OSDTIMEOUT is when the OSD will dissapear, it's in seconds.
MONITOR is for a multi-monitor setup. 0 being the default for a single monitor
DISPLAYSIZE this is a decimal representation of the % of the screen you want to cover so the 0.60 will cover 60% of the screen (on that monitor)


copy and paste the code below into a python script. you will have to get rid of everything in the macro except the event and the TextGrabber. and both of those have to be located before the script.

there seems to be one glitch. i have to poke around and see if i can find it. but it's when the menu goes to shutdown on occasion it will throw an exception. one time i had the osd get stuck on. not sure what is causing it and why it's so random

i will add other features like being able to change the colors but this is a nice start.

Code: Select all

LINELENGTH = 50
TRANSPARENCY = 220
FADESTEPS = 50
OSDTIMEOUT = 30
MONITOR = 0
DISPLAYSIZE = 0.60

ERROR_REASON = (
    "We failed to reach a server.\n"
    "Reason: %s"
)

ERROR_CODE = (
    "The server couldn't fulfill the request.\n"
    "Error code: %d"
)

URL = 'http://www.omdbapi.com/?t='

KEYS = [
    'Title',
    'Released',
    'Season',
    'Episode',
    'Runtime',
    'Plot'
]

import wx
import urllib2
from urllib2 import HTTPError, URLError
from ast import literal_eval
from PIL import Image
from time import sleep
from eg.WinApi.Utils import GetMonitorDimensions


class ScrapedOSD(wx.Frame):
    def __init__(self, osdtext, poster):
        
        self.fontInfo = '0;-41;0;0;0;700;255;0;0;0;3;2;1;82;Lucoda Handwriting'
        self.ProcessFont()
        print osdtext
        xPos, yPos, xSize, ySize = self.GetDimensions()
        poster = Image.open(urllib2.urlopen(poster)).resize((xSize, ySize), Image.ANTIALIAS)
                
        print xSize, ySize
        
        image = wx.EmptyImage(poster.size[0], poster.size[1])
        image.SetData(poster.convert("RGB").tobytes())
        image.SetAlphaData(poster.convert("RGBA").tobytes()[3::4])
        
        self.poster = wx.BitmapFromImage(image)
        self.osdtext = osdtext
        
        wx.Frame.__init__(
            self,
            parent=None,
            size=(xSize, ySize),
            pos=(xPos, yPos),
            style = wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.NO_BORDER,
        )
        self.fadeinvalue = 0
        self.fadeoutvalue = TRANSPARENCY
        
        self.menutimer = wx.Timer(self)
        self.fadeintimer = wx.Timer(self)
        self.fadeouttimer = wx.Timer(self)
        
        self.Bind(wx.EVT_TIMER, self.OnTimer, self.menutimer)
        self.Bind(wx.EVT_TIMER, self.OnFadeIn, self.fadeintimer)
        self.Bind(wx.EVT_TIMER, self.OnFadeOut, self.fadeouttimer)
        
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        
        wx.CallAfter(self.FadeIn, TRANSPARENCY)
        wx.CallAfter(self.menutimer.Start, OSDTIMEOUT * 1000)
        self.Show()
    
    def GetDimensions(self):
        
        try:
            screen = GetMonitorDimensions()[MONITOR]
        except IndexError:
            screen = GetMonitorDimensions()[0]
        xpos, ypos, xmon, ymon = screen
        
        xsize = int(float(xmon) * DISPLAYSIZE)
        ysize = int(float(ymon - 90) * DISPLAYSIZE)
        
        xpos += (xmon - xsize) / 2
        ypos += (ymon - ysize) / 2
        
        return xpos, ypos, xsize, ysize
    
    def OnPaint(self, evt):
        bmp = self.poster
        xPos, yPos, xSize, ySize = self.GetDimensions()
        #bmp = wx.EmptyBitmap(xSize, ySize)
        
        
        dc = wx.MemoryDC()
        dc.SelectObject(bmp)
        dc = wx.GCDC(dc)
        dc.SetFont(self.font)
        
        dc.SetBrush(wx.Brush(wx.Colour(0, 0, 0, TRANSPARENCY - 30)))
        dc.SetPen(wx.Pen(wx.Colour(255, 0, 0, TRANSPARENCY - 30), 3))
        dc.DrawRoundedRectangle(25, 25, xSize-50, ySize-50, 5)
        
        dc.SetTextForeground(wx.Colour(0, 255, 0, 225))
        print self.osdtext
        dc.DrawText(self.osdtext, 45, 45)
        
        pdc = wx.PaintDC(self)
        pdc.DrawBitmap(bmp, 0, 0)
        
    def ProcessFont(self): 
        self.font = wx.Font(18, wx.FONTFAMILY_TELETYPE,wx.NORMAL,wx.BOLD, faceName="Arial")
        nativeFontInfo = wx.NativeFontInfo()
        nativeFontInfo.FromString(self.fontInfo)
        self.font.SetNativeFontInfo(nativeFontInfo)
        
    def OnEraseBackground(self, event):
        pass # do nothing to avoid flicker
    
    def OnTimer(self, evt):
        self.menutimer.Stop()
        wx.CallAfter(self.FadeOut, TRANSPARENCY)
        evt.Skip()
    
    def OnClose(self, dummyEvent):
        def stop(t):
            try:
                t.Stop()
            except:
                pass
        
        stop(self.menutimer)
        stop(self.fadeouttimer)
        stop(self.fadeintimer)
        self.Show(False)
        self.Destroy()
    
    def OnFadeIn(self, evt):
        self.FadeIn()
        evt.Skip()
    
    def OnFadeOut(self, evt):
        self.FadeOut()
        evt.Skip()
    
    def FadeOut(self, fadeoutsteps=None):
        if fadeoutsteps is not None:
            self.fadeoutincrement = TRANSPARENCY / fadeoutsteps
            wx.CallAfter(self.fadeouttimer.Start, 1)
        else:
            self.fadeoutvalue -= self.fadeoutincrement
            if self.fadeoutvalue < 0:
                self.fadeoutvalue = 0
                self.fadeouttimer.Stop()
                wx.CallAfter(self.OnClose, None)
            self.SetTransparent(self.fadeoutvalue)
    
    def FadeIn(self, fadeinsteps=None):
        if fadeinsteps is not None:
            self.fadeinincrement = TRANSPARENCY / fadeinsteps
            wx.CallAfter(self.fadeintimer.Start, 1)
        else:
            self.fadeinvalue += self.fadeinincrement
            if self.fadeinvalue > TRANSPARENCY:
                self.fadeinvalue = TRANSPARENCY
                self.fadeintimer.Stop()
            self.SetTransparent(self.fadeinvalue)


def Scrape():
    try:
        response = urllib2.urlopen(URL)
    except HTTPError as httpError:
        eg.PrintError(ERROR_REASON % httpError.reason)
        eg.PrintError(ERROR_CODE % httpError.code)
    except URLError as urlError:
        eg.PrintError(ERROR_REASON % urlError.reason)
    else:
        return literal_eval(response.read())


text = eg.globals.grabbedText.split('(')
title = text[0].split('.')[0].replace(' ', '%20')
URL += title

try:
    episodedata = text[1].split(')')[0]
    episodedata = episodedata.upper()[1:].split('E')
    URL += '&Season=%d&Episode=%d' % (int(episodedata[0]), int(episodedata[1]))
except IndexError:
    pass

URL += '&y=&plot=full&r=json'

data = Scrape()
if data is not None:
    print data
    text = 'Title: %s\n' % title.replace('%20', ' ')
    for key in KEYS:
        try:
            scrapedata = list(data[key])
            if len(scrapedata) > LINELENGTH:
                for i in range(LINELENGTH, len(scrapedata), LINELENGTH):
                    scrapedata.insert(i, '\n')
            else:
                scrapedata.append('\n')
            if 'Season' in data:
                if key == 'Title':
                    key = 'Episode Title'
            text += '%s: %s' % (key, ''.join(scrapedata))
        except KeyError:
            pass
        
    ScrapedOSD(text, data['Poster'])
If you like the work I have been doing then feel free to Image
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Ah excellent, thanks! I'd added something in python that further edited the title down to hide episode code, then inserted the text into the clipboard on my phone, so I could paste into iMDB app haha.
Yours is great for some quick info. Although the OSD doesn't seem to be working, I can only see plot, runtime, etc. in the Event Log (with the little blue info bubble icons).

Here is the log:

Code: Select all

Traceback (most recent call last):
 Python script "2", line 223, in <module>
  ScrapedOSD(text, data['Poster'])
 Python script "2", line 45, in __init__
  poster = Image.open(urllib2.urlopen(poster)).resize((xSize, ySize), Image.ANTIALIAS)
 File "PIL\Image.pyc", line 1964, in open
AttributeError: addinfourl instance has no attribute 'seek'
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
User avatar
kgschlosser
Site Admin
Posts: 5190
Joined: Fri Jun 05, 2015 5:43 am
Location: Rocky Mountains, Colorado USA

Re: Parsing global variable

Post by kgschlosser »

i need to know what the title of the movie/show you are trying to watch is.

and i will put in some exception handling to deal with that error. and to post up a just OSD

what this script does is this
osd.jpg
Now any time there is scraping involved there is bound to be some problems. so try it with a different movie and i will work on doing some exception handling to deal with no data issues


but this also goes and grabs the movie poster and shows it.

i am going to add 3 separate transparency values. one for the poster, one for the box overlay, and the 3rd for the text. maybe i should just make a plugin for this. so that any data can be passed into it and it will bring up an osd, that might be the way to go to have some nice dialogs for the settings and what have you
If you like the work I have been doing then feel free to Image
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Great, sounds awesome 8)

Ive tried it with files with titles like

The Departed, Birdman, The Wire (S02E04) - Hard Cases

and mkv, mp4, avi
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
User avatar
kgschlosser
Site Admin
Posts: 5190
Joined: Fri Jun 05, 2015 5:43 am
Location: Rocky Mountains, Colorado USA

Re: Parsing global variable

Post by kgschlosser »

If you could add a

Code: Select all

print eg.globals.grabbedText
At the beginning of the script and run it again. And then copy and paste what is printed in the event log. That would be most helpful. The service the script is using for the data I am not to sure about the completeness of information. But it is the only one that doesnt require you to use a. API key and doesn't have a limit on the number of queries. I am sure I can get an API key for IMDB. But I think MyMovies is the better. And the quality of the poster is kinda crappy from that other site. I need to add something that will maintain a ratio on resize. And check the number of lines of data and times it by the average height of the text. So it can either add a scroll and same goes for the width. It's just more code and the complexity jumps up a bit. And i really do hate writing code in the Python script editor. I have to get my version up and running.
If you like the work I have been doing then feel free to Image
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Code: Select all

2016-10-20 17:20:08  MACRO: VLC - Show Title (forum)
2016-10-20 17:20:08     ACTION: Find Window: vlc.exe
2016-10-20 17:20:08     ACTION: TextGrab: GrabText
2016-10-20 17:20:08        INFO: Text grabbed: The Departed.mkv - VLC media player
2016-10-20 17:20:08     ACTION: Python Script
2016-10-20 17:20:08        INFO: The Departed.mkv - VLC media player
2016-10-20 17:20:08        INFO: {'Plot': "In South Boston, the state police force is waging war on Irish-American organized crime. Young undercover cop Billy Costigan (Leonardo DiCaprio) is assigned to infiltrate the mob syndicate run by gangland chief Frank Costello (Jack Nicholson). While Billy quickly gains Costello's confidence, Colin Sullivan (Matt Damon), a hardened young criminal who has infiltrated the state police as an informer for the syndicate is rising to a position of power in the Special Investigation Unit. Each man becomes deeply consumed by their double lives, gathering information about the plans and counter-plans of the operations they have penetrated. But when it becomes clear to both the mob and the police that there is a mole in their midst, Billy and Colin are suddenly in danger of being caught and exposed to the enemy - and each must race to uncover the identity of the other man in time to save themselves. But is either willing to turn on their friends and comrades they've made during their long stints undercover?", 'Rated': 'R', 'Response': 'True', 'Language': 'English, Cantonese', 'Title': 'The Departed', 'Country': 'USA, Hong Kong', 'Writer': 'William Monahan (screenplay), Alan Mak, Felix Chong', 'Metascore': '86', 'imdbRating': '8.5', 'Director': 'Martin Scorsese', 'Released': '06 Oct 2006', 'Actors': 'Leonardo DiCaprio, Matt Damon, Jack Nicholson, Mark Wahlberg', 'Year': '2006', 'Genre': 'Crime, Drama, Thriller', 'Awards': 'Won 4 Oscars. Another 90 wins & 123 nominations.', 'Runtime': '151 min', 'Type': 'movie', 'Poster': 'https://images-na.ssl-images-amazon.com/images/M/MV5BMTI1MTY2OTIxNV5BMl5BanBnXkFtZTYwNjQ4NjY3._V1_SX300.jpg', 'imdbVotes': '885,411', 'imdbID': 'tt0407887'}
2016-10-20 17:20:08        INFO: Title: The Departed
2016-10-20 17:20:08        INFO: Title: The Departed
2016-10-20 17:20:08        INFO: Released: 06 Oct 2006
2016-10-20 17:20:08        INFO: Runtime: 151 min
2016-10-20 17:20:08        INFO: Plot: In South Boston, the state police force is waging
2016-10-20 17:20:08        INFO: war on Irish-American organized crime. Young unde
2016-10-20 17:20:08        INFO: rcover cop Billy Costigan (Leonardo DiCaprio) is
2016-10-20 17:20:08        INFO: assigned to infiltrate the mob syndicate run by g
2016-10-20 17:20:08        INFO: angland chief Frank Costello (Jack Nicholson). Wh
2016-10-20 17:20:08        INFO: ile Billy quickly gains Costello's confidence, Co
2016-10-20 17:20:08        INFO: lin Sullivan (Matt Damon), a hardened young crimi
2016-10-20 17:20:08        INFO: nal who has infiltrated the state police as an in
2016-10-20 17:20:08        INFO: former for the syndicate is rising to a position
2016-10-20 17:20:08        INFO: of power in the Special Investigation Unit. Each
2016-10-20 17:20:08        INFO: man becomes deeply consumed by their double lives
2016-10-20 17:20:08        INFO: , gathering information about the plans and count
2016-10-20 17:20:08        INFO: er-plans of the operations they have penetrated.
2016-10-20 17:20:08        INFO: But when it becomes clear to both the mob and the
2016-10-20 17:20:08        INFO: police that there is a mole in their midst, Bill
2016-10-20 17:20:08        INFO: y and Colin are suddenly in danger of being caugh
2016-10-20 17:20:08        INFO: t and exposed to the enemy - and each must race t
2016-10-20 17:20:08        INFO: o uncover the identity of the other man in time t
2016-10-20 17:20:08        INFO: o save themselves. But is either willing to turn
2016-10-20 17:20:08        INFO: on their friends and comrades they've made during
2016-10-20 17:20:08        INFO: their long stints undercover?
2016-10-20 17:20:08        ERROR: Traceback (most recent call last):
2016-10-20 17:20:08        ERROR: Python script "3", line 225, in <module>
2016-10-20 17:20:08        ERROR: ScrapedOSD(text, data['Poster'])
2016-10-20 17:20:08        ERROR: Python script "3", line 47, in __init__
2016-10-20 17:20:08        ERROR: poster = Image.open(urllib2.urlopen(poster)).resize((xSize, ySize), Image.ANTIALIAS)
2016-10-20 17:20:08        ERROR: File "PIL\Image.pyc", line 1964, in open
2016-10-20 17:20:08        ERROR: AttributeError: addinfourl instance has no attribute 'seek'
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
User avatar
kgschlosser
Site Admin
Posts: 5190
Joined: Fri Jun 05, 2015 5:43 am
Location: Rocky Mountains, Colorado USA

Re: Parsing global variable

Post by kgschlosser »

i do not know what it is that you posted. none of that appears to have anything to do with the script i made. it seems as though it has been altered in some fashion. and i do not know what the reference to addinfourl is.
If you like the work I have been doing then feel free to Image
nathan323
Posts: 9
Joined: Fri Aug 05, 2016 4:19 am

Re: Parsing global variable

Post by nathan323 »

Ok thats weird huh.

Here is what I get from copying the macro I have:

Code: Select all

<?xml version="1.0" encoding="UTF-8" ?>
<EventGhost Version="1722">
    <Macro Name="VLC - Show Title (forum)" Expanded="True">
        <Event Name="vlc_show_title_forum" />
        <Action>
            Window.FindWindow(u'vlc.exe', None, None, None, None, None, False, 0.0, 0)
        </Action>
        <Action>
            TextGrabPlugin.GrabText()
        </Action>
        <Action>
            EventGhost.PythonScript(u'print eg.globals.grabbedText\n\nLINELENGTH = 50\nTRANSPARENCY = 220\nFADESTEPS = 50\nOSDTIMEOUT = 30\nMONITOR = 0\nDISPLAYSIZE = 0.60\n\nERROR_REASON = (\n    "We failed to reach a server.\\n"\n    "Reason: %s"\n)\n\nERROR_CODE = (\n    "The server couldn\'t fulfill the request.\\n"\n    "Error code: %d"\n)\n\nURL = \'http://www.omdbapi.com/?t=\'\n\nKEYS = [\n    \'Title\',\n    \'Released\',\n    \'Season\',\n    \'Episode\',\n    \'Runtime\',\n    \'Plot\'\n]\n\nimport wx\nimport urllib2\nfrom urllib2 import HTTPError, URLError\nfrom ast import literal_eval\nfrom PIL import Image\nfrom time import sleep\nfrom eg.WinApi.Utils import GetMonitorDimensions\n\n\nclass ScrapedOSD(wx.Frame):\n    def __init__(self, osdtext, poster):\n        \n        self.fontInfo = \'0;-41;0;0;0;700;255;0;0;0;3;2;1;82;Lucoda Handwriting\'\n        self.ProcessFont()\n        print osdtext\n        xPos, yPos, xSize, ySize = self.GetDimensions()\n        poster = Image.open(urllib2.urlopen(poster)).resize((xSize, ySize), Image.ANTIALIAS)\n                \n        print xSize, ySize\n        \n        image = wx.EmptyImage(poster.size[0], poster.size[1])\n        image.SetData(poster.convert("RGB").tobytes())\n        image.SetAlphaData(poster.convert("RGBA").tobytes()[3::4])\n        \n        self.poster = wx.BitmapFromImage(image)\n        self.osdtext = osdtext\n        \n        wx.Frame.__init__(\n            self,\n            parent=None,\n            size=(xSize, ySize),\n            pos=(xPos, yPos),\n            style = wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.NO_BORDER,\n        )\n        self.fadeinvalue = 0\n        self.fadeoutvalue = TRANSPARENCY\n        \n        self.menutimer = wx.Timer(self)\n        self.fadeintimer = wx.Timer(self)\n        self.fadeouttimer = wx.Timer(self)\n        \n        self.Bind(wx.EVT_TIMER, self.OnTimer, self.menutimer)\n        self.Bind(wx.EVT_TIMER, self.OnFadeIn, self.fadeintimer)\n        self.Bind(wx.EVT_TIMER, self.OnFadeOut, self.fadeouttimer)\n        \n        self.Bind(wx.EVT_CLOSE, self.OnClose)\n        self.Bind(wx.EVT_PAINT, self.OnPaint)\n        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\n        \n        wx.CallAfter(self.FadeIn, TRANSPARENCY)\n        wx.CallAfter(self.menutimer.Start, OSDTIMEOUT * 1000)\n        self.Show()\n    \n    def GetDimensions(self):\n        \n        try:\n            screen = GetMonitorDimensions()[MONITOR]\n        except IndexError:\n            screen = GetMonitorDimensions()[0]\n        xpos, ypos, xmon, ymon = screen\n        \n        xsize = int(float(xmon) * DISPLAYSIZE)\n        ysize = int(float(ymon - 90) * DISPLAYSIZE)\n        \n        xpos += (xmon - xsize) / 2\n        ypos += (ymon - ysize) / 2\n        \n        return xpos, ypos, xsize, ysize\n    \n    def OnPaint(self, evt):\n        bmp = self.poster\n        xPos, yPos, xSize, ySize = self.GetDimensions()\n        #bmp = wx.EmptyBitmap(xSize, ySize)\n        \n        \n        dc = wx.MemoryDC()\n        dc.SelectObject(bmp)\n        dc = wx.GCDC(dc)\n        dc.SetFont(self.font)\n        \n        dc.SetBrush(wx.Brush(wx.Colour(0, 0, 0, TRANSPARENCY - 30)))\n        dc.SetPen(wx.Pen(wx.Colour(255, 0, 0, TRANSPARENCY - 30), 3))\n        dc.DrawRoundedRectangle(25, 25, xSize-50, ySize-50, 5)\n        \n        dc.SetTextForeground(wx.Colour(0, 255, 0, 225))\n        print self.osdtext\n        dc.DrawText(self.osdtext, 45, 45)\n        \n        pdc = wx.PaintDC(self)\n        pdc.DrawBitmap(bmp, 0, 0)\n        \n    def ProcessFont(self): \n        self.font = wx.Font(18, wx.FONTFAMILY_TELETYPE,wx.NORMAL,wx.BOLD, faceName="Arial")\n        nativeFontInfo = wx.NativeFontInfo()\n        nativeFontInfo.FromString(self.fontInfo)\n        self.font.SetNativeFontInfo(nativeFontInfo)\n        \n    def OnEraseBackground(self, event):\n        pass # do nothing to avoid flicker\n    \n    def OnTimer(self, evt):\n        self.menutimer.Stop()\n        wx.CallAfter(self.FadeOut, TRANSPARENCY)\n        evt.Skip()\n    \n    def OnClose(self, dummyEvent):\n        def stop(t):\n            try:\n                t.Stop()\n            except:\n                pass\n        \n        stop(self.menutimer)\n        stop(self.fadeouttimer)\n        stop(self.fadeintimer)\n        self.Show(False)\n        self.Destroy()\n    \n    def OnFadeIn(self, evt):\n        self.FadeIn()\n        evt.Skip()\n    \n    def OnFadeOut(self, evt):\n        self.FadeOut()\n        evt.Skip()\n    \n    def FadeOut(self, fadeoutsteps=None):\n        if fadeoutsteps is not None:\n            self.fadeoutincrement = TRANSPARENCY / fadeoutsteps\n            wx.CallAfter(self.fadeouttimer.Start, 1)\n        else:\n            self.fadeoutvalue -= self.fadeoutincrement\n            if self.fadeoutvalue < 0:\n                self.fadeoutvalue = 0\n                self.fadeouttimer.Stop()\n                wx.CallAfter(self.OnClose, None)\n            self.SetTransparent(self.fadeoutvalue)\n    \n    def FadeIn(self, fadeinsteps=None):\n        if fadeinsteps is not None:\n            self.fadeinincrement = TRANSPARENCY / fadeinsteps\n            wx.CallAfter(self.fadeintimer.Start, 1)\n        else:\n            self.fadeinvalue += self.fadeinincrement\n            if self.fadeinvalue > TRANSPARENCY:\n                self.fadeinvalue = TRANSPARENCY\n                self.fadeintimer.Stop()\n            self.SetTransparent(self.fadeinvalue)\n\n\ndef Scrape():\n    try:\n        response = urllib2.urlopen(URL)\n    except HTTPError as httpError:\n        eg.PrintError(ERROR_REASON % httpError.reason)\n        eg.PrintError(ERROR_CODE % httpError.code)\n    except URLError as urlError:\n        eg.PrintError(ERROR_REASON % urlError.reason)\n    else:\n        return literal_eval(response.read())\n\n\ntext = eg.globals.grabbedText.split(\'(\')\ntitle = text[0].split(\'.\')[0].replace(\' \', \'%20\')\nURL += title\n\ntry:\n    episodedata = text[1].split(\')\')[0]\n    episodedata = episodedata.upper()[1:].split(\'E\')\n    URL += \'&Season=%d&Episode=%d\' % (int(episodedata[0]), int(episodedata[1]))\nexcept IndexError:\n    pass\n\nURL += \'&y=&plot=full&r=json\'\n\ndata = Scrape()\nif data is not None:\n    print data\n    text = \'Title: %s\\n\' % title.replace(\'%20\', \' \')\n    for key in KEYS:\n        try:\n            scrapedata = list(data[key])\n            if len(scrapedata) > LINELENGTH:\n                for i in range(LINELENGTH, len(scrapedata), LINELENGTH):\n                    scrapedata.insert(i, \'\\n\')\n            else:\n                scrapedata.append(\'\\n\')\n            if \'Season\' in data:\n                if key == \'Title\':\n                    key = \'Episode Title\'\n            text += \'%s: %s\' % (key, \'\'.join(scrapedata))\n        except KeyError:\n            pass\n        \n    ScrapedOSD(text, data[\'Poster\'])')
        </Action>
    </Macro>
</EventGhost>
Here is a screenshot of EG after running macro:

Image

EDIT: Well that didnt work. Here is Google Drive link: https://drive.google.com/open?id=0BxzKi ... GJMdHh6Wnc
Program Version: 0.4.1.r1722
Build Time: Wed, 03 Feb 2016 08:20:52
Python Version: Stackless Python 2.6.5 final 0
wxPython Version: 2.8.12.1

Windows 7 Home Premium SP1, 64-bit (build 7601)
CPU: Intel(R) Core(TM) i5 CPU 750 @ 2.67GHz
RAM: 4091 MB
Post Reply