Skip to content

Commit 701f57e

Browse files
authored
Merge pull request #10 from Python-World/2023W29
Week 29 article
2 parents ae0a3b8 + 7fed83f commit 701f57e

File tree

2 files changed

+224
-3
lines changed

2 files changed

+224
-3
lines changed

Diff for: doc/newsletters/2023/WEEK_28.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
# Week 28 - Jully 2023
2+
# Week 28 - July 2023
33

44
## Introduction and Highlights
55

Diff for: doc/newsletters/2023/WEEK_29.md

+223-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11

2-
# Week 29 - Jully 2023
2+
# Week 29 - July 2023
33

44
## Introduction and Highlights
55

@@ -117,7 +117,7 @@ Experiment with `inspect` interactively in a Python REPL to get a better feel fo
117117

118118

119119

120-
### 3. 🔧 The Python Package Manager: Unleashing the Power of pip
120+
### 3. 🔧 The Python Package Manager: Unleashing the Power of pip
121121

122122

123123
`pip` is your go-to tool for installing, managing, and distributing Python packages. 🛠️📚 With a vast repository of open-source libraries available on the Python Package Index (PyPI), `pip` makes it a breeze to enhance your Python projects with external functionality. 🌟📦
@@ -229,6 +229,227 @@ print(f"Remainders: {remainders}")
229229
Remember that `divmod` can be a powerful tool to optimize certain mathematical operations and simplify your code. 🧮🚀
230230

231231

