I have written code to compress image in .py file and tried to compile using transcrypt to convert to JS file. During this process i got the below error(screen shot) But if i run the .py file separately using IDE ,it works fine & compress the image.
Code:
import PIL
from PIL import Image as pil
class FileUpload:
def Images (self,arg):
# Open the image
im = pil.open(arg)
# Now save it
im.save("img_compressed.jpg", format="JPEG", quality=90)
fileupload = FileUpload()
Error :
\python src\imgcompress>python -m transcrypt -b -m -n imageCompress.py
Transcrypt (TM) Python to JavaScript Small Sane Subset Transpiler Version 3.6.101
Copyright (C) Geatec Engineering. License: Apache 2.0
Error while compiling (offending file last):
File '/python src/imgcompress/imageCompress.py', line 1, at import of:
File '/python/lib/site-packages/PIL/__init__.py', line 14, namely:
Can't import module 'PIL'
Aborted
screen shot
The following JS library for example is suitable to compress images before uploading:
https://github.com/brunobar79/J-I-C
Any JS library can be used directly from Transcrypt, so there are many alternatives. Main point is: look for a JS rather than a Python lib. Just Google for
javascript image compression browser
Transcrypt was deliberately made to live in the JS ecosystem.
http://www.transcrypt.org/docs/html/what_why.html#the-ecosystem-different-batteries
To compress without using a library at all, see e.g.
How to compress an image via Javascript in the browser?
Note that you can embed any JS code unmodified with:
http://www.transcrypt.org/docs/html/special_facilities.html#inserting-literal-javascript-pragma-js-and-include
but this is rarely necessary, you can use the trick above directly from Transcrypt, just convert to Python syntax. All DOM functions are available.
Transcrypt cannot use C extension libraries, only pure-Python libraries. That's why they reimplemented part of the Numpy API as Numscrypt instead of just using Numpy.
There are some pure-Python libraries that have similar functionality to Pillow, like pymaging, but I don't know if any of them have the functionality, speed, or robustness you need; you'd have to try them out for yourself.
If you're not running it in the browser, it can also use Node.js packages, and there are Node packages for dealing with image files. I doubt any of them will be an exact drop-in replacement for Pillow, but if you just want basic functionality, it should be pretty easy to write a try/except that imports whichever is available and defines a couple wrappers.
If you are running in the browser… well, then you don't have access to the filesystem, which rules out a lot of PIL functionality off the bat… but on the other hand, you've got native image objects from the DOM.
Related
How does one compile/process typescript files (that import typescript and/or javascript files) to JavaScript files that can be run in modern JavaScript runtimes that support JavaScript modules (such as Chrom(e|ium)s) and Deno).
Reasoning(s)
"TypeScript is a programming language that's a superset of JavaScript"
Modules / importing is a feature in most programming languages (including TypeScript) for reason(s) X. It is now also a feature in JavaScript (since ~2017) for reason(s) X.
JavaScript - as a syntax and as an API that can at least do math, concatenate strings, solve code golf problems, etc. - can be run by several engines such as Node, Deno, Bun, Chrom(e|ium)s, etc.
JavaScript modules is/can be a solution for all of those runtimes to import other JavaScript code because it doesn't make any assumptions about what JavaScript runtime is used or how paths are resolved.
TypeScript is already compiled to JavaScript so that it can be run in e.g. Node environments.
The JavaScript module standard uses URL / file paths because I want the concept of URLs and file paths to be universal. The concept goes as such: point to an exact resource using an identifier string and that same resource can also be identified and utilized by a variety of other tools using the same identifier (including file browsers and web browsers).
I do not identify as a robot whose job it is to change all the ".ts" import lines (but only the correct ones) to ".js". A typescript compiler is uniquely suited for the job because it has already resolved the typescript files that have been referenced and already know that it's compiling them to JavaScript and has already chosen paths to output the resulting JavaScript files to (likely with a .js extension nonetheless).
One should not "simply import the .js file" in typescript, ̶b̶e̶c̶a̶u̶s̶e̶ ̶t̶h̶e̶ ̶J̶a̶v̶a̶S̶c̶r̶i̶p̶t̶ ̶f̶i̶l̶e̶ ̶d̶o̶e̶s̶n̶'̶t̶ ̶y̶e̶t̶ ̶e̶x̶i̶s̶t̶ ̶u̶s̶i̶n̶g̶ ̶t̶h̶e̶ ̶c̶o̶n̶c̶e̶p̶t̶ ̶o̶f̶ ̶f̶i̶l̶e̶ ̶p̶a̶t̶h̶s̶.̶ Edit: #jsejcksn is right: "code that's written uses the conventions of the compiler, not the conventions of the runtime engine"
One should not "leave the import extension blank" in typescript (for example, let's say import * as foo from './foo';), because resolving the import to runnable code using magic requires querying the environment, which isn't something that the W3C/WHATWG has standardized over the web. In the example, do we mean to import the resource ./foo.ts? If so, how does one convey that they wish to import the existing file ./foo?
If one uses a bundler to bundle modules together (such as "webpack" or "deno-bundle") then the modules cannot be used as modules.
"Write once, run anywhere" (WORA) is a sentiment. Many developers seem to desire this to be a reality. Billions of dollars have been spent on this concept.
I've tried using the "tsc" command (because a lot of websites seem to reccommend it and thus far is the closest utility I've discovered), but it doesn't correct the import lines. For example:
If there exists a valid typescript file located at ./baz.ts, and another file located at ./foo.ts that contains the following code...
import * as baz from './baz.ts';
and I run the "tsc" command on both files (./foo.ts and ./baz.ts), the resulting ./foo.js incorrectly contains...
import * as baz from './baz.ts';
But this throws an error in JavaScript runtimes that support JavaScript modules but not TypeScript. I desire to compile these two files from typescript to working JavaScript.
It doesn't matter what the extensions (or even paths) are, as long as the typescript files contain working typescript code that imports other modules (written in typescript if you desire) and the compiled/processed JavaScript modules contain working JavaScript code that imports other working modules (written in JavaScript - not TypeScript) because that's what a transpiler does.
Thank you.
I have read Google's documentation and a number of similar questions, and am not having any success adapting the answers to my issue. I am working with Google App Engine in a Node.js Standard Environment and already have much of my app working and correctly configured.
Now I am trying to use npm modules as library code for BOTH my server-side app, and a client-side javascript app I am serving as a static directory. For this example, consider the widely used jquery module, of course available in npm
I believe the issue is in my app.yaml file, distilled to the part relevant to this question:
handlers:
### THIS ROUTE IS NOT WORKING
- url: /client/shared/lib/jquery\.js$
static_files: node_modules/jquery/dist/jquery.js
upload: node_modules/jquery/dist/jquery\.js$
mime_type: text/javascript
### CLIENT-SIDE STATIC ROUTES ARE WORKING
- url: /client/shared
static_dir: shared
- url: /client.*$
static_dir: client
- url: /.*$
redirect_http_response_code: 301
script: auto
Of course, I have already run $ npm install jquery.
For example, from the "server-side" (my app.js file & friends), the following works perfectly:
import $ from "./node_modules/jquery/dist/jquery.js
Importing from my own "shared" code also works from both client and server via:
import { whatever } from "../shared/<module>.js"
But when I deploy and browse to https://<myapp>/client/shared/lib/jquery.js, I get a 404 error..
The goal is to be to get jquery from my "client-side" static javascript files with:
import $ from "../shared/lib/jquery.js"
(Or an equivalent relative path for deeper modules in the directory tree.)
Jquery is perhaps not the best example, if it bothers you pretend I'm talking about the "pluralize" library. I intend to use plenty of other npm distributions of js libraries and share them between my "client-side" statically served javascript files and my "server-side" code imported/pointed to from script: routes in app.yaml and/or imports from app.js
Also, I know I can use a "bundler" - or a cdn - etc. and I may eventually in production, but according to all the documentation this /should/ work. A correct answer will actually show me how to make this work and/or teach me what I don't understand about the static_files and upload handler options in app.yaml, not suggest an alternative that is a large edit distance away from my current setup.
I am trying to call a function in a python file from a js file, I got this to work through my console, but I am now trying to implement it in a mobile app using expo.
The way I had set this up is, I have the JS file for a certain screen in my app, this then calls a function in a separate JS file, which then calls the function in the python file.
I am using the child_process module to talk to python from JS.
And as I said, this was working before I tried to export the JS function to my screen file.
index.js
export function foo(process, sentence){
const spawn = require("child_process").spawn;
const process = spawn("python3", ["./python.py", sentence]);
...
}
screen.js
*other imports
import { foo } from "./filepath..."
...
But when I run npm start I get the following error:
Failed building JavaScript bundle.
While trying to resolve module `child_process` from file `/Users/mee/Documents/GitHub/project/app/screens/screen.js`, the package `/Users/mee/Documents/GitHub/project/node_modules/child_process/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/me/Documents/GitHub/project/node_modules/child_process/app/screens/screen.js`. Indeed, none of these files exist:
How can I fix this?
It won't work for few reasons
child_process is part of the node standard library, it's not available in other environments like react-native or browser
even if above was not true, there is no python3 executable on your phone
python.py file from your local directory wouldn't be even uploaded to the phone because bundler is only uploading one big js file with entire js code combined + assets, python.py is neither of those.
Only solution that make sense it to rewrite that code to javascript.
Technically it's not impossible, there might be a way to do that, by compiling python interpreter for mobile platform, or using some tool that translates python code into js, but it's not something that you should consider.
I'm trying to host a website, and I use a .wasm file with .js scripts created by the wasm-pack tool.
I tested the project locally with npm and node.js and everything worked fine.
But Then I hosted it on a raspberry (apache2), and when I try to access it, I get in the following error:
Failed to load module script: The server responded with a non-JavaScript MIME type of "application/wasm". Strict MIME type checking is enforced for module scripts per HTML spec.
details
There are multiple files, but here is the idea:
my index.html loads the module bootstrap.js
// bootstrap.js content
import("./index.js").catch(e => console.error("Error importing `index.js`:", e));
my main code is in the index.js, which calls test_wasm_bg.js
And finally, test_wasm_bg.js loads the wasm file with this line:
// test_wasm_bg.js first line
import * as wasm from './test_wasm_bg.wasm';
Where is the problem?
What is the right way to load a web assembly file?
I finally found what is the right way to load a wasm application in a wasm-bindgen project!
In fact, everything was on this page
When you compile the project without wanting to run it with a bundler, you have to run wasm-pack build with a --target flag.
wasm-pack build --release --target web.
This creates a .js file (pkg/test_wasm.js in my example) with everything you need to load the wasm-application.
And then this is how you use the functions created by wasm-bindgen (index.js):
import init from './pkg/test_wasm.js';
import {ex_function, ex_Struct ...} from '../pkg/test_wasm.js';
function run {
// use the function ex_function1 here
}
init().then(run)
You include your index.js in your HTML file
<script type="module" src="./index.js"></script>
And then it work's !
Edit:
Now that's I understand the javascript ecosystem a bit more, I cab try to explain what I understand:
There are many ways to do imports in js, here is a list :
https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm
You don't need to know much about that, except that the default target of wasm-pack is a node style ecmascript module. This import will work in node.js, but not directly in the browser. So in node, you can import a function from a wasm file directly, like so:
import {ex_function} from "./test.wasm"
But these styles of import don't work in the browser right now. Maybe it will be possible in the future
But for now, your browser only knows about js modules. So if you try to import a .wasm file directly in the browser, it will throw a mime type error because it doesn't know how to deal with webassembly files.
The tool you use to go from ecmascipt modules (with a lot of nmp packages for example) to a single js file is called a web-bundler (webpack, rollup, snowpack ...). If you work on a big project with npm, you probably need one. Otherwise, the "--target web" will say to wasm-bindgen to instantiate the wasm module the right way (look at the pkg/test_wasm.js)
I am trying to convert a python file to JS using transcrypt using the command transcrypt -b -m -n hello.py. I have an import to JSON in my python script:
import json
# the MAIN meaty function!!!
def exec_script_str(script_str, raw_input_lst_json, options_json, finalizer_func):
if options_json:
options = json.loads(options_json)
...
I get this error message:
Transcrypt (TM) Python to JavaScript Small Sane Subset Transpiler
Version 3.7.16 Copyright (C) Geatec Engineering. License: Apache 2.0
Saving target code in:
/home/sarwagya/Desktop/Hello/target/org.transcrypt.runtime.js
Saving target code in:
/home/sarwagya/Desktop/Hello/target/re.translate.js Saving target
code in: /home/sarwagya/Desktop/Hello/target/re.js Saving target
code in: /home/sarwagya/Desktop/Hello/target/warnings.js
Error while compiling (offending file last):
File '/home/sarwagya/Desktop/Hello/hello.py', line 2186, at import of:
File '/usr/lib/python3.8/json/init.py', line 108, at import of:
File 'codecs', line 44, namely: Can't import module 'codecs'
Aborted
I have a number of imports before this which seem to work. Since there is a JSON package in Javascript I would have thought transcript would support this.
Thanks for the help.
The full standard library has not been ported to Transcrypt yet, the json library included. In most cases you can get around this by using a JavaScript equivalent library to support whatever you are trying to accomplish, and they can be called directly from your Python code. But Transcrypt doesn't automatically do this library mapping for you, so you'll have to explicitly import the JavaScript library to use it.
Since Python dictionaries are converted to JavaScript objects with Transcrypt, you may be able to just use the JSON data as-is. Otherwise you can call the built-in JSON.parse() and JSON.stringify() directly with no imports necessary.