Python  Library

Python Library

1656755220

Thumbor: An Open-source Photo Thumbnail Service Written in Python

Thumbor

thumbor is a smart imaging service and enables on-demand cropping, resizing, applying filters and optimizing images.

Cropping photos automatically can be a frustrating experience with severed heads involved. thumbor uses AI for smart detection.

thumbor is an HTTP server and you can create as many different images as you want just by varying path parameters:

http://<thumbor-server>/300x200/smart/thumbor.readthedocs.io/en/latest/_images/logo-thumbor.png

You should see an image of the thumbor logo in 300x200.

Learn more about all you can do in thumbor's documentation.

鈿欙笍 Installation

Decide which installation option you want to use.

Option 1: pip

# thumbor with main dependencies only
pip install thumbor

# thumbor with opencv dependency
pip install thumbor[opencv]

# thumbor with all dependencies
pip install thumbor[all]

Option 2: Binary

sudo add-apt-repository ppa:thumbor/ppa
sudo aptitude update
sudo aptitude install thumbor

For more ways, please check out Installation.

Run

Running it is as easy as hit:

thumbor

After this, you can reach it on https://localhost:8888/unsafe/https://raw.githubusercontent.com/thumbor/thumbor/master/example.jpg

Troubles?

If you experience any troubles, try running:

thumbor-doctor

If you have a thumbor.conf file, you can use that to help thumbor-doctor:

thumbor-doctor -c thumbor.conf

If you still need help, please raise an issue. Remember to send your thumbor-doctor output in the issue:

thumbor-doctor --nocolor -c thumbor.conf

馃幆 Features

  • supports all common images formats out of the box
  • intelligent cropping and resizing
  • blazing fast using caching
  • supports many storages (local storage, AWS S3, rackspace, ceph, ...)
  • AI-powered cropping based on face and feature detection (glasses, interesting points, ...)
  • integrated with many programming languages and frameworks  and many more...
  • highly extensible

馃専 Awesome Goodies

awesome-thumbor is a curated list of all things thumbor. There you can find filters, storages, engines, loaders, docker images, extensions in your favorite language and framework, and much more.

All of it with clear indication of each project quality. Have fun!

馃憤 Contribute

thumbor is an open-source project with many contributors. Join them contributing code or contributing documentation.

If you use thumbor, please take 1 minute and answer this survey? Only 2 questions!

Join the chat at https://gitter.im/thumbor/thumbor

馃憖 Demo

You can see thumbor in action at http://thumborize.me/

Download Details:
Author: thumbor
Source Code: https://github.com/thumbor/thumbor
License: MIT license

#python

What is GEEK

Buddha Community

Thumbor: An Open-source Photo Thumbnail Service Written in Python
Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Build an Android application with Kivy Python framework

If you鈥檙e a Python developer thinking about getting started with mobile development, then the Kivy framework is your best bet. With Kivy, you can develop platform-independent applications that compile for iOS, Android, Windows, macOS, and Linux. In this article, we鈥檒l cover Android specifically because it is the most used.

We鈥檒l build a simple random number generator app that you can install on your phone and test when you are done. To follow along with this article, you should be familiar with Python. Let鈥檚 get started!

Getting started with Kivy

First, you鈥檒l need a new directory for your app. Make sure you have Python installed on your machine and open a new Python file. You鈥檒l need to install the Kivy module from your terminal using either of the commands below. To avoid any package conflicts, be sure you鈥檙e installing Kivy in a virtual environment:

pip install kivy 
//
pip3 install kivy 

Once you have installed Kivy, you should see a success message from your terminal that looks like the screenshots below:

Kivy installation

Successful Kivy installation

 

Next, navigate into your project folder. In the main.py file, we鈥檒l need to import the Kivy module and specify which version we want. You can use Kivy v2.0.0, but if you have a smartphone that is older than Android 8.0, I recommend using Kivy v1.9.0. You can mess around with the different versions during the build to see the differences in features and performance.

Add the version number right after the import kivy line as follows:

kivy.require('1.9.0')

Now, we鈥檒l create a class that will basically define our app; I鈥檒l name mine RandomNumber. This class will inherit the app class from Kivy. Therefore, you need to import the app by adding from kivy.app import App:

class RandomNumber(App): 