232+
233+
### 6. 👫 Strict separation of settings from code with Decouple
234+
235+
*Decouple* is a tool that assists in managing settings, allowing you to adjust parameters without the need to redeploy your application. It offers several benefits, such as the ability to store parameters in files like *ini* or *.env*, set up default values, ensure proper data type conversions, and centralize all configurations into a single module. Initially created for Django, it has evolved into a versatile tool for separating settings from the core code, making it applicable to various projects beyond Django.
236+
237+
**How to use in your project ?**
238+
239+
1. Install the package into your project environment.
240+
```shell
241+
pip install python-decouple
242+
```
243+
2. In your `config.py`
244+
245+
```python
246+
from decouple import config
247+
248+
SECRET_KEY = config('SECRET_KEY')
249+
DEBUG = config('DEBUG', default=False, cast=bool)
250+
EMAIL_HOST = config('EMAIL_HOST', default='localhost')
251+
EMAIL_PORT = config('EMAIL_PORT', default=25, cast=int)
252+
PAYMENT_GATEWAY_API_KEY = config('PAYMENT_GATEWAY_API_KEY', cast=str)
253+
```
254+
255+
3. Now in your other modules where you need to use these values
256+
257+
```python
258+
import config as cfg
259+
print(cfg.EMAIL_HOST)
260+
261+
```
262+
263+
### 7. 🐍 Empower yourself with Pydantic
264+
265+
Pydantic is a powerful data validation library for Python that has gained significant popularity among developers due to its extensive features and ease of use.
266+
267+
1. Typehints powering schema validation: Pydantic leverages Python type hints to define the structure of data models.
268+
269+
2. Performance: The core is written in rust, making it superfast.
270+
271+
3. Serialization: Pydantic provides seamless serialization and deserialization of data models to and from JSON, dictionaries, and other data formats.
272+
273+
4. JSON Schema: JSON Schema is a standard for describing the structure of JSON data. Pydantic can automatically generate JSON Schema representations of your data models. This allows you to validate your data against a defined JSON Schema or share the schema with other systems.
274+
275+
5. Strict mode and data coercion: Pydantic supports a strict mode that enforces the data model's field types strictly. It also provides data coercion, allowing you to automatically convert data to the specified types whenever possible. This feature makes handling user inputs and external data sources more robust.
276+
277+
278+
Let's consider a simple use case of using Pydantic to validate and serialize data for a User model:
279+
280+
```python
281+
from pydantic import BaseModel
282+
283+
class User(BaseModel):
284+
username: str
285+
email: str
286+
age: int
287+
288+
# Valid data
289+
user_data = {
290+
"username": "john_doe",
291+
"email": "john@example.com",
292+
"age": 30
293+
}
294+
295+
# Creating a User instance from the data
296+
user = User(**user_data)
297+
298+
# The instance is automatically validated and parsed
299+
print(user.username) # Output: john_doe
300+
print(user.email) # Output: john@example.com
301+
print(user.age) # Output: 30
302+
303+
# Invalid data - missing 'email' field
304+
invalid_user_data = {
305+
"username": "jane_doe",
306+
"age": 25
307+
}
308+
309+
# Trying to create a User instance with invalid data
310+
try:
311+
invalid_user = User(**invalid_user_data)
312+
except Exception as e:
313+
print(f"Error: {e}")
314+
# Output: Error: 1 validation error for User
315+
# email
316+
# field required (type=value_error.missing)
317+
```
318+
319+
In this example, we define a simple User model using Pydantic's BaseModel class and specify the expected types for each field (username, email, and age). When we create an instance of the User model with valid data, Pydantic automatically validates and parses the input. If the data is invalid, Pydantic raises an error with a helpful validation message.
320+
321+
Overall, Pydantic simplifies data validation, serialization, and parsing tasks, making it an invaluable tool for Python developers, especially in the context of web APIs, data processing, and data validation tasks. Its performance, type hint-based approach, and seamless integration with other libraries contribute to its widespread adoption in the Python ecosystem.
322+
323+
324+
### 8. 🐃 Stable Diffusion WebUI
325+
326+
This project offers a browser interface based on Gradio library for Stable Diffusion.
327+
328+
Gradio is a library offered by HuggingFace to quickly develop web interfaces for ml apps.
329+
330+
In simple words you can generate images based on a prompt.
331+
332+
Refer to the [GitHub repository](https://github.com/AUTOMATIC1111/stable-diffusion-webui) to learn about installation and usage.
333+
334+
### 9. ✍️ Text Generation WebUI
335+
336+
This is a sibling project of the previous one. A gradio web UI for running Large Language Models like LLaMA, llama.cpp, GPT-J, OPT, and GALACTICA.
337+
338+
As per its documentation the key features are:
339+
340+
- 3 interface modes: default, notebook, and chat
341+
- Multiple model backends: tranformers, llama.cpp, AutoGPTQ, GPTQ-for-LLaMa, ExLlama, RWKV, FlexGen
342+
- Dropdown menu for quickly switching between different models
343+
344+
Refer to the [github repository](https://github.com/oobabooga/text-generation-webui) for learning how to install and use.
345+
346+
347+
### 10. 🥇 Streamlit: A Python Library for Interactive Data Apps
348+
349+
In recent years, data visualization and interactive web applications have become essential tools for data scientists and developers. Creating intuitive and interactive data apps used to require extensive web development skills, but now, with the Streamlit Python library, anyone with basic Python knowledge can build powerful data-driven applications effortlessly.
350+
351+
**What is Streamlit?**
352+
353+
Streamlit is an open-source Python library that allows developers to create web applications for data exploration and visualization with minimal effort. It was designed to simplify the process of turning data scripts into shareable web apps, making it an excellent tool for showcasing data insights and machine learning models.
354+
355+
**Getting Started**
356+
357+
To use Streamlit, you need to have Python installed on your system. You can install Streamlit using pip:
358+
359+
```
360+
pip install streamlit
361+
```
362+
363+
**Creating Your First Streamlit App**
364+
365+
Once Streamlit is installed, creating a basic app is as simple as writing a few lines of Python code. Let's start by importing Streamlit and creating a simple app that displays a line chart:
366+
367+
```python
368+
# app.py
369+
import streamlit as st
370+
import pandas as pd
371+
import numpy as np
372+
import matplotlib.pyplot as plt
373+
374+
# Create a sample dataframe
375+
data = pd.DataFrame({
376+
'x': np.arange(10),
377+
'y': np.random.randn(10)
378+
})
379+
380+
# Add a title to the app
381+
st.title('My First Streamlit App')
382+
383+
# Display the dataframe
384+
st.dataframe(data)
385+
386+
# Create a line chart
387+
plt.plot(data['x'], data['y'])
388+
st.pyplot(plt)
389+
```
390+
391+
Save this code in a file named `app.py`, and then run the app using the following command:
392+
393+
```
394+
streamlit run app.py
395+
```
396+
397+
A new tab will open in your default web browser, displaying your first Streamlit app. The app will show a DataFrame and a simple line chart based on the data provided.
398+
399+
**Customizing Your App**
400+
401+
One of the greatest strengths of Streamlit is its ability to respond to user inputs and generate dynamic visualizations accordingly. For instance, you can add widgets like sliders, buttons, and text inputs to allow users to interact with your app.
402+
403+
Here's an example of how to add a slider to control the number of data points displayed in the chart:
404+
405+
```python
406+
# app.py
407+
import streamlit as st
408+
import pandas as pd
409+
import numpy as np
410+
import matplotlib.pyplot as plt
411+
412+
# Create a sample dataframe
413+
data = pd.DataFrame({
414+
'x': np.arange(100),
415+
'y': np.random.randn(100)
416+
})
417+
418+
# Add a title to the app
419+
st.title('Dynamic Chart with Streamlit')
420+
421+
# Add a slider for the number of data points
422+
num_points = st.slider('Number of Data Points', 10, 100, 50)
423+
424+
# Display the selected number of data points in the DataFrame
425+
st.dataframe(data.head(num_points))
426+
427+
# Create a dynamic line chart
428+
plt.plot(data['x'][:num_points], data['y'][:num_points])
429+
st.pyplot(plt)
430+
```
431+
432+
Now, when you run the app again, you will see a slider that allows you to control the number of data points displayed in the line chart.
433+
434+
**Sharing Your App**
435+
436+
Once you've created your Streamlit app and are satisfied with its functionality, you can easily share it with others. You can deploy it on various platforms, including Streamlit Sharing, Heroku, or your own web server.
437+
438+
For example, if you want to deploy it on Streamlit Sharing, you can follow these steps:
439+
440+
1. Create a GitHub repository with your Streamlit app code.
441+
2. Sign in to Streamlit Sharing (https://streamlit.io/sharing) using your GitHub account.
442+
3. Connect your GitHub repository to Streamlit Sharing and set up the deployment settings.
443+
4. Once connected, Streamlit Sharing will automatically build and deploy your app.
444+
445+
Now, you have a publicly accessible web link for your Streamlit app that you can share with anyone.
446+
447+
**Conclusion**
448+
449+
Streamlit is a game-changer in the world of data visualization and app development. Its simplicity and ease of use allow data scientists and developers to focus on presenting their data insights and models interactively without getting bogged down in web development complexities. With its increasing popularity and active community, Streamlit is likely to remain a popular choice for building interactive data applications in Python. So, if you want to create stunning and interactive data apps quickly, give Streamlit a try!
450+
451+
452+
232453
## Upcoming Events
233454

234455

0 commit comments

Comments
 (0)