Jump to content

xilopaint

Member
  • Posts

    896
  • Joined

  • Last visited

  • Days Won

    24

Posts posted by xilopaint

  1. Sorry if it's a dumb question. I am a beginner.
     
    I have tried to convert this Python script for PDF compression into an Alfred workflow. It relies on pdftops from Poppler and ps2pdf from Ghostscript. I have installed both Poppler and Ghostscript using Homebrew on Terminal. Since that, the script is fully functional on Terminal but I didn't manage to convert the code to an Alfred workflow using Alfred-Workflow helper library. It seems Alfred misses the Poppler library.

     

    This is my attempt:
    #!/usr/bin/python
    # encoding: utf-8
    
    from __future__ import division
    import sys
    import argparse
    import tempfile
    import subprocess
    import os
    import shutil
    import contextlib
    from workflow import Workflow
    
    def main(wf):
     
        query = wf.args[0]
        argv = query
    
        def main(argv=None):
    
            parser = argparse.ArgumentParser(description="one weird PDF trick")
            parser.add_argument('before', nargs=1, help="PDF (before)",
                                type=extant_file)
            parser.add_argument('after', nargs="?", help="PDF (after)")
            parser.add_argument('-t', '--tempdir', help="needs a lot of temp space", required=False)
    
            if argv is None:
                argv = parser.parse_args()
    
            if argv.tempdir:
                tempfile.tempdir = argv.tempdir
    
            if not which('pdftops'):   # use poppler to create a .ps
                raise Exception("need pdftops from poppler")
            if not which('ps2pdf'):    # and use ghostscript to create a .pdf
                raise Exception("need ps2pdf from ghostscript")
    
            with make_temp_directory(prefix='popgho') as tempdir:
                main_with_temp(tempdir, argv)
    
        def main_with_temp(tempdir, argv):
            os.environ.update({'TMPDIR': tempdir})  # for ghostscript
            postscript = os.path.join(tempdir, 'poppler.ps')
            o_pdf = argv.before[0]
            n_pdf = os.path.join(tempdir, 'ghost.pdf')
    
            with open(os.devnull, "w") as f:
                subprocess.check_call(['pdftops', o_pdf, postscript],
                                      stdout=f, stderr=f)
                subprocess.check_call(['ps2pdf', postscript, n_pdf],
                                      stdout=f, stderr=f, env=os.environ)
    
            o_size = os.path.getsize(o_pdf)
            n_size = os.path.getsize(n_pdf)
            compression_ratio = o_size/n_size
    
            if (argv.after):
                shutil.move(n_pdf, argv.after)
                print("compression: {1}; created: {0}"
                      .format(argv.after, compression_ratio))
            elif (compression_ratio > 1.2):
                shutil.move(n_pdf, o_pdf)
                print("compression: {1}; overwrite: {0}"
                      .format(o_pdf, compression_ratio))
            else:
                os.remove(n_pdf)
                print("compression: {0}; not worth it, deleted new file"
                      .format(compression_ratio))
            os.remove(postscript)
    
        def which(program):
    
            def is_exe(fpath):
                return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
    
            fpath, fname = os.path.split(program)
    
            if fpath:
                if is_exe(program):
                    return program
    
            else:
                for path in os.environ["PATH"].split(os.pathsep):
                    path = path.strip('"')
                    exe_file = os.path.join(path, program)
                    if is_exe(exe_file):
                        return exe_file
    
            return None
    
        def extant_file(x):
    
            if not os.path.exists(x):
                    raise argparse.ArgumentError("{0} does not exist".format(x))
            return x
    
        @contextlib.contextmanager
    
        def make_temp_directory(prefix):
    
            temp_dir = tempfile.mkdtemp(prefix=prefix)
            yield temp_dir
            shutil.rmtree(temp_dir)
    
        if __name__ == "__main__":
            sys.exit(main())
    
    if __name__ == '__main__':
    
        wf = Workflow()
        sys.exit(wf.run(main))
    
    

    Alfred Console:

     

    [2016-06-29 20:32:20][trigger.action] Processing output of 'action.script' with arg '(

        "/Users/usuario/Desktop/test.pdf"
    )'
    [2016-06-29 20:32:21][ERROR: action.script] 20:32:21 workflow.py:2157 DEBUG    Workflow version : 1.0.0
    20:32:21 workflow.py:2175 ERROR    need pdftops from poppler
    Traceback (most recent call last):
      File "/Users/usuario/Library/Application Support/Alfred 3/Alfred.alfredpreferences/workflows/user.workflow.C3709BD1-8479-4079-B9BB-559C4B577012/workflow/workflow.py", line 2168, in run
        func(self)
      File "pdftrick.py", line 110, in main
        sys.exit(main())
      File "pdftrick.py", line 34, in main
        raise Exception("need pdftops from poppler")
    Exception: need pdftops from poppler
    20:32:21 workflow.py:2195 DEBUG    Workflow finished in 0.043 seconds.
  2. Using the same suggestion as in the thread you're referring to, could you check what Airmail 3 is named as? If it's not exclusively called "Airmail", try renaming it, which seems to have resolved the issue for those who were using "Airmail Beta" in that thread.

     

    Having said that, it's likely we'll add support for Airmail 3 once it's confirmed that it has the same AppleScript support as previous versions of it :)

     

     

    Renaming the app has solved the issue for me using Airmail 3. Please, add a reference on change log when the Airmail 3 support come out.

  3. Try deleting the config file. It should be somewhere like ~/Library/Application Support/Alfred 2/Workflow Data/com.spr.translate.api/config.ini.

     

    Then re-enter the api key and try again. More than likely there is a null value for the first item. I'll change the code for BR soon.

     

     

    Nothing has changed and the null value persists. :(

  4. Try adding a new API key to the Google project and then plugging that one in.

     

     

    Still not working.

     

    By the way, why the first result has no flag or language? Look:

    xPzgQ3m.png

    P.S.: Notice, as I already pointed out in this thread, that the code for Brazilian Portuguese is wrong (pt-BZ instead pt-BR).

  5. The 403 error is happening because Google is denying you access to the translation.

     

    Read through the (short) introduction and then follow the setup instructions here: https://cloud.google.com/translate/v2/getting_started.

     

    After that, set the API key correctly in the workflow.

     

     

    I can't understand what's going on. I used this workflow some time ago with the paid API and decided to stop until the multiple langue support was released. Now the workflow no longer works. :(

  6. Starting debug for 'Translate API'

     
    [sTDERR: alfred.workflow.input.scriptfilter] [15:21:51][filter.php:122][ERROR] Request completely failed, and no cached data exists. cURL debug information follows:
    [15:21:51][filter.php:122][ERROR] cURL error number: 22
    [15:21:51][filter.php:122][ERROR] cURL error message: `The requested URL returned error: 403 Forbidden`.
    [15:21:52][filter.php:122][ERROR] Request completely failed, and no cached data exists. cURL debug information follows:
    [15:21:52][filter.php:122][ERROR] cURL error number: 22
    [15:21:52][filter.php:122][ERROR] cURL error message: `The requested URL returned error: 403 Forbidden`.
    [15:21:52][filter.php:122][ERROR] Request completely failed, and no cached data exists. cURL debug information follows:
    [15:21:52][filter.php:122][ERROR] cURL error number: 22
    [15:21:52][filter.php:122][ERROR] cURL error message: `The requested URL returned error: 403 Forbidden`.
    [15:21:53][filter.php:122][ERROR] Request completely failed, and no cached data exists. cURL debug information follows:
    [15:21:53][filter.php:122][ERROR] cURL error number: 22
    [15:21:53][filter.php:122][ERROR] cURL error message: `The requested URL returned error: 403 Forbidden`.
  7. The workflow with the official API is no longer working for me:

     

    [sTDERR: alfred.workflow.input.scriptfilter] [09:56:21][filter.php:86][ERROR] Request completely failed, and no cached data exists. cURL debug information follows:

    [09:56:21][filter.php:86][ERROR] cURL error number: 22

    [09:56:21][filter.php:86][ERROR] cURL error message: `The requested URL returned error: 403 Forbidden`.

  8. My advice is that you get away from AppleScript as soon as you can. It’s only useful to interact with some OS X and a loathsome language at every other level.

    For the most part, it doesn’t really matter what language you learn programming concepts in, but AppleScript is really an exception, there. It is so different (in a bad way) from other languages, what you learn there can be hard to transpose to others. Add to that the fact it’s so limiting, you shouldn’t be wasting your time with it. Pick any other popular scripting language (ruby, python, even bash) and try that, falling back to AppleScript only when necessary.

    Now that we’ve got that out of the way, you don’t need to understand deanishe’s code, just the connections. Simply connect your Script Filter into Copy to Clipboard. Make sure the latter consists of just {query}. Now, whatever you pass as the arg in your Script Filter will be what’s passed into the next stage of the workflow (i.e. it will be copied to the clipboard, in this case).

     

     

    Thank you for the advice. In fact, I started from AppleScript because of its similarity with natural english. For a beginner it's easier to understand.

     

    Regarding my question, I still can't get the point. I had already connected the Script Filter into Copy to Clipboard but the text copied to clipboard is not the result returned by my script filter (the address) but the typed argument (the zip code).

  9. Though the question was directed at deanishe, I’m answering as reply to this tweet.

    Yes, it’s possible to pass Script Filter results into Copy to CLipboard. Look at deanishe’s own Glosbe translation workflow that does exactly that.

     

     

    Sorry Vítor. Maybe I should had point out that I am still a beginner on coding and can only understand AppleScript at the moment.

     

    Could you offer a more detailed answer for AppleScript language?

  10. That's exactly how Alfred works. It just uses {query} throughout (rather than {input} and {output}).

     

    As far as running scripts is concerned, any output to STDOUT is treated as the input to the following action (i.e. the following action's {query}).

     

    The exceptions are Run NSAppleScript (where you use q for input and return for output as described above) and Script Filters, which must output XML to STDOUT.

     

     

    Hello deanishe. I have a dumb question and don't know if it's already answered in this thread.

     

    I have created a workflow that uses a script filter which searches a web API by a zip code and returns the matching address. Look:

     

    L3XOvxa.png

     

    Is it possible to pass the workflow results to a Copy to Clipboard output?

  11. Some file sharing services like CloudApp or Droplr have hard restrictions on their free plans like tiny file size limits or mandatory expiration time. These limitations made me migrate to Jumpshare, a powerful file sharing service with a generous free plan that includes:

    • 2GB total free space, 250MB max filesize, no auto-self-destructing files;
    • Supports multiple files and folder uploads;
    • Preview over 200 file formats online without installing any software;
    • Real-time sharing: recipients can see upload progress; once uploading finishes, they can view the file right away;
    • Share via email directly from the app (with advanced options);
    • Expire links after x number of days, views or downloads;
    • Disable download so recipient can only preview the files;
    • Powerful In-depth Analytics dashboard;
    • Track shared files;
    • Collections and nested folders;
    • Jumpshare Inbox (allow anyone to send you files without signing up for an account).

    Before moving to Jumpshare I used to use the nice CloudApp workflow by Carlos-Sz, so after the migration I created the following workflow which works in a similar manner.

     

    ___________________________________________________

     

     

    Description

     

    Upload files and folders to Jumpshare.

     

    Requirements

    • Jumpshare installed
    • OS X 10.9 or later
    • 64-bit processor

     

    Usage

     

    Jumpshare workflow can be used by the following actions:

    • Enter the keyword jmp without any argument to upload the selected items.
    • Enter the keyword jmp with some argument to rename and upload the selected items.
    • Select one or more items in Alfred and enter the file action Upload to Jumpshare.
    • Select one or more items in Finder and enter a custom hotkey to upload them.

     

    Credits

     

    This workflow is partly based on CloudApp Workflow by Carlos-Sz and uses qWorkflow Library by Ursan Razvan.

     

    Download from Packal

  12. Great works!

     

    I discover Alfred (today), and your workflow!

    It's very impressive ;-)

     

    I'm French, and I just want to know if it's possible to use french preferences with google?

    When I try with a keyword, there are somme differences in the results: I think it's due to language preferences.

     

    I red all the post, but my english is not very good to understand, and I never try the "terminal"...

    Is it possible?

     

    Thanks, have a nice day.

     

     

    The workflow author has not been around. Maybe you want to take a look at Searchio! workflow for auto-suggestion from multiple search engines in your language.

×
×
  • Create New...