Encontrar

Artículo
· 18 nov, 2024 Lectura de 8 min

Embedded Python dans InterSystems IRIS

Bonjour la communauté,

Dans cet article, je vais décrire et illustrer le processus de mise en œuvre d'ObjectScript au sein de Embedded Python. Cette discussion fera également référence à d'autres articles relatifs à Embedded Python, et répondra aux questions qui ont été utiles à mon apprentissage.

Comme vous le savez peut-être, l'intégration des fonctionnalités de Python dans IRIS est possible depuis un certain temps. Cet article se concentrera sur la manière dont ObjectScript peut être incorporé de manière transparente à Embedded Python.

Comentarios (0)2
Inicie sesión o regístrese para continuar
Artículo
· 18 nov, 2024 Lectura de 1 min

Novedades de FHIR 2024.3: Nuevos modificadores de búsqueda FHIR y parámetros de resultados de búsqueda compatibles

La versión 2024.3 de InterSystems IRIS for Health ya está disponible como Vista Previa para Desarrolladores desde hace un tiempo, y quiero destacar las nuevas funcionalidades relacionadas con la búsqueda FHIR que se han introducido.

Se soporte ahora la posibilidad de utilizar dos modificadores adicionales: 

Estos os permitirán realizar consultas de búsqueda más flexibles, sofisticadas y completas.

Y un nuevo parámetro de resultados de búsqueda:

Este os permitirá obtener resultados más compactos (y, potencialmente, más eficientes).

Consultad también las Notas de la Versión relacionadas.

Comentarios (0)1
Inicie sesión o regístrese para continuar
Artículo
· 18 nov, 2024 Lectura de 2 min

Visión general de la IA Generativa - Parte 1

La inteligencia artificial generativa es una inteligencia artificial capaz de generar texto, imágenes u otros datos utilizando modelos generativos, a menudo en respuesta a indicaciones o "prompts". Los modelos de IA generativa aprenden los patrones y la estructura de sus datos de entrenamiento y luego generan nuevos datos con características similares.

La IA generativa es capaz de crear texto, imágenes y otros tipos de contenido. Lo que la convierte en una tecnología fantástica es que democratiza el uso de la IA; cualquiera puede utilizarla con tan solo una indicación escrita en lenguaje natural.

Cómo funcionan los modelos de lenguaje a gran escala (Large Language Models o LLMs en sus siglas en inglés):

  • Tokenizador, de texto a números: Los modelos de lenguaje a gran escala reciben un texto como entrada y generan un texto como salida. Sin embargo, al ser modelos estadísticos, funcionan mucho mejor con números que con secuencias de texto. Por eso, cada entrada al modelo es procesada por un tokenizador antes de ser utilizada por el modelo central. Un token es un fragmento de texto que consiste en un número variable de caracteres, por lo que la tarea principal del tokenizador es dividir la entrada en un conjunto de tokens. Luego, cada token se asigna a un índice de token, que es la codificación numérica del fragmento original de texto. Example of tokenization
  • Predicción de tokens de salida: Dado un número de tokens como entrada (con un máximo de n que varía de un modelo a otro), el modelo es capaz de predecir un token como salida. Este token se incorpora a la entrada de la siguiente iteración, en un patrón de ventana expansiva, lo que permite ofrecer una mejor experiencia de usuario al obtener una o varias frases como respuesta. Esto explica por qué, si alguna vez habéis jugado con ChatGPT, quizá habréis notado que a veces parece que se detiene a mitad de una frase.
  • Proceso de selección, distribución de probabilidades: El token de salida es seleccionado por el modelo según su probabilidad de aparecer después de la secuencia de texto actual. Esto se debe a que el modelo predice una distribución de probabilidad sobre todos los posibles "siguientes tokens", calculada en función de su entrenamiento. Sin embargo, no siempre se selecciona el token con mayor probabilidad de la distribución resultante. Se añade un grado de aleatoriedad a esta elección, de manera que el modelo actúa de forma no determinista, lo que significa que no obtenemos exactamente la misma salida para una misma entrada. Este grado de aleatoriedad se añade para simular el proceso de pensamiento creativo y se puede ajustar utilizando un parámetro del modelo llamado temperatura.

En el próximo artículo realizaremos demostraciones prácticas.

Gracias

Comentarios (0)1
Inicie sesión o regístrese para continuar
Resumen
· 18 nov, 2024

Publications des développeurs d'InterSystems, semaine Novembre 11 - 17, 2024, Résumé

Novembre 11 - 17, 2024Week at a GlanceInterSystems Developer Community
Artículo
· 18 nov, 2024 Lectura de 8 min

Getting to know Python Streamlit Web Framework



Hi, Community!

In this article, I will introduce Python Streamlit Web Framework.

Below, you can find the topics we will cover:

  • 1-Introduction to Streamlit Web Framework
  • 2-Installation of Streamlit module
  • 3-Running Streamlit Application
  • 4-Streamlit Basic commands
  • 5-Display multimedia 
  • 6-Input widgets
  • 7-Display progress and status
  • 8-Sidebar and container
  • 9-Data Visualization
  • 10-Display a DataFrame

 

So, let's start with the first topic.
1-Introduction to Python Streamlit Web Framework 

Streamlit is an open-source Python framework that allows data scientists and machine learning engineers to create interactive web applications quickly and easily.
With its simple syntax and effortless integration with popular data science libraries, Streamlit has become the front-runner for prototyping and sharing projects.

For more details please view Streamit Documentations

2-Installation of Streamlit module

Before we start building our Streamlit Web Application, we need to install the module using the pip package installer.

To install Streamlit, run the following command:

pip install streamlit

Below there is the command to test the installation: 

streamlit hello



When you type the command mentioned above in the terminal, the following page should open automatically:
Install Streamlit 3

 

3-Running Streamlit Application

Working with Streamlit is straightforward. First, you sprinkle a few Streamlit commands into a normal Python script, then you run it with streamlit run:

streamlit run your_python_file.py 

As soon as you run the script, a local Streamlit server will spin up and your app will open in a new tab in your default web browser.  Please note that the app is your canvas, where you will draw charts, texts, widgets, tables, and more.

Another way of running Streamlit is doing so as a Python module. This can come in handy when configuring an IDE, e.g., PyCharm to work with Streamlit:

python -m streamlit run your_python_file.py

Remember to save the source file whenever you wish to update your app. When you do so, Streamlit detects a change if any, and asks you whether you want to rerun your app. Select "Always rerun" at the top-right of your screen to automatically update your app each time you modify its source code. It will allow you to work in a fast interactive loop: you type some code, save it, try it out live, then type some more code, save it, try it out, and so on until you are happy with the results. This tight loop between coding and viewing results live is one of the ways Streamlit makes your life easier.

4-Streamlit Basic commands

Display texts with Streamlit

st.write(): This function adds anything from formatted strings to charts in Matplotlib figures, Altair charts, Plotly figures, data frames, Keras models, and others to a web app.

Let's create main.py file below:

import streamlit as st

st.write("Hello ,let's learn how to build a streamlit app together")

Run the main.py file by operating the following command:

streamlit run main.py


st.title(): This function allows you to add the title to the app. 
st.header(): This function is used to assign the header of a section.
st.markdown(): This function is utilized to set a markdown of a section. 
st.subheader(): This function is employed to set the sub-header of a section.
st.caption(): This function is used to write captions.
st.code(): This function is utilized to set a code.  
st.latex(): This function displays mathematical expressions formatted as LaTeX. 

import streamlit as st

st.title("This is the app title")
st.header("This is the header")
st.markdown("This is the markdown")
st.subheader("This is the subheader")
st.caption("This is the caption")
st.code("x = 2021")
st.latex(r''' a+a r^1+a r^2+a r^3 ''')

Display texts with Streamlit 2

5-Display multimedia 

Below we listed some functions to display images, videos, and audio files.

st.image(): This function is employed to depict an image.
st.audio(): This function is utilized to display an audio. 
st.video(): This function is used to show a video.

import streamlit as st

st.subheader("Image :")
st.image("kid.jpg")

st.subheader("Audio :")
st.audio("audio.mp3")

st.subheader("Video :")
st.video("video.mp4")


6-Input widgets

Widgets are the most significant user interface components. Streamlit has various widgets that allow you to build interactivity directly into your apps with buttons, sliders, text inputs, and more.

st.checkbox(): This function returns a Boolean value. When the box is checked, it returns a True value. Otherwise, it sends back a False value.
st.button(): This function is used to display a button widget. 
st.radio(): This function exhibits a radio button widget. 
st.selectbox(): This function is utilized to demonstrate a select widget. 
st.multiselect(): This function is used to display a multi select widget. 
st.select_slider(): This function is used to display a select slider widget. 
st.slider(): This function is used to display a slider widget.

import streamlit as st

st.checkbox('Yes')
st.button('Click Me')
st.radio('Pick your gender', ['Male', 'Female'])
st.selectbox('Pick a fruit', ['Apple', 'Banana', 'Orange'])
st.multiselect('Choose a planet', ['Jupiter', 'Mars', 'Neptune'])
st.select_slider('Pick a mark', ['Bad', 'Good', 'Excellent'])
st.slider('Pick a number', 0, 50)

st.number_input(): This function displays a numeric input widget.
st.text_input(): This function exhibits a text input widget.
st.date_input(): This function reveals a date input widget to choose a date.
st.time_input(): This function exposes a time input widget to select a time.
st.text_area(): This function shows a text input widget with more than a line of text.
st.file_uploader(): This function is operated to demonstrate a file uploader widget.
st.color_picker(): This function is operated to demonstrate a file uploader widget.

import streamlit as st

st.number_input('Pick a number', 0, 10)
st.text_input('Email address')
st.date_input('Traveling date')
st.time_input('School time')
st.text_area('Description')
st.file_uploader('Upload a photo')
st.color_picker('Choose your favorite color')

7-Display progress and status

At this point, we will explain how to add a progress bar and such status messages as error and success to our app.

st.balloons(): This function is used to display balloons for celebration. 
st.progress(): This function is utilized to show a progress bar. 
st.spinner(): This function demonstrates a temporary waiting message during execution.

import streamlit as st
import time

st.balloons()  # Celebration balloons
st.subheader("Progress bar")
st.progress(10)  # Progress bar
st.subheader("Wait the execution")
with st.spinner('Wait for it...'):
    time.sleep(10)  # Simulating a process delay

Display progress and status with Streamlit 1

st.success(): This function exhibits a success message.
st.error(): This function is used to demonstrate an error message. 
st.warning(): This function is utilized to display a warning message.
st.info(): This function reveals an informational message.
st.exception(): This function is operated to show an exception message.

import streamlit as st

st.success("You did it!")
st.error("Error occurred")
st.warning("This is a warning")
st.info("It's easy to build a Streamlit app")
st.exception(RuntimeError("RuntimeError exception"))


Display progress and status with Streamlit 2

8-Sidebar and container

We can additionally create a sidebar or a container on your page to organize your app. The hierarchy and arrangement of pages on your app can have a huge impact on your user experience. Organizing your content allows visitors to understand your site better and navigate it easier. It also helps them find what they are looking for faster and increases the likelihood that they will return. 

Passing an element to st.sidebar() will pin this element to the left, allowing users to focus on the content making your app more organized and easier to deal with.

import streamlit as st

st.sidebar.title("This is writter inside sidebar")
st.sidebar.button("Click")
st.sidebar.radio("Pick your gender",["Male","Female"])

Sidebar

Container

st.container() is employed to construct an invisible container where you can put elements creating a useful arrangement and hierarchy.

import streamlit as st

container = st.container()
container.write("This is written inside the container")
st.write("This is written outside the container")

Container

import streamlit as st
import numpy as np

with st.container():
    st.write("This is inside the container")

    st.bar_chart(np.random.randn(50, 3))

st.write("This is outside the container")

9-Data Visualization

Data visualization simplifies telling stories by curating data into a more straightforward format, highlighting the trends and outliers. A good visualization conveys a narrative, removing the noise from data and emphasizing the valuable information. However, it is way more complicated than just dressing up a graph to make it look better or slapping on an infographic's "info" part.
Effective data visualization is a delicate balancing act between form and function. A plain graph could be too boring to draw attention or communicate a powerful message, whereas the most stunning visualization could fail to deliver the right idea. The data and visuals need to work together. However, combining great analysis with excellent storytelling is an art. 

st.pyplot(): This function is used to display a matplotlib.pyplot figure.

import streamlit as st
import matplotlib.pyplot as plt
import numpy as np

rand = np.random.normal(1, 2, size=20)
fig, ax = plt.subplots()
ax.hist(rand, bins=15)
st.pyplot(fig)

This function is used to display a line chart.

st.line_chart(): This function is utilized to show a line chart.

import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10, 2), columns=['x', 'y'])
st.line_chart(df)

This function is used to display a bar chart.

st.bar_chart(): This function is employed to exhibit a bar chart.

import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10, 2), columns=['x', 'y'])
st.bar_chart(df)

This function is used to display an area chart.

st.map(): This function displays maps in the app. However, it requires the values of latitude and longitude which cannot be null/NA.

import pandas as pd
import numpy as np
import streamlit as st

df = pd.DataFrame(
    np.random.randn(500, 2) / [50, 50] + [37.76, -122.4], columns=['lat', 'lon']
)
st.map(df)

Display maps with Streamlit 1

10-Display a DataFrame

st.dataframe(): This command shows a DataFrame as an interactive table. It works with a variety of collection-like and DataFrame-like object types.

import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(50, 20), columns=("col %d" % i for i in range(20)))

st.dataframe(df)  # Same as st.write(df)

You can also pass a Pandas Styler object to change the style of the rendered DataFrame:

import streamlit as st
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(10, 20), 
                  columns=("col %d" % i for i in range(20)))

st.dataframe(df.style.highlight_max(axis=0))


Summary

In this article, after introducing the Streamlit web framework, I demonstrated how to install Streamlit and run the application. We also explored some basic commands, widgets, and data visualization functionality.

In my next article, we will create a Streamlit web application to connect to the IRIS dataset and explore advanced concepts of Streamlit together.

Thanks

1 Comentario
Comentarios (1)2
Inicie sesión o regístrese para continuar