In the RandomNumber class, you鈥檒l need to add a function called build, which takes a self parameter. To actually return the UI, we鈥檒l use the build function. For now, I have it returned as a simple label. To do so, you鈥檒l need to import Label using the line from kivy.uix.label import Label:

import kivy
from kivy.app import App
from kivy.uix.label import Label

class RandomNumber(App):
  def build(self):
    return Label(text="Random Number Generator")

Now, our app skeleton is complete! Before moving forward, you should create an instance of the RandomNumber class and run it in your terminal or IDE to see the interface:

import kivy from kivy.app import App from kivy.uix.label import Label class RandomNumber(App):  def build(self):    return Label(text="Random Number Generator") randomApp = RandomNumber() randomApp.run()

When you run the class instance with the text Random Number Generator, you should see a simple interface or window that looks like the screenshot below:

 

Simple interface after running the code

You won鈥檛 be able to run the text on Android until you鈥檝e finished building the whole thing.

Outsourcing the interface

Next, we鈥檒l need a way to outsource the interface. First, we鈥檒l create a Kivy file in our directory that will house most of our design work. You鈥檒l want to name this file the same name as your class using lowercase letters and a .kv extension. Kivy will automatically associate the class name and the file name, but it may not work on Android if they are exactly the same.

Inside that .kv file, you need to specify the layout for your app, including elements like the label, buttons, forms, etc. To keep this demonstration simple, I鈥檒l add a label for the title Random Number, a label that will serve as a placeholder for the random number that is generated _, and a Generate button that calls the generate function.

My .kv file looks like the code below, but you can mess around with the different values to fit your requirements:

<boxLayout>:
    orientation: "vertical"
    Label:
        text: "Random Number"
        font_size: 30
        color: 0, 0.62, 0.96

    Label:
        text: "_"
        font_size: 30

    Button:
        text: "Generate"
        font_size: 15 

In the main.py file, you no longer need the Label import statement because the Kivy file takes care of your UI. However, you do need to import boxlayout, which you will use in the Kivy file.

In your main file, you need to add the import statement and edit your main.py file to read return BoxLayout() in the build method:

from kivy.uix.boxlayout import BoxLayout

If you run the command above, you should see a simple interface that has the random number title, the _ place holder, and the clickable generate button:

Random Number app rendered

Notice that you didn鈥檛 have to import anything for the Kivy file to work. Basically, when you run the app, it returns boxlayout by looking for a file inside the Kivy file with the same name as your class. Keep in mind, this is a simple interface, and you can make your app as robust as you want. Be sure to check out the Kv language documentation.

Generate the random number function

Now that our app is almost done, we鈥檒l need a simple function to generate random numbers when a user clicks the generate button, then render that random number into the app interface. To do so, we鈥檒l need to change a few things in our files.

First, we鈥檒l import the module that we鈥檒l use to generate a random number with import random. Then, we鈥檒l create a function or method that calls the generated number. For this demonstration, I鈥檒l use a range between 0 and 2000. Generating the random number is simple with the random.randint(0, 2000) command. We鈥檒l add this into our code in a moment.

Next, we鈥檒l create another class that will be our own version of the box layout. Our class will have to inherit the box layout class, which houses the method to generate random numbers and render them on the interface:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

Within that class, we鈥檒l create the generate method, which will not only generate random numbers but also manipulate the label that controls what is displayed as the random number in the Kivy file.

To accommodate this method, we鈥檒l first need to make changes to the .kv file . Since the MyRoot class has inherited the box layout, you can make MyRoot the top level element in your .kv file:

<MyRoot>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

Notice that you are still keeping all your UI specifications indented in the Box Layout. After this, you need to add an ID to the label that will hold the generated numbers, making it easy to manipulate when the generate function is called. You need to specify the relationship between the ID in this file and another in the main code at the top, just before the BoxLayout line:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

The random_label: random_label line basically means that the label with the ID random_label will be mapped to random_label in the main.py file, meaning that any action that manipulates random_label will be mapped on the label with the specified name.

We can now create the method to generate the random number in the main file:

def generate_number(self):
    self.random_label.text = str(random.randint(0, 2000))

# notice how the class method manipulates the text attributre of the random label by a# ssigning it a new random number generate by the 'random.randint(0, 2000)' funcion. S# ince this the random number generated is an integer, typecasting is required to make # it a string otherwise you will get a typeError in your terminal when you run it.

The MyRoot class should look like the code below:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_number(self):
        self.random_label.text = str(random.randint(0, 2000))

Congratulations! You鈥檙e now done with the main file of the app. The only thing left to do is make sure that you call this function when the generate button is clicked. You need only add the line on_press: root.generate_number() to the button selection part of your .kv file:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15
            on_press: root.generate_number()

Now, you can run the app.

Compiling our app on Android

Before compiling our app on Android, I have some bad news for Windows users. You鈥檒l need Linux or macOS to compile your Android application. However, you don鈥檛 need to have a separate Linux distribution, instead, you can use a virtual machine.

To compile and generate a full Android .apk application, we鈥檒l use a tool called Buildozer. Let鈥檚 install Buildozer through our terminal using one of the commands below:

pip3 install buildozer
//
pip install buildozer

Now, we鈥檒l install some of Buildozer鈥檚 required dependencies. I am on Linux Ergo, so I鈥檒l use Linux-specific commands. You should execute these commands one by one:

sudo apt update
sudo apt install -y git zip unzip openjdk-13-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev

pip3 install --upgrade Cython==0.29.19 virtualenv 

# add the following line at the end of your ~/.bashrc file
export PATH=$PATH:~/.local/bin/

After executing the specific commands, run buildozer init. You should see an output similar to the screenshot below:

Buildozer successful initialization

The command above creates a Buildozer .spec file, which you can use to make specifications to your app, including the name of the app, the icon, etc. The .spec file should look like the code block below:

[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = \['"\](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = 漏 Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
#android.permissions = INTERNET

# (int) Target Android API, should be as high as possible.
#android.api = 27

# (int) Minimum API your APK will support.
#android.minapi = 21

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 19b

# (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi.
#android.ndk_api = 21

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (bool) If True, then automatically accept SDK license
# agreements. This is intended for automation only. If set to False,
# the default, you will be shown the license when first running
# buildozer.
# android.accept_sdk_license = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (str) Android app theme, default is ok for Kivy-based app
# android.apptheme = "@android:style/Theme.NoTitleBar"

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =

# (list) add java compile options
# this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option
# see https://developer.android.com/studio/write/java8-support for further information
# android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8"

# (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies}
# please enclose in double quotes 
# e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }"
#android.add_gradle_repositories =

# (list) packaging options to add 
# see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html
# can be necessary to solve conflicts in gradle_dependencies
# please enclose in double quotes 
# e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'"
#android.add_gradle_repositories =

# (list) Java classes to add as activities to the manifest.
#android.add_activities = com.example.ExampleActivity

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_arm64_v8a = libs/android-v8/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag
#android.uses_library =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64
android.arch = armeabi-v7a

# (int) overrides automatic versionCode computation (used in build.gradle)
# this is not the same as app version and should only be edited if you know what you're doing
# android.numeric_version = 1

#
# Python for android (p4a) specific
#

# (str) python-for-android fork to use, defaults to upstream (kivy)
#p4a.fork = kivy

# (str) python-for-android branch to use, defaults to master
#p4a.branch = master

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =


#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# Alternately, specify the URL and branch of a git checkout:
ios.kivy_ios_url = https://github.com/kivy/kivy-ios
ios.kivy_ios_branch = master

# Another platform dependency: ios-deploy
# Uncomment to use a custom checkout
#ios.ios_deploy_dir = ../ios_deploy
# Or specify URL and branch
ios.ios_deploy_url = https://github.com/phonegap/ios-deploy
ios.ios_deploy_branch = 1.7.0

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s


[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

If you want to specify things like the icon, requirements, loading screen, etc., you should edit this file. After making all the desired edits to your application, run buildozer -v android debug from your app directory to build and compile your application. This may take a while, especially if you have a slow machine.

After the process is done, your terminal should have some logs, one confirming that the build was successful:

Android successful build

You should also have an APK version of your app in your bin directory. This is the application executable that you will install and run on your phone:

Android .apk in the bin directory

Conclusion

Congratulations! If you have followed this tutorial step by step, you should have a simple random number generator app on your phone. Play around with it and tweak some values, then rebuild. Running the rebuild will not take as much time as the first build.

As you can see, building a mobile application with Python is fairly straightforward, as long as you are familiar with the framework or module you are working with. Regardless, the logic is executed the same way.

Get familiar with the Kivy module and it鈥檚 widgets. You can never know everything all at once. You only need to find a project and get your feet wet as early as possible. Happy coding.

Link: https://blog.logrocket.com/build-android-application-kivy-python-framework/

#python 

Cree Una Aplicaci贸n De Android Con El Marco Kivy Python

Si es un desarrollador de Python que est谩 pensando en comenzar con el desarrollo m贸vil, entonces el marco Kivy es su mejor opci贸n. Con Kivy, puede desarrollar aplicaciones independientes de la plataforma que compilan para iOS, Android, Windows, macOS y Linux. En este art铆culo, cubriremos Android espec铆ficamente porque es el m谩s utilizado.

Construiremos una aplicaci贸n generadora de n煤meros aleatorios simple que puede instalar en su tel茅fono y probar cuando haya terminado. Para continuar con este art铆culo, debe estar familiarizado con Python. 隆Empecemos!

Primeros pasos con Kivy

Primero, necesitar谩 un nuevo directorio para su aplicaci贸n. Aseg煤rese de tener Python instalado en su m谩quina y abra un nuevo archivo de Python. Deber谩 instalar el m贸dulo Kivy desde su terminal usando cualquiera de los comandos a continuaci贸n. Para evitar conflictos de paquetes, aseg煤rese de instalar Kivy en un entorno virtual:

pip install kivy 
//
pip3 install kivy 

Una vez que haya instalado Kivy, deber铆a ver un mensaje de 茅xito de su terminal que se parece a las capturas de pantalla a continuaci贸n:

Instalaci贸n decepcionada

Instalaci贸n exitosa de Kivy

 

A continuaci贸n, navegue a la carpeta de su proyecto. En el main.pyarchivo, necesitaremos importar el m贸dulo Kivy y especificar qu茅 versi贸n queremos. Puede usar Kivy v2.0.0, pero si tiene un tel茅fono inteligente anterior a Android 8.0, le recomiendo usar Kivy v1.9.0. Puede jugar con las diferentes versiones durante la compilaci贸n para ver las diferencias en las caracter铆sticas y el rendimiento.

Agregue el n煤mero de versi贸n justo despu茅s de la import kivyl铆nea de la siguiente manera:

kivy.require('1.9.0')

Ahora, crearemos una clase que b谩sicamente definir谩 nuestra aplicaci贸n; Voy a nombrar el m铆o RandomNumber. Esta clase heredar谩 la appclase de Kivy. Por lo tanto, debe importar appagregando from kivy.app import App:

class RandomNumber(App): 

En la RandomNumberclase, deber谩 agregar una funci贸n llamada build, que toma un selfpar谩metro. Para devolver la interfaz de usuario, usaremos la buildfunci贸n. Por ahora, lo tengo devuelto como una simple etiqueta. Para hacerlo, deber谩 importar Labelusando la l铆nea from kivy.uix.label import Label:

import kivy
from kivy.app import App
from kivy.uix.label import Label

class RandomNumber(App):
  def build(self):
    return Label(text="Random Number Generator")

隆Ahora, el esqueleto de nuestra aplicaci贸n est谩 completo! Antes de continuar, debe crear una instancia de la RandomNumberclase y ejecutarla en su terminal o IDE para ver la interfaz:

importar kivy de kivy.app importar aplicaci贸n de kivy.uix.label clase de etiqueta de importaci贸n RandomNumber(App): def build(self): return Label(text="Generador de n煤meros aleatorios") randomApp = RandomNumber() randomApp.run()

Cuando ejecuta la instancia de clase con el texto Random Number Generator, deber铆a ver una interfaz o ventana simple que se parece a la siguiente captura de pantalla:

 

Interfaz simple despu茅s de ejecutar el c贸digo.

No podr谩 ejecutar el texto en Android hasta que haya terminado de construir todo.

Externalizaci贸n de la interfaz

A continuaci贸n, necesitaremos una forma de subcontratar la interfaz. Primero, crearemos un archivo Kivy en nuestro directorio que albergar谩 la mayor parte de nuestro trabajo de dise帽o. Querr谩 nombrar este archivo con el mismo nombre que su clase usando letras min煤sculas y una .kvextensi贸n. Kivy asociar谩 autom谩ticamente el nombre de la clase y el nombre del archivo, pero es posible que no funcione en Android si son exactamente iguales.

Dentro de ese .kvarchivo, debe especificar el dise帽o de su aplicaci贸n, incluidos elementos como la etiqueta, los botones, los formularios, etc. Para simplificar esta demostraci贸n, agregar茅 una etiqueta para el t铆tulo Random Number, una etiqueta que servir谩 como marcador de posici贸n. para el n煤mero aleatorio que se genera _, y un Generatebot贸n que llama a la generatefunci贸n.

Mi .kvarchivo se parece al siguiente c贸digo, pero puede jugar con los diferentes valores para que se ajusten a sus requisitos:

<boxLayout>:
    orientation: "vertical"
    Label:
        text: "Random Number"
        font_size: 30
        color: 0, 0.62, 0.96

    Label:
        text: "_"
        font_size: 30

    Button:
        text: "Generate"
        font_size: 15 

En el main.pyarchivo, ya no necesita la Labeldeclaraci贸n de importaci贸n porque el archivo Kivy se encarga de su interfaz de usuario. Sin embargo, necesita importar boxlayout, que utilizar谩 en el archivo Kivy.

En su archivo principal, debe agregar la declaraci贸n de importaci贸n y editar su main.pyarchivo para leer return BoxLayout()el buildm茅todo:

from kivy.uix.boxlayout import BoxLayout

Si ejecuta el comando anterior, deber铆a ver una interfaz simple que tiene el t铆tulo del n煤mero aleatorio, el _marcador de posici贸n y el generatebot贸n en el que se puede hacer clic:

Aplicaci贸n de n煤meros aleatorios renderizada

Tenga en cuenta que no tuvo que importar nada para que funcione el archivo Kivy. B谩sicamente, cuando ejecuta la aplicaci贸n, regresa boxlayoutbuscando un archivo dentro del archivo Kivy con el mismo nombre que su clase. Tenga en cuenta que esta es una interfaz simple y puede hacer que su aplicaci贸n sea tan robusta como desee. Aseg煤rese de consultar la documentaci贸n del idioma Kv .

Generar la funci贸n de n煤meros aleatorios

Ahora que nuestra aplicaci贸n est谩 casi terminada, necesitaremos una funci贸n simple para generar n煤meros aleatorios cuando un usuario haga clic en el generatebot贸n y luego mostrar ese n煤mero aleatorio en la interfaz de la aplicaci贸n. Para hacerlo, necesitaremos cambiar algunas cosas en nuestros archivos.

Primero, importaremos el m贸dulo que usaremos para generar un n煤mero aleatorio con import random. Luego, crearemos una funci贸n o m茅todo que llame al n煤mero generado. Para esta demostraci贸n, usar茅 un rango entre 0y 2000. Generar el n煤mero aleatorio es simple con el random.randint(0, 2000)comando. Agregaremos esto a nuestro c贸digo en un momento.

A continuaci贸n, crearemos otra clase que ser谩 nuestra propia versi贸n del box layout. Nuestra clase tendr谩 que heredar la box layoutclase, que alberga el m茅todo para generar n煤meros aleatorios y representarlos en la interfaz:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

Dentro de esa clase, crearemos el generatem茅todo, que no solo generar谩 n煤meros aleatorios, sino que tambi茅n manipular谩 la etiqueta que controla lo que se muestra como n煤mero aleatorio en el archivo Kivy.

Para acomodar este m茅todo, primero necesitaremos hacer cambios en el .kvarchivo. Dado que la MyRootclase ha heredado el box layout, puede crear MyRootel elemento de nivel superior en su .kvarchivo:

<MyRoot>:
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

Tenga en cuenta que todav铆a mantiene todas las especificaciones de la interfaz de usuario con sangr铆a en el archivo Box Layout. Despu茅s de esto, debe agregar una identificaci贸n a la etiqueta que contendr谩 los n煤meros generados, lo que facilita la manipulaci贸n cuando generatese llama a la funci贸n. Debe especificar la relaci贸n entre la ID en este archivo y otra en el c贸digo principal en la parte superior, justo antes de la BoxLayoutl铆nea:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15

La random_label: random_labell铆nea b谩sicamente significa que la etiqueta con el ID random_labelse asignar谩 a random_labelen el main.pyarchivo, lo que significa que cualquier acci贸n que manipula random_labelser谩n mapeados en la etiqueta con el nombre especificado.

Ahora podemos crear el m茅todo para generar el n煤mero aleatorio en el archivo principal:

def generate_number(self):
    self.random_label.text = str(random.randint(0, 2000))

# notice how the class method manipulates the text attributre of the random label by a# ssigning it a new random number generate by the 'random.randint(0, 2000)' funcion. S# ince this the random number generated is an integer, typecasting is required to make # it a string otherwise you will get a typeError in your terminal when you run it.

La MyRootclase deber铆a parecerse al siguiente c贸digo:

class MyRoot(BoxLayout):
    def __init__(self):
        super(MyRoot, self).__init__()

    def generate_number(self):
        self.random_label.text = str(random.randint(0, 2000))

隆Felicidades! Ya ha terminado con el archivo principal de la aplicaci贸n. Lo 煤nico que queda por hacer es asegurarse de llamar a esta funci贸n cuando se haga generateclic en el bot贸n. Solo necesita agregar la l铆nea on_press: root.generate_number()a la parte de selecci贸n de botones de su .kvarchivo:

<MyRoot>:
    random_label: random_label
    BoxLayout:
        orientation: "vertical"
        Label:
            text: "Random Number"
            font_size: 30
            color: 0, 0.62, 0.96

        Label:
            id: random_label
            text: "_"
            font_size: 30

        Button:
            text: "Generate"
            font_size: 15
            on_press: root.generate_number()

Ahora, puede ejecutar la aplicaci贸n.

Compilando nuestra aplicaci贸n en Android

Antes de compilar nuestra aplicaci贸n en Android, tengo malas noticias para los usuarios de Windows. Necesitar谩 Linux o macOS para compilar su aplicaci贸n de Android. Sin embargo, no necesita tener una distribuci贸n de Linux separada, en su lugar, puede usar una m谩quina virtual.

Para compilar y generar una .apkaplicaci贸n Android completa , usaremos una herramienta llamada Buildozer . Instalemos Buildozer a trav茅s de nuestra terminal usando uno de los siguientes comandos:

pip3 install buildozer
//
pip install buildozer

Ahora, instalaremos algunas de las dependencias requeridas de Buildozer. Estoy en Linux Ergo, as铆 que usar茅 comandos espec铆ficos de Linux. Debe ejecutar estos comandos uno por uno:

sudo apt update
sudo apt install -y git zip unzip openjdk-13-jdk python3-pip autoconf libtool pkg-config zlib1g-dev libncurses5-dev libncursesw5-dev libtinfo5 cmake libffi-dev libssl-dev

pip3 install --upgrade Cython==0.29.19 virtualenv 

# add the following line at the end of your ~/.bashrc file
export PATH=$PATH:~/.local/bin/

Despu茅s de ejecutar los comandos espec铆ficos, ejecute buildozer init. Deber铆a ver un resultado similar a la captura de pantalla a continuaci贸n:

Inicializaci贸n exitosa de Buildozer

El comando anterior crea un .specarchivo Buildozer , que puede usar para hacer especificaciones para su aplicaci贸n, incluido el nombre de la aplicaci贸n, el 铆cono, etc. El .specarchivo debe verse como el bloque de c贸digo a continuaci贸n:

[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = \['"\](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = 漏 Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
#android.permissions = INTERNET

# (int) Target Android API, should be as high as possible.
#android.api = 27

# (int) Minimum API your APK will support.
#android.minapi = 21

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 19b

# (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi.
#android.ndk_api = 21

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (bool) If True, then automatically accept SDK license
# agreements. This is intended for automation only. If set to False,
# the default, you will be shown the license when first running
# buildozer.
# android.accept_sdk_license = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (str) Android app theme, default is ok for Kivy-based app
# android.apptheme = "@android:style/Theme.NoTitleBar"

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =

# (list) add java compile options
# this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option
# see https://developer.android.com/studio/write/java8-support for further information
# android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8"

# (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies}
# please enclose in double quotes 
# e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }"
#android.add_gradle_repositories =

# (list) packaging options to add 
# see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html
# can be necessary to solve conflicts in gradle_dependencies
# please enclose in double quotes 
# e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'"
#android.add_gradle_repositories =

# (list) Java classes to add as activities to the manifest.
#android.add_activities = com.example.ExampleActivity

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_arm64_v8a = libs/android-v8/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag
#android.uses_library =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64
android.arch = armeabi-v7a

# (int) overrides automatic versionCode computation (used in build.gradle)
# this is not the same as app version and should only be edited if you know what you're doing
# android.numeric_version = 1

#
# Python for android (p4a) specific
#

# (str) python-for-android fork to use, defaults to upstream (kivy)
#p4a.fork = kivy

# (str) python-for-android branch to use, defaults to master
#p4a.branch = master

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =


#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# Alternately, specify the URL and branch of a git checkout:
ios.kivy_ios_url = https://github.com/kivy/kivy-ios
ios.kivy_ios_branch = master

# Another platform dependency: ios-deploy
# Uncomment to use a custom checkout
#ios.ios_deploy_dir = ../ios_deploy
# Or specify URL and branch
ios.ios_deploy_url = https://github.com/phonegap/ios-deploy
ios.ios_deploy_branch = 1.7.0

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s


[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#


#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

Si desea especificar cosas como el 铆cono, los requisitos, la pantalla de carga, etc., debe editar este archivo. Despu茅s de realizar todas las ediciones deseadas en su aplicaci贸n, ejecute buildozer -v android debugdesde el directorio de su aplicaci贸n para construir y compilar su aplicaci贸n. Esto puede llevar un tiempo, especialmente si tiene una m谩quina lenta.

Una vez finalizado el proceso, su terminal deber铆a tener algunos registros, uno que confirme que la compilaci贸n fue exitosa:

Construcci贸n exitosa de Android

Tambi茅n debe tener una versi贸n APK de su aplicaci贸n en su directorio bin. Este es el ejecutable de la aplicaci贸n que instalar谩 y ejecutar谩 en su tel茅fono:

Android .apk en el directorio bin

Conclusi贸n

隆Felicidades! Si ha seguido este tutorial paso a paso, deber铆a tener una aplicaci贸n simple de generador de n煤meros aleatorios en su tel茅fono. Juega con 茅l y ajusta algunos valores, luego reconstruye. Ejecutar la reconstrucci贸n no llevar谩 tanto tiempo como la primera compilaci贸n.

Como puede ver, crear una aplicaci贸n m贸vil con Python es bastante sencillo , siempre que est茅 familiarizado con el marco o m贸dulo con el que est谩 trabajando. Independientemente, la l贸gica se ejecuta de la misma manera.

Familiar铆cese con el m贸dulo Kivy y sus widgets. Nunca se puede saber todo a la vez. Solo necesita encontrar un proyecto y mojarse los pies lo antes posible. Codificaci贸n feliz.

Enlace: https://blog.logrocket.com/build-android-application-kivy-python-framework/

#python 

22 Interesting Python Open Source Project Ideas & Topics for Beginners [2021]

Python is among the most popular programming languages on the planet, and there are many reasons behind this fame. One of those reasons is a large number of open-source projects and libraries available for this language. From machine learning to animation, there鈥檚 a Python project for nearly everything. If you want to become a proficient Python developer, you should be familiar with some of these projects (if not all).

That鈥檚 why in this article, we鈥檒l discuss different Python projects with source code Github. Because Python has applications in various industries, you might find many projects to help you complete your tasks. You should choose projects according to your interests and your experience. You can bookmark this article for future reference. Let鈥檚 get started.

Here are a few of the Python Open Source Project Ideas 鈥

#data science #open source project ideas #open source projects #project ideas #python #python open source

August  Larson

August Larson

1621294620

Reflecting On My First 5 Months As An Open-Source Contributor

Hey there everybody,

Early in 2020 I started a journey as a Content Creator, where I鈥檝e been writing technical content on Software Development 鈥 mostly focused on the Python stack.

In the past 5 months, I began a new journey as an open-source contributor, and to date, I鈥檝e contributed to 8 different python packages.

I鈥檓 going to share my story as 5-month old contributor with you here, along with my thoughts on why it鈥檚 beneficial to contribute to open source.

This article originally started as a thread on Twitter and then decided to turn it into an article regarding my journey as an open-source contributor. I hope you鈥檒l enjoy it, and take your time!

#python #python-skills #python-libraries #learn-python #data-science #open-source #hackernoon-top-story #contributing-to-open-source #web-monetization