<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Carlos Suarez on Medium]]></title>
        <description><![CDATA[Stories by Carlos Suarez on Medium]]></description>
        <link>https://medium.com/@smca310777?source=rss-c65b400f91c4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*fvlDVq6nxyGJcTb8iLEfqw.jpeg</url>
            <title>Stories by Carlos Suarez on Medium</title>
            <link>https://medium.com/@smca310777?source=rss-c65b400f91c4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:27:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smca310777/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Snowpark Container Service ❄️]]></title>
            <link>https://medium.com/snowflake/snowpark-container-service-%EF%B8%8F-ec640368a091?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec640368a091</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[containers]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Fri, 24 May 2024 14:02:22 GMT</pubDate>
            <atom:updated>2024-05-24T14:02:22.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Audio to Text (Whisper) + API (FastAPI) + Streamlit App</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFqXr5aMWOxPuXar817sOQ.png" /></figure><p>Todays world is based mostly in audio conversation, it’s easy to communicate over the services, but listening high number of audio to extract information can be a big challenge. Imagine an Data App that you only load audio files and it can convert it into text and request it via API, sounds complex but using Snowpark Container Services makes easy to to containerize LLM (OpenAI Whisper) +API (FastAPI) + Streamlit, you will require:</p><ul><li>Docker Desktop</li><li>Snowflake account with SPCS (Snowpark Container Services) enabled</li><li>Python 3.10</li><li>Hugging Face account</li></ul><p>let’s build our own one!</p><p>Note: make sure all this following files are organized into your local computer as follow , first create API and APP directories, then the files we’re going to filling with instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ZVCJkc-PvHEncMH5U-S5w.png" /></figure><h4>Create Snowflake Objects</h4><p>In a Snowflake SQL Worksheet:</p><pre>-- Create Snowflake object<br>use role accountadmin;<br>create or replace database audio;<br><br>-- Compute to process data <br>create or replace  warehouse audio_wh<br>warehouse_size = &#39;X-SMALL&#39;<br>auto_suspend = 60<br>auto_resume = true<br>initially_suspended = true;<br><br><br>-- Activate Objects<br>use database audio;<br>use schema public;<br>use warehouse audio_wh;</pre><h4>Container Objects</h4><p>Let’s create a compute pool (GPU), integration between containers and some stages(Audio files, LLM Whisper model, and container definition)</p><pre>-- Compute pool to run containers<br>create compute pool audio_pool<br>  MIN_NODES = 1<br>  MAX_NODES = 1<br>  INSTANCE_FAMILY = GPU_NV_S;<br><br><br>-- MUST BE RUN BY ACCOUNTADMIN to allow browsing to containers via HTTPS <br>create security integration snowservices_ingress_oauth<br>  TYPE=oauth<br>  OAUTH_CLIENT=snowservices_ingress<br>  ENABLED=true;<br><br>  <br>-- Stage for Audio Files<br>create stage if not exists audiofiles <br>DIRECTORY =(ENABLE=true)<br>ENCRYPTION = (TYPE=&#39;SNOWFLAKE_SSE&#39;);; <br><br>-- Stage to store LLM Wispher <br>create stage if not exists AUDIO.PUBLIC.MODELS<br> DIRECTORY = (ENABLE = TRUE)<br> ENCRYPTION = (TYPE=&#39;SNOWFLAKE_SSE&#39;);<br><br>-- Stage to store yaml specs<br>create stage if not exists specs<br> DIRECTORY = (ENABLE = TRUE)<br> ENCRYPTION = (TYPE=&#39;SNOWFLAKE_SSE&#39;);<br><br>-- Image registry<br>CREATE OR REPLACE IMAGE REPOSITORY images;</pre><h4>Security Integration to HuggingFace</h4><p>Because we’re going to download from HuggingFace repo (first time only) the LLM (Whisper) model, we must create a security integration to allow Snowflake go/accept secure connection from container</p><pre>-- Secure Network rule for Huggingface<br>CREATE OR REPLACE NETWORK RULE hf_network_rule<br>  MODE = EGRESS<br>  TYPE = HOST_PORT<br>  VALUE_LIST = (&#39;huggingface.co&#39;, &#39;cdn-lfs.huggingface.co&#39;);<br><br>-- Secure Integration<br>CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION whisper_access_integration<br>    ALLOWED_NETWORK_RULES = (hf_network_rule)<br>    ENABLED = true;</pre><h4>Checking on Objects</h4><pre>-- Describe object<br>describe SECURITY INTEGRATION snowservices_ingress_oauth;<br>describe compute pool audio_pool;<br>show compute pools;<br>show IMAGE REPOSITORIES in schema;<br>show stages;</pre><p>Create an user (audiouser) who will be login on Streamlit App running on the container</p><pre>--Role definition<br>create role audio_role;<br><br>--Create user for external access for Data App<br>create user audiouser PASSWORD=&#39;audio2024&#39; DEFAULT_ROLE = audio_role MUST_CHANGE_PASSWORD = FALSE;<br>GRANT ROLE audio_role TO USER audiouser;<br><br></pre><p>Grants privileges to user (audio_role role) for Snowflake objects</p><pre>-- Objects Privileges <br>grant role audio_role TO USER &lt;your username&gt;;<br><br>grant usage on warehouse audio_wh to role audio_role;<br>grant usage on database audio to role audio_role;<br>grant all privileges on schema public to role audio_role;<br>grant all privileges on table audiotext to role audio_role;<br><br>grant read,write on stage audiofiles to role audio_role;<br>grant read,write on stage specs to role audio_role;<br>grant read,write on stage AUDIO.PUBLIC.MODELS to role audio_role;<br>grant read,write on image repository images to role audio_role;<br><br>grant usage on compute pool audio_pool to role audio_role;<br>grant monitor on compute pool audio_pool to role audio_role;<br><br>grant create streamlit on schema audio.public to role audio_role;<br><br>grant BIND SERVICE ENDPOINT on account to role audio_role;<br><br><br>GRANT USAGE ON NETWORK RULE hf_network_rule TO ROLE audio_role;<br>GRANT USAGE ON INTEGRATION whisper_access_integration TO ROLE audio_role;</pre><h3>Container Whisper+FastAPI</h3><p>(api/Dockerfile) <br>Docker file to get Pytorch, install libraries for Hugging Face and python requirements like fastapi(app/requerimientos.txt file)</p><pre>FROM nvcr.io/nvidia/pytorch:24.01-py3<br><br>RUN pip3 install --upgrade pip &amp;&amp; pip3 install accelerate transformers huggingface_hub<br><br>WORKDIR /whisperapp<br><br>COPY requerimientos.txt requerimientos.txt<br>COPY fastapi_app.py fastapi_app.py<br>RUN pip3 install -r requerimientos.txt<br>RUN apt-get update &amp;&amp; apt-get install -y ffmpeg<br><br>EXPOSE 8000<br><br>ENV HUGGING_FACE_MODEL=openai/whisper-large<br>                       <br>CMD [&quot;uvicorn&quot;, &quot;fastapi_app:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8000&quot;]</pre><p>Requirements (api/requerimientos.txt)</p><pre>fastapi<br>aiofiles<br>python-multipart<br>uvicorn<br>pydantic<br>pydub</pre><p>YAML file (api/api.yml)</p><pre>spec:<br>  containers:<br>    - name: api<br>      image: &lt;your image repository url&gt;/api<br>      resources:<br>        requests:<br>          nvidia.com/gpu: 1<br>        limits:<br>          nvidia.com/gpu: 1<br>      env:<br>        HF_TOKEN: &lt;your huggingface access token&gt;<br>        NUM_GPU: 1<br>        MAX_GPU_MEMORY: 64Gib<br>      volumeMounts:<br>      - name: whisper-models<br>        mountPath: /whisper_models<br>    - name: app<br>      image: &lt;your image repository url&gt;/app<br>  endpoints:<br>    - name: api<br>      port: 8000<br>      public: false<br>    - name: app<br>      port: 8080<br>      public: true<br>  volumes:<br>    - name: whisper-models<br>      source: &quot;@AUDIO.PUBLIC.MODELS&quot;<br>      uid: 1000<br>      gid: 1000<br>  networkPolicyConfig:<br>    allowInternetEgress: true</pre><p>App (api/fast_app.py)</p><pre>import torch<br>from fastapi import FastAPI, File, UploadFile, HTTPException<br>from fastapi.responses import JSONResponse, RedirectResponse<br>from typing import List <br>from tempfile import NamedTemporaryFile<br>from pydantic import BaseModel<br>from pydub import AudioSegment<br>from io import BytesIO<br>import numpy as np<br>import os<br><br># Checking if NVIDIA GPU is available<br>torch.cuda.is_available()<br>DEVICE = &quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br><br><br>#Env variables<br>hfm = os.getenv(&#39;HUGGING_FACE_MODEL&#39;)<br>hf_token = os.getenv(&quot;HF_TOKEN&quot;)<br>os.environ[&#39;HF_HOME&#39;] = &#39;/whisper_models&#39;<br><br><br><br>#Check NVIDIA is available<br>DEVICE = &quot;cuda:0&quot; if torch.cuda.is_available() else &quot;cpu&quot;<br>torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32<br><br>#Load Whisper model from Huggingface Hub first time, else load from stage<br>pipe = pipeline(<br>    &quot;automatic-speech-recognition&quot;,<br>    model=hfm,<br>    model_kwargs={&quot;torch_dtype&quot;: torch_dtype},<br>    device_map=&quot;auto&quot;,<br>    token=hf_token<br>)<br><br>#FastAPI service<br>app = FastAPI()<br><br>#Receive from Streamlit App after uploaded file<br>@app.post(&#39;/upload/&#39;)<br>async def process_local_audio_file(upload_file: UploadFile = File(...)) -&gt; None:<br>    results = []<br>    try:<br>        # Extract the audio bytes from the uploaded file<br>        audio_bytes = await upload_file.read()<br><br>        # Use pydub to handle different audio formats and convert audio<br>        audio = AudioSegment.from_file(BytesIO(audio_bytes))<br>        audio = audio.set_channels(1).set_frame_rate(16000)<br><br>        # Convert the audio to a raw data byte string<br>        raw_data = audio.raw_data<br><br>        # Convert the raw data into a NumPy array for processing<br>        audio_np = np.frombuffer(raw_data, dtype=np.int16).astype(np.float32)<br>        audio_np /= np.iinfo(np.int16).max  # Normalize to range [-1.0, 1.0]<br><br>        # Transcribe the audio using the Whisper model<br>        result = pipe(audio_np)<br><br>        # Update the task status with the transcription result<br>        results.append({<br>            &#39;filename&#39;:upload_file.filename,<br>            &#39;transcript&#39;: result[&#39;text&#39;]<br>        })<br>        return JSONResponse(content={&#39;results&#39;: results})<br>    <br>    except Exception as e:<br>        # Handle any errors that occur during the processing<br>        results.append({<br>            &quot;status&quot;: &quot;failed&quot;, <br>            &quot;error&quot;: str(e)<br>        })<br>        return JSONResponse(content={&#39;results&#39;: results})</pre><p>Build, tag and push into Snowflake image registry, this file is inside on “api” directory then run</p><pre>docker login &lt;your registry url&gt; -u &lt;your username&gt;<br><br>docker build --rm --platform linux/amd64 -t api .<br><br>docker tag api &lt;your image repository url&gt;/api<br><br>docker push &lt;your image repository url&gt;/api</pre><h3>Container Streamlit App</h3><p>(app/Dockerfile)<br>Docker file to get Python(3.10) and python requirements like Streamlit (api/requerimientos.txt)</p><pre>FROM python:3.10<br><br>WORKDIR /app<br>ADD ./requerimientos.txt /app/<br><br>RUN pip install --no-cache-dir -r requerimientos.txt<br>RUN pip uninstall oscrypto -y<br>RUN pip install oscrypto@git+https://github.com/wbond/oscrypto.git@d5f3437ed24257895ae1edd9e503cfb352e635a8<br>ADD ./streamlit_app.py /app<br><br>EXPOSE 8080<br><br>ENV STREAMLIT_GLOBAL_DISABLE_WATCHDOG_WARNING=1<br>CMD [&quot;streamlit&quot;, &quot;run&quot;, &quot;streamlit_app.py&quot;,&quot;--server.port&quot;, &quot;8080&quot;]</pre><p>Requirements (app/requerimientos.txt)</p><pre>streamlit<br>snowflake-snowpark-python[pandas]<br>python-dotenv<br>requests</pre><p>Streamlit App(app/streamlit_app.py)</p><pre>import streamlit as st<br>import requests<br>import json<br><br><br>st.title(&quot;Simple Whisper App&quot;)<br><br><br>api_server = &quot;http://localhost:8000/upload&quot;<br><br>with st.spinner(&#39;Wait for it...&#39;):<br>    uploaded_file = st.file_uploader(&quot;Choose a Audio file&quot;)<br>    if uploaded_file:<br>        st.success(&#39;Done!&#39;)<br>        if extraer_btn := st.button(&quot;Extraer&quot;):<br>            files = {&quot;upload_file&quot;: uploaded_file.getvalue()}<br>            response = requests.post(api_server, files=files)<br>            st.write(response.json())</pre><p>Build, tag and push into Snowflake image registry</p><pre>docker login &lt;your registry url&gt; -u &lt;your username&gt;<br><br>docker build --rm --platform linux/amd64 -t app .<br><br>docker tag api &lt;your image repository url&gt;/app<br><br>docker push &lt;your image repository url&gt;/app</pre><h4>Container Services Up</h4><p>We need first to upload our api/api.yml file to the specs stage in Snowflake</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*devlY-eE0vEGOQsUCX7tRw.png" /></figure><p>With that, using our Snowflake SQL Worksheet we can activate the container.</p><pre>-- Activate container<br>use role audio_role;<br>use database audio;<br>use schema public;<br>use warehouse audio_wh;<br><br><br>--Create LLM/API container  (wait for download model)<br><br>-- Whisper LLM<br>create service whisper_service<br>in compute pool audio_pool<br>from @specs<br>spec=&#39;api.yaml&#39;<br>MIN_INSTANCES=1<br>MAX_INSTANCES=1<br>EXTERNAL_ACCESS_INTEGRATIONS=(WHISPER_ACCESS_INTEGRATION);</pre><p>Then Snowflake will create the service, when ready you can ask for the endpoint (public) where de Streamlit App is running like</p><pre>-- show endpoint (public)<br>show endpoints IN SERVICE whisper_service;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpNdeHhuyOQPvvLbq36ZTQ.png" /></figure><p>Finally on an Web browser you can reach the endpoint (URL) to login with the user created (audiouser) and upload an WAV/mp3 audio. file and get the extrext text</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kycn0FKi1_kO6eGG9Y7LxA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec640368a091" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/snowpark-container-service-%EF%B8%8F-ec640368a091">Snowpark Container Service ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Cortex-RAG from External API ❄️]]></title>
            <link>https://medium.com/snowflake/snowflake-cortex-rag-from-external-api-%EF%B8%8F-abc493bc155f?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/abc493bc155f</guid>
            <category><![CDATA[snowflake-cortex]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[snowpark]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Tue, 21 May 2024 14:02:26 GMT</pubDate>
            <atom:updated>2024-05-21T14:02:26.854Z</atom:updated>
            <content:encoded><![CDATA[<p>External API Integration + Vector Type + LLM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MR8ScBQUgszD9ggqGahrPA.png" /></figure><p>Create a fast and quick RAG functionality -Retrieval Augmented Generation- by reading data from external Web Service (API) over a secure integration from inside Snowflake, with that store the learning corpus as RAW data to be convert -using Snowflake Artic LLM - into embedding to search for similarity to “talk” with your own data.<br>We will connect to Ninja API via access token to get information about Historical Characters service.</p><h4>Create Snowflake Objects</h4><pre>use role accountadmin;<br><br>create database HISPERSON;<br><br>create or replace warehouse python_wh<br>warehouse_size = &#39;X-SMALL&#39;<br>auto_suspend = 60<br>auto_resume = true<br>initially_suspended = true;</pre><h4>Create External Access Integration</h4><p>We will use our API Access Token form API Provider (Ninja API) to stage it as “secret” data and assign a Network rule to indicate Snowflake egress rule to API endpoint (in this case <em>api.api-ninjas.com</em>)</p><pre>CREATE NETWORK RULE ninja_rule<br>  TYPE = HOST_PORT<br>  MODE = EGRESS<br>  VALUE_LIST = (&#39;api.api-ninjas.com&#39;);<br><br><br> CREATE or REPLACE SECRET ninja_api_key<br>    TYPE = password<br>    USERNAME = &#39;NOT_USED&#39;<br>    PASSWORD = &#39;&lt;Your Access Token&gt;&#39;;<br><br><br><br>CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION ninja_integration<br>  ALLOWED_NETWORK_RULES = (ninja_rule)<br>  ALLOWED_AUTHENTICATION_SECRETS = (ninja_api_key)<br>  ENABLED = true;</pre><h4>Create UDF(User Defined Function)</h4><p>The historical_figure function will receive name of the character as parameter to perform request to API endpoint using the secret and external access integration already, as reponse we will send out the JSON structure of data</p><pre>CREATE OR REPLACE FUNCTION historical_figure(person STRING)<br>RETURNS STRING<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.10<br>HANDLER = &#39;get_history&#39;<br>EXTERNAL_ACCESS_INTEGRATIONS = (ninja_integration)<br>PACKAGES = (&#39;requests&#39;)<br>SECRETS = (&#39;api_key&#39; = HISPERSON.public.ninja_api_key)<br>AS<br>$$<br>import requests<br>import _snowflake <br><br>def get_history(person):<br>    api_url = &#39;https://api.api-ninjas.com/v1/historicalfigures?name={}&#39;.format(person)<br>    api_key = _snowflake.get_username_password(&#39;api_key&#39;).password<br>    response = requests.get(api_url, headers={&#39;X-Api-Key&#39;: api_key})<br>    if response.status_code == requests.codes.ok:<br>        return response.text<br>    else:<br>        return &quot;Error: &quot; + response.status_code + &quot;:&quot; + response.text<br>$$;</pre><h4>Checking the UDF</h4><p>from here you can use the historial_figure UDF to get data form external API Service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RKd4yu1pOrmg6KzqMokVkQ.png" /></figure><h4>Snowflake Notebooks</h4><p>From here we can use Snowflake Notebook, in case that some packages are required you can add them (1) and select the version(2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7KG65zhFwan6LDv_S0w7xw.png" /></figure><p>Add the Snowpark functions (lit, parse_json, col and concat) and get_active.session method in order to process transformation and session object respectively</p><pre># Import paquetes Python<br>import streamlit as st<br>from snowflake.snowpark.functions import lit,parse_json,col, concat<br>from snowflake.snowpark.context import get_active_session<br><br>session = get_active_session()</pre><p>Then take response(JSON) from API call and perform tranformation to get specific keys values, and finally store on a RAW_DATA table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*pPqIhdjq0xO-wQ30Wtq_0g.png" /></figure><pre>query = &quot;create or replace table RAW_DATA (texto STRING)&quot;<br>session.sql(query).collect()<br><br>query = &quot;select HISTORICAL_FIGURE(&#39;Napoleon Bonaparte&#39;) as RAW&quot;<br>df = session.sql(query)<br>json_data = df.select(parse_json(df[&#39;RAW&#39;]).alias(&quot;JSON_DATA&quot;))<br><br>nombre_tabla = &#39;RAW_DATA&#39;<br>database = session.get_current_database()<br>schema = session.get_current_schema()<br>contexto = ([database, schema, nombre_tabla])<br>      <br>text_df = json_data.select(<br>   concat(col(&quot;JSON_DATA&quot;)[0][&quot;name&quot;],lit(&quot; &quot;) ,col(&quot;JSON_DATA&quot;)[0][&quot;title&quot;],lit(&quot; &quot;) ,col(&quot;JSON_DATA&quot;)[0][&quot;info&quot;][&quot;born&quot;])<br>)<br><br>text_df.show()<br><br>text_df.write.mode(&quot;append&quot;).save_as_table(contexto)</pre><h4>Create a Embedding Store (Vector Type)</h4><p>Is time to convert RAW text into numerical vector type, fist we need to create a Vector Type storage using Snowflake Artic LLM using Cortex to Embed (EMBED_TEXT_768) text into vector numerical information, then we can perform a similarity taking an input (question) and check de distance (VECTOR_L2_DISTANCE)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpG-oAa_bH-k2yFdtwCxWA.png" /></figure><pre>create or replace table VECTOR_STORE as<br>select <br> texto as input,<br> SNOWFLAKE.CORTEX.EMBED_TEXT_768(&#39;snowflake-arctic-embed-m&#39;,input) as embeddings from raw_data;<br><br>select input from VECTOR_STORE <br>order by VECTOR_L2_DISTANCE(<br>SNOWFLAKE.CORTEX.EMBED_TEXT_768(&#39;snowflake-arctic-embed-m&#39;,&#39;Where Napoleon was born?&#39;), embeddings) limit 1;</pre><p>And naw we can add Snowflake Artic LLM via Cortex to complete a response, notice how Artic if fixing the response, Napoleón vs Pierre Napoleón, but is taking vector type data to perform de response (RAG)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AQsDLHJn3bE2Kf30FuKuNA.png" /></figure><pre>SELECT snowflake.cortex.complete(<br>    &#39;mistral-7b&#39;, CONCAT( <br>    &#39;Answer the question based on the context. Be concise.&#39;,&#39;Context: &#39;,<br>        (<br>            SELECT input FROM VECTOR_STORE<br>            ORDER BY vector_l2_distance(<br>            snowflake.cortex.embed_text(&#39;snowflake-arctic-embed-m&#39;, <br>            &#39;Where Napoleon was born?&#39;<br>            ), embeddings<br>            ) LIMIT 1<br>        ),<br>        &#39;Question: &#39;, <br>        &#39;Where Napoleon was born?&#39;,<br>        &#39;Answer: &#39;<br>    )<br>) as response;</pre><h4>Streamlit App</h4><p>You can build a Streamlit App to add UX to final users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnktX_Zz7kasURT5NuGwiA.png" /></figure><pre>import streamlit as st <br>from snowflake.snowpark.context import get_active_session<br><br>session = get_active_session()<br><br>st.title(&quot;Ask Your Data Anything :snowflake:&quot;)<br>st.write(&quot;&quot;&quot;Built using end-to-end RAG in Snowflake with Cortex functions.&quot;&quot;&quot;)<br><br>model = st.selectbox(&#39;Select your model:&#39;,(&#39;mistral-7b&#39;,&#39;llama3-8b&#39;,&#39;snowflake-arctic&#39;))<br>prompt = st.text_input(&quot;Enter prompt&quot;, placeholder=&quot;What makes time perceived to be slower?&quot;, label_visibility=&quot;collapsed&quot;)<br><br>quest_q = f&#39;&#39;&#39;<br>SELECT snowflake.cortex.complete(<br>    &#39;{model}&#39;, CONCAT( <br>    &#39;Answer the question based on the context. Fix any error.&#39;,&#39;Context: &#39;,<br>        (<br>            SELECT input FROM VECTOR_STORE<br>            ORDER BY vector_l2_distance(<br>            snowflake.cortex.embed_text(&#39;snowflake-arctic-embed-m&#39;, <br>            &#39;{prompt}&#39;<br>            ), embeddings<br>            ) LIMIT 1<br>        ),<br>        &#39;Question: &#39;, <br>        &#39;{prompt}&#39;,<br>        &#39;Answer: &#39;<br>    )<br>) as response;<br>&#39;&#39;&#39;;<br><br>if prompt:<br>    df_query = session.sql(quest_q).to_pandas()<br>    st.write(df_query[&#39;RESPONSE&#39;][0])</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abc493bc155f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/snowflake-cortex-rag-from-external-api-%EF%B8%8F-abc493bc155f">Snowflake Cortex-RAG from External API ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LangChain + Snowpark + OpenAI in Streamlit ❄️]]></title>
            <link>https://medium.com/snowflake/langchain-snowpark-openai-in-streamlit-%EF%B8%8F-33a9c019dc24?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/33a9c019dc24</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[snowpark]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Fri, 19 Apr 2024 01:17:58 GMT</pubDate>
            <atom:updated>2024-04-19T03:59:56.277Z</atom:updated>
            <content:encoded><![CDATA[<p>Coding Data App for External LLM</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tu53g2-eRp_bYwj9kR-FAQ.png" /></figure><p>An Snowflake portability to code inside form the suecure data zone to external services, in this case, OpenAI services, to extend functionality with single dev environment. In this escenario OpenAI allow cross-services vua API endpoint. So lets haking!</p><h4>Snowflake Objects</h4><p>Creating external access secret and external access network rules to securely connect to OpenAI LLM from Snowflake SQL Worksheet</p><pre>use role accountadmin;<br><br>create database openai;<br>create schema trainer;<br><br>use database openai;<br>use schema trainer;<br>use warehouse python_wh;<br><br><br>CREATE OR REPLACE NETWORK RULE openai_api_network_rule<br>  MODE = EGRESS<br>  TYPE = HOST_PORT<br>  VALUE_LIST = (&#39;api.openai.com&#39;);<br><br><br>  <br>CREATE OR REPLACE SECRET openai_api_key<br>    TYPE = password<br>    USERNAME = &#39;NOT_USED&#39;<br>    PASSWORD = &#39;&lt;your API OpenAI token&gt;&#39;;<br><br><br>CREATE OR REPLACE EXTERNAL ACCESS INTEGRATION openai_api_access_integration<br> ALLOWED_NETWORK_RULES = (openai_api_network_rule)<br> ALLOWED_AUTHENTICATION_SECRETS = (openai_api_key)<br> ENABLED = true;</pre><h4>Governance Over Function ( role based)</h4><p>This will allow to assign in a controlled way al process that user with the role RUN_AGENT can perform inside Snowflake</p><pre>CREATE OR REPLACE ROLE RUN_AGENT;<br>GRANT USAGE ON DATABASE openai TO ROLE RUN_AGENT;<br>GRANT USAGE ON SCHEMA trainer TO ROLE RUN_AGENT;<br>GRANT USAGE ON WAREHOUSE python_wh TO ROLE RUN_AGENT;<br>--grant en la función <br>GRANT USAGE ON FUNCTION openai_chat_completion(string) TO ROLE RUN_AGENT;<br>GRANT USAGE ON SCHEMA public TO ROLE RUN_AGENT;</pre><h4>UDF(User Defined Function)</h4><p>Creation of UDF(Python) to standardize and encapsulate the internal process of the LangChain framework that processes data and messages for conversation with OpenAI.<br>Inside de UDF we can use al Snowflake object for Secreat Network rule and External Access Network</p><p>The <strong>openai_chat_completion(prompt STRING)</strong> function generates the tokenized secure connection and can process the prompting and completion (call-back) response from OpenAI with Python and LangChain.<br>The function will tranlate from English to Spanish using OpenAI Model</p><pre>CREATE OR REPLACE FUNCTION openai_chat_completion(prompt STRING)<br>RETURNS STRING<br>LANGUAGE PYTHON<br>RUNTIME_VERSION = 3.8<br>HANDLER = &#39;get_completion&#39;<br>EXTERNAL_ACCESS_INTEGRATIONS = (openai_api_access_integration)<br>PACKAGES = (&#39;langchain&#39;,&#39;openai&#39;)<br>SECRETS = (&#39;api_key&#39; = OPENAI.public.openai_api_key)<br>AS<br>$$<br>import json<br>import _snowflake<br>from langchain.chat_models import ChatOpenAI<br>from langchain.prompts import PromptTemplate<br>from langchain.prompts.chat import ChatPromptTemplate,SystemMessagePromptTemplate,HumanMessagePromptTemplate<br>from langchain.chains import LLMChain<br><br>api_key = _snowflake.get_username_password(&#39;api_key&#39;).password or &quot;fake-password&quot;<br>llm = ChatOpenAI(openai_api_key=api_key)<br><br><br>def template_asistant():<br>    template = &quot;You are a helpful assitant that translate {input_language} to {output_language}.&quot;<br>    system_message_prompt = SystemMessagePromptTemplate.from_template(template=template)<br>    human_template = &quot;{text}&quot;<br>    human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)<br>    chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt,human_message_prompt])<br>    #chat_prompt.format_messages()<br>    return chat_prompt <br><br><br>def get_completion(texto: str):<br>    llm = ChatOpenAI(openai_api_key=api_key)<br>    chat_prompt = template_asistant()<br>    chain = LLMChain(llm=llm,prompt=chat_prompt)<br>    res = chain.run(input_language=&quot;English&quot;, output_language=&quot;Spanish&quot;, text=texto)<br>    <br>    return res <br>$$;</pre><p>You can assign the RUN_AGENT role to different users, to test the UDF function within Snowflake SQL, time to switch to test the UDF</p><pre>use role RUN_AGENT;<br>use database openai;<br>use schema trainer;<br>use warehouse python_wh;<br><br>select OPENAI_CHAT_COMPLETION(&#39;I love programing!’);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tiEtaYb2hssrF7Yq79CSWQ.png" /><figcaption>Test UDF Fucntion</figcaption></figure><h4>Streamlit Data App</h4><p>We can create a SiS Data App that take advantage of UDF function to extend UX experience to users</p><pre># Import python packages<br>import streamlit as st<br>from snowflake.snowpark.context import get_active_session<br><br><br><br># App Title and Subtitle <br>st.title(&quot;LangChain/OpenAI demo&quot;)<br>st.write(<br>    &quot;&quot;&quot;Importando una función ya creada en  **Snowsight,** y ejecutada en Streamlit<br>    &quot;&quot;&quot;<br>)<br><br># get current session<br>session = get_active_session()<br><br># Python method to call UDF <br>def openai(texto:str):<br>    query = f&quot;SELECT OPENAI_CHAT_COMPLETION(&#39;{texto}&#39;) as RESP&quot;<br>    resp =session.sql(query).collect()<br>    return resp[0][&#39;RESP&#39;]<br><br><br>#Run App reauesting Text input <br>input = st.text_input(&#39;Texto a traducir desde función OPENAI_CHAT_COMPLETION() &#39;)<br>if input:<br>    tran = openai(input)<br>    if tran == None:<br>        st.write(&#39;No se entiende!&#39;)<br>    else:<br>        with st.spinner(&#39;Traduciendo...&#39;):<br>            st.write(&quot;### Traducción&quot;)<br>            st.write(tran)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4iyLHSCC3-zFzW8aEm9Gw.png" /></figure><p>From here you can improve or create deep UDF request from Snowflake to OpenAI, even using data staged inside Snowflake in a secure way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33a9c019dc24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/langchain-snowpark-openai-in-streamlit-%EF%B8%8F-33a9c019dc24">LangChain + Snowpark + OpenAI in Streamlit ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Document AI❄️]]></title>
            <link>https://medium.com/@smca310777/snowflake-document-ai-%EF%B8%8F-a28f7416c858?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/a28f7416c858</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 13:02:05 GMT</pubDate>
            <atom:updated>2024-04-12T13:02:05.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Feature Extraction from Unstructured Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpvDNlVlUbTcBBpXt2VFmw.png" /><figcaption>Snowflake Document AI</figcaption></figure><h4>Feature Extraction</h4><p>In order to extract features, Document AI apply Snowflake ML framework which use LLM functions based on natural language conversation to identify specific data by making question to the document, train a model (fine running and reinforcement ) then finally apply the trained model to extra over a large number on files and place data in Snowflake object (table)</p><ul><li>Grant SNOWFLAKE.DOCUMENT_INTELLIGENCE_CREATOR to the role that you want to use</li><li>Set up a default virtual warehouse, database, schema and role to the role that you want to use</li><li>Grant virtual warehouse usage and operating privileges to the role that you want to use</li><li>Ensure that the role can access the default database and schema</li></ul><h4>Setting Document AI</h4><pre>use role accountadmin;<br>create database docai_db;<br><br>create or replace warehouse docai_wh <br>WAREHOUSE_SIZE=&#39;X-SMALL&#39; <br>WAREHOUSE_TYPE=&#39;STANDARD&#39;<br>AUTO_SUSPEND=600<br>AUTO_RESUME=TRUE;<br><br>use database docai_db;<br>use schema public;<br>use warehouse docai_wh;<br><br>create role docai_role;<br><br>GRANT ROLE docai_role TO  USER &lt;your_user&gt;;<br><br>-- DocAI Grants<br>GRANT DATABASE ROLE SNOWFLAKE.DOCUMENT_INTELLIGENCE_CREATOR TO ROLE docai_role;<br>ALTER user csuarez set DEFAULT_WAREHOUSE=docai_wh DEFAULT_ROLE=docai_role DEFAULT_NAMESPACE=docai_db.public;<br>GRANT USAGE, OPERATE ON WAREHOUSE docai_wh TO ROLE docai_role;<br>GRANT ALL ON DATABASE docai_db TO ROLE docai_role;<br>GRANT ALL ON SCHEMA docai_db.public TO ROLE docai_role;</pre><h4><strong>Document AI / Adding files</strong></h4><p>To access Document AI, click on (1) “Document AI” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9eVE2cmY_LZCRfXAgJRv0A.png" /></figure><p>This will present a new tab on the browser, then (1) create a new project by click on “Add Project” button, a pop-up window to insert (2) project name and finally click (3) next button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KYRh3vr8wiTOMHbqz8859w.png" /></figure><p>Then add file documents to the project in order to identify textual information, in this case we will add PDF files, click on (1) “Documents” tab section, then on (2) ”Add Documents” button, a pop-over window is present, then click on (3) to select local files to be uploaded and finally (4) click “Summit” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVPEoB6WKrrX9GL1HYcgOw.png" /></figure><p>Then, on the (1) “Documents” tab section, all files are uploaded, you must wait until Snowflake Document AI (2) update the “Status” column as “Done”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsKFp1pjG9YHmkC6lroyrw.png" /></figure><h4><strong>Document AI / Training</strong></h4><p>After loading at least 10/20 documents, click on (1) Training tab section, you will see the current document on the right pane (2) l, then click on (3) “+ Add Question” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7UKcEX-zj_oyoGYXZJIFQ.png" /></figure><p>On the same (1) Training section, click on “Add question” and type down your question (even in English Language), then add a identifier to assign the result of the question, you can add more question by click on (3) “+ Add Question”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KDM4KsbfOgQoaQQXLsABeg.png" /></figure><p>Finally, on the same (1) Training section, you can review the value of each question (2,3,4), then click on (5) “Start training” button to allow Model be trained, in order to provide the next document you must click on the (6) next button no navigate on all Training PDF (10 or 20), and review on (7) the Model quality during the training, you can “stop training” any moment by click on the button with the same name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YaisyBJD3vL83gheOthYRw.png" /></figure><h4><strong>Snowflake Feature Extraction</strong></h4><p>Activate Snowflake Objects:</p><pre>use role accountadmin;<br>use database docai_db;<br>use schema public;<br>use warehouse docai_wh;</pre><p>Create named stage where all documents PDF will be stored to extract using:</p><pre>CREATE STAGE ARCHIVOS<br>  DIRECTORY = (enable = true)<br>  ENCRYPTION = (type = ‘snowflake_sse&#39;);</pre><p>Grant permission to role on stage:</p><pre>GRANT read,write on stage ARCHIVOS to role docai_role;</pre><p>Switch to docai_role:</p><pre>use role docai_role;<br>use database docai_db;<br>use schema public;<br>use warehouse docai_wh;</pre><p>Use the (1) !PREDICT function over the DocAI project, in this case “facturas” as project name, to extract data(value) as was trained on (2) specific identifiers (3)</p><pre>SELECT facturas!PREDICT(GET_PRESIGNED_URL(@ARCHIVOS, RELATIVE_PATH), 1) as Extracted_data FROM DIRECTORY(@ARCHIVOS);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4jn2dljlRyBqdNQs2oDd5w.png" /></figure><p>Create Snowflake object to store PDF filename and Extraction data (as Variant type):</p><pre>create table facturas_tbl(<br>file_name string, <br>file_data variant<br>);</pre><p>Insert extracted data on Snowflake table object:</p><pre>INSERT INTO facturas_tbl(file_name,file_data)<br>SELECT <br>RELATIVE_PATH AS file_name,<br>facturas!PREDICT(GET_PRESIGNED_URL(@ARCHIVOS,RELATIVE_PATH),1) as file_data<br>FROM DIRECTORY(@ARCHIVOS);</pre><p>Finally, due to JSON data structure on a Variant Type in the table, you can parse and convert data.</p><pre>select <br>    file_data:factura[0]:value::string as factura,<br>    file_data:nombre[0]:value::string as nombre,<br>    REGEXP_REPLACE(file_data:total[0]:value,&#39;^\\$|\\d*$&#39;,&#39;&#39;)::float as total<br>from facturas_tbl;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*gTUXy91l02dGbFJoiLnwqA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a28f7416c858" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Key-pair Authentication in Snowflake ❄️]]></title>
            <link>https://medium.com/snowflake/key-pair-authentication-in-snowflake-%EF%B8%8F-4854cbc0481a?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4854cbc0481a</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[keypair]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 23:43:51 GMT</pubDate>
            <atom:updated>2024-02-02T23:44:34.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using SnowSQL and test on Postman</h4><h3><strong>SnowSQL</strong></h3><p>SnowSQL is a CLI (Command Line Interface Tool) created by Snowflake to execute some statements form command line app (Terminal), it can be used to create a Token for authorization.</p><p>Go to <a href="http://developers.snowflake.com/">developers.snowflake.com</a> and download SnowSQL App for your OS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qU7IpD6dNDZnfDvZoKe6vA.png" /><figcaption>SnowSQL App download</figcaption></figure><p>Once it was installed, on your root directory will be installed a hidden directory “.snowsql” like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*leAb8ROKfTAcZP5pTaeCuA.png" /></figure><p>Inside this directory will be a “config” file where you could set custom credential:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*EDm3yY3V0p53BSHaYgVzhg.png" /></figure><p>In order to get the values, you can get them from your Snowflake URL, for instance in:</p><p><a href="https://yp12647.us-east-2.aws.snowflakecomputing.com/">https://<strong>yp12647.us-east-2.aws</strong>.snowflakecomputing.com</a></p><p>accountname: <strong>yp12647 </strong>, region: <strong>us-east-2.aws</strong></p><p>If you wondering where find more details about your Snowflake account, follow this steps in order to get your Snowflake account name and region information</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tqEb_zbHRkmJ2zevvWBE0Q.png" /></figure><h3>Key-Pair Certificate</h3><p>Create a local directory in which you wants to store all files (on production environment you must set the file access to chmod 400)<br>Then using terminal app run the following command to create the private key file, It will create the file <strong>rsa_key.p8</strong></p><pre>openssl genrsa 2048 | openssl pkcs8 -topk8 -inform PEM -out rsa_key.p8 -nocrypt</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8FUC2HFQOWpZ8xS1hGq9g.png" /></figure><p>Then run the follow command to create the public key file (rsa_key.pub)</p><pre>openssl rsa -in rsa_key.p8 -pubout -out rsa_key.pub</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7ZFIWMLMXJUAtaPjANlkA.png" /></figure><p>Then present it as base64 format to compare it latter:</p><pre>openssl rsa -pubin -in rsa_key.pub -outform DER | openssl dgst -sha256 -binary | openssl enc -base64</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2hVEGYF7Z50yGWPBtQrhw.png" /></figure><h3><strong>Snowflake Integration Setting</strong></h3><p>In Snowflake on a SQL Worksheet, enable ACCOUNTADMIN role</p><pre>use role accountadmin;</pre><p>Set the public key contained on <strong>rsa_key.pub </strong>to the user(s):</p><pre>ALTER USER csuarez SET RSA_PUBLIC_KEY=&#39;MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsuR7zFTJK12jvFViTzO4eXTQhdE27pFxFilocjpVlRnMDmjo+BbZDc8PSn4KeYlNX8BS7Tpn1eREvYcBjyeJ8qZUnWPJFDtZXNm+OpD0YHPJGakhpPgrwIcv5UrM8erpVGPti858ujhKH3UOwkHHotpSBUIEMANKo8ej5RWwiD4HbSxFDFXmOBxWcdxTLUgv+lIiaQ7srYDhCqR7fR+fGmw02pFPeQazu1HccBWYjhq0QxRlpsmTvCXzxR0fD/fgPA04Gvc1O7kxAYT0JcHWCmuDowtgYVf4QEpj+okUpoAnMwIv9xBbGwogup82NUs/aHv1vLlzjgjOzCI8BOOhswIDAQAB&#39;;</pre><p>You can check the fingerprint on Snowflake and compare with base64 format:</p><pre>desc user csuarez;<br>SELECT TRIM((SELECT &quot;value&quot; FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))<br>  WHERE &quot;property&quot; = &#39;RSA_PUBLIC_KEY_FP&#39;), &#39;SHA256:&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBMFJxCWO76p4rGN0G7ZIQ.png" /></figure><h3><strong>Create a Token</strong></h3><p>Open SnowSQL and move to the directory where you create the private and public keys (in this case the snowcert directory)</p><p>Than run the follow command:</p><pre>snowsql --private-key-path rsa_key.p8 --generate-jwt -a Snowflake_location -u user</pre><p>Where <strong>Snowflake_location</strong> can be obtained from Snowflake URL the first part https://<strong>yp12647.us-east-2.aws</strong>.snowflakecomputing.com in this case <strong>yp12647.us-east-2.aws</strong><br>And the <strong>user</strong> that was assigned the RSA_PUBLIC_KEY in Snowflake</p><p>The outcome of this command is a temporary JWToken:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ty7UN8OHDRhaG09D830lfw.png" /></figure><h3><strong>Testing with Postman</strong></h3><p>Open Postmand and make a Post request to the URL (1) to Snowflake SQL API Endpoint, in this case [api/v2/statements]:</p><pre>https://yp12647.us-east-2.aws.snowflakecomputing.com/api/v2/statements</pre><p>Replace <a href="http://yp12647.us-east-2.aws.snowflakecomputing.com/">yp12647.us-east-2.aws.snowflakecomputing.com</a> with your own Snowflake URL information and verify the endpoint is /api/v2/statements</p><p>Click in Authorization option (2) and add your JWT on (3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YppGcFOXhAzUAipqWm8IjQ.png" /></figure><p>Clink on Headers option (1) add/verify the following headers:</p><ul><li>Authorization: Bearer + JWToken (2)</li><li>X-Snowflake-Authorization-Token-Type: KEYPAIR_JWT (3)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPdQ-mersQVYqdqyxNrJCQ.png" /></figure><p>Finally on option Body, add the body of the request on JSON format (2) and press the “Send” button to get the response (data) requested (3)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMogxopmSpxM-IlJnnmiig.png" /></figure><h3>References</h3><p><a href="https://docs.snowflake.com/en/developer-guide/sql-api/index">https://docs.snowflake.com/en/developer-guide/sql-api/index</a></p><p><a href="https://docs.snowflake.com/en/developer-guide/sql-api/reference">https://docs.snowflake.com/en/developer-guide/sql-api/reference</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4854cbc0481a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/key-pair-authentication-in-snowflake-%EF%B8%8F-4854cbc0481a">Key-pair Authentication in Snowflake ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake Summit ’23 ❄️]]></title>
            <link>https://medium.com/snowflake/snowflake-summit-23-%EF%B8%8F-31addef7843c?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/31addef7843c</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[snowpark-python]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 01:16:11 GMT</pubDate>
            <atom:updated>2023-07-08T04:13:40.463Z</atom:updated>
            <content:encoded><![CDATA[<p>New features and powerful toolset!</p><p>Lot of innovations announced at Summit, including advancements with generative AI and LLMs, Apache Iceberg, flexible programmability, application development, and much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*XM6aYPQvKchIE4VzWtRV8w.gif" /></figure><h4>Dynamic Tables</h4><p>Dynamic Tables are the declarative components designed to orchestrate the data transformation pipeline. They significantly simplify data engineering at Snowflake and provide a reliable, cost-effective, and automated way to transform your data for consumption. Instead of defining the data transformation steps as a series of tasks and having to monitor dependencies and scheduling, you can simply define the end state of the transformation using PivotTables and leave complex pipeline management to Snowflake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*dY27JprkoQsNYXN5v_3JOA.png" /></figure><p><a href="https://docs.snowflake.com/en/user-guide/dynamic-tables-about">https://docs.snowflake.com/en/user-guide/dynamic-tables-about</a></p><h4>Infer Schema and Schema Evolution</h4><p>Infer Schema — Automatically detects the file metadata schema in a set of prepared data files containing semi-structured data and retrieves the column definitions, allowing the creation of tables based on the input files.</p><p>Schema Evolution: Semi-structured data tends to evolve over time. Systems that generate data add new columns to accommodate additional information, requiring subsequent tables to evolve accordingly. The structure of tables in Snowflake can automatically evolve to accommodate the structure of new data received from data sources. Snowflake supports the following:<br>- Automatically add new columns<br>- Automatically removes the NOT NULL constraint from missing columns in new data files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*gM8jzHoF42FAp0RByTBcxA.png" /></figure><p><a href="https://docs.snowflake.com/pt/sql-reference/functions/infer_schema">https://docs.snowflake.com/pt/sql-reference/functions/infer_schema</a></p><h4>Snowflake Iceberg Table</h4><p>Iceberg Tables combines unique features in Snowflake with the open source projects Apache Iceberg and Apache Parquet to support the architecture of your choice. As part of the latest version of Iceberg, we added catalog support to the Iceberg project to ensure that engines outside of Snowflake can interoperate with Iceberg tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*rcWF00Oy2PqBdb9_AemYCQ.png" /></figure><h4>Snowflake Native Apps</h4><p>A new way to build apps with the Snowflake native app framework. Today, we’re excited to bring the power of the Snowflake Native App Framework to developers around the world with a public preview on AWS. Developers can now start building and testing native Snowflake apps in their AWS account. Distribution and monetization features will be available in public preview on AWS later this year. Snowflake Native App Framework continues to be available in private preview on Google Cloud Platform and Azure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*VRkG5QSRMErTHSy7--UF_A.png" /></figure><p><a href="https://quickstarts.snowflake.com/guide/getting_started_with_native_apps/index.html?index=../..index#0">https://quickstarts.snowflake.com/guide/getting_started_with_native_apps/index.html</a></p><h4>Snowflake and LLM / Generative AI</h4><p>The potential of Generative AI and the Large Language Model (LLM) for businesses is enormous. We’ve talked about this opportunity before, and at Summit’23 we announced several capabilities coming together to help our clients bring generative AI and LLM’s directly to their property data, all delivered through a single, secure platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*EiyY6nm5x_LeMuYUTWIy8g.png" /></figure><p><a href="https://quickstarts.snowflake.com/guide/frosty_llm_chatbot_on_streamlit_snowflake/#0">https://quickstarts.snowflake.com/guide/frosty_llm_chatbot_on_streamlit_snowflake/#0</a></p><h4>Snowpark Container</h4><p>Snowpark Container Services is a fully managed container offering that helps you easily deploy, manage, and scale containerized applications without having to move data out of Snowflake. As a fully managed service, it comes with Snowflake security, configuration, and operational best practices built in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*o0LaWNj7pzEumPafniwLsw.png" /></figure><p><a href="https://docs.snowflake.com/en/LIMITEDACCESS/snowpark-containers/overview">https://docs.snowflake.com/en/LIMITEDACCESS/snowpark-containers/overview</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31addef7843c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/snowflake-summit-23-%EF%B8%8F-31addef7843c">Snowflake Summit ’23 ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ingeniería y Visualización de Datos usando INEGI y Snowpark❄️]]></title>
            <link>https://medium.com/snowflake/ingenier%C3%ADa-y-visualizaci%C3%B3n-de-datos-usando-inegi-y-snowpark-%EF%B8%8F-5418fabe2dd8?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/5418fabe2dd8</guid>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[inegi]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 01:31:29 GMT</pubDate>
            <atom:updated>2023-06-07T01:31:29.634Z</atom:updated>
            <content:encoded><![CDATA[<p>Instituto Nacional de Estadística y Geografía (INEGI) proporciona datos abiertos dedicados a coordinar el Sistema Nacional de Información Estadística y Geográfica del país (México) <a href="https://www.inegi.org.mx/siscon/">https://www.inegi.org.mx/siscon/</a></p><p>El INEGI recopila datos sobre información económica y geográfica de una sola ciudad a todo el país mediante un cuestionario en el hogar en una segmentación y un catálogo de datos bien definidos, después de que todos los datos se digitalizan, se publican en un portal abierto en varios formatos de archivo (principalmente CSV) Uno de los desafíos al que se enfrenta un consumidor de datos es cuán válidos son los datos bien definidos, esto porque provienen de la digitalización (tipos de datos, NULL, carácter incorrecto ‘*’, formato de latitud/longitud incorrecto, etc. 🛠️)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xqv3dfirwWfFYqyrUwJVRQ.png" /><figcaption>Datos de origen INEGI no curados</figcaption></figure><p>Este desafío viene con la idea de mover datos a la nube, aplicar algo de ingeniería de datos con Python y Snowflake Snowpark Framework basado en la siguiente extracción, transformación y carga (ETL) de datos desde un servidor web público usando solo Python y luego con algún modelo de datos (RAW , consolidación y materialización) optimizar la calidad de los datos y finalmente crear una aplicación de datos con Streamlit para visualización de datos como se ilustra a continuación:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ip8PPLHQfOWmzS5CF7QFg.png" /><figcaption>Diseño de solución desde datos INEGI en webhost</figcaption></figure><h4>Requerimientos para el proyecto</h4><ul><li>Snowflake production/<a href="https://signup.snowflake.com/">trial account</a></li><li><a href="https://code.visualstudio.com/download">VSCode</a> con Jupyter Notebook</li><li><a href="https://www.python.org/">Python</a> (Python 3.8)</li><li><a href="https://www.anaconda.com/products/distribution">Anaconda</a></li><li>Snowpark Python</li><li>Streamlit</li></ul><p>Descargar el proyecto desde el repositorio de <a href="http://git%20clone%20https//github.com/sfc-gh-csuarez/snowpark_inegi.git">GitHub Repo</a> o clonarlo:<br>git clone <a href="https://github.com/sfc-gh-csuarez/snowpark_inegi.git">https:</a><a href="https://github.com/sfc-gh-csuarez/snowpark_inegi.git"><em>//github.com/sfc-gh-csuarez/snowpark_inegi.git</em></a></p><h4>Configuración del entorno de desarrollo</h4><p>Después de instalar Anaconda, en la ventana de la terminal o en el IDE de VS Code, cree un entorno de desarrollo como:</p><pre>conda create - name snowpark_env python=3.8<br>conda activate snowpark_env</pre><p>Instalar Snowpark/Streamlit :</p><pre>pip install snowflake-snowpark-python pandas<br>pip install lat-lon-parser<br>pip install requests<br>conda install -c conda-forge streamlit <br>conda install -c conda-forge pillow</pre><p>En el directorio del proyecto, edite el archivo config.py. En este archivo, ingrese los valores para cada propiedad con la información para acceder a Snowflake desde Python usando Snowpark.</p><pre>connection_parameters = {<br>    &quot;account&quot;: &quot;&lt;account_id&gt;.&lt;account_region_zone&gt;&quot;,<br>    &quot;user&quot;: &quot;&lt;snowflake username&gt;&quot;,<br>    &quot;password&quot;: &quot;&lt;snowflake password&gt;&quot;,<br>    &quot;warehouse&quot;: &quot;INEGI_WH&quot;,<br>    &quot;role&quot;: &quot;INEGI_ROLE&quot;,<br>    &quot;database&quot;: &quot;INEGI&quot;,<br>    &quot;schema&quot;: &quot;PUBLIC&quot;<br>}</pre><p>El valor del parámetro “cuenta” se puede encontrar en la URL de Snowflake como: <br><strong>https://&lt;account_id&gt;.&lt;account_region_zone&gt;.snowflakecomputing.com</strong></p><p>Por ejemplo en:<br>URL de copo de nieve: <a href="https://ly14496.south-central-us.azure.snowflakecomputing.com/"><strong>https://ly14496.south-central-us.azure.snowflakecomputing.com</strong></a><br>los valores correspondientes son:<br>cuenta_id = ly14496<br>account_region_zone = south-central-us.azure</p><h4>Objetos Snowflake</h4><p>En Snowflake Snowsight, configurando la base de datos, el almacén virtual, las funciones y los privilegios como:</p><pre>use role accountadmin;<br>--objects <br>create database inegi;<br>--virtual wharehouse<br>create warehouse inegi_wh <br>warehouse_type = &#39;STANDARD&#39; <br>warehouse_size =XSMALL <br>auto_suspend = 120 <br>auto_resume = TRUE <br>max_cluster_count=1 <br>min_cluster_count=1;<br>--roles<br>create role inegi_role;<br>grant role inegi_role to user &lt;your_snowflake_user&gt;;<br>grant role sysadmin to user &lt;your_snowflake_user&gt;;<br>grant role sysadmin to role inegi_role;<br>--privileges <br>grant usage on database inegi to role inegi_role;<br>grant all privileges on schema public to role inegi_role;<br>grant usage on warehouse inegi_wh to role inegi_role;</pre><p>A partir de este punto, todo está configurado en el modelo de datos y el objeto de datos que admitirá todo el proceso, es hora de comenzar a ingresar al proceso y la consolidación de ETL, ¡para eso tendrá varios archivos de Jupiter Notebook como guía en cada parte del proceso! 🏁</p><h4>Extracción de Datos: 01_INEGI_download.ipynb</h4><p>Al ejecutar la primera celda de Jupiter Notebook, ejecutará un proceso de python para descargar datos de la fuente (host web), convertirlos en un archivo CSV, realizar alguna transformación sobre tipos de datos, NULL, conversión de formato textual de latitud/longitud a formato flotante, y dividir en archivos JSON (con compresión) y almacenarlos en una carpeta local llamada “JSON” en la carpeta raíz del directorio del proyecto</p><pre>from inegidata import urlDownload<br># &#39;remote&#39; option in orer to download from INEGI web hosting <br># opciób &#39;local&#39; to use local file<br>urlDownload(&#39;remote&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6cyij3tga5D5gQX9P2GpA.png" /></figure><h4>Modelo y Carga de Datos: 02_INEGI_dataEngineering.ipynb</h4><p>Abra este archivo de jupyter notebook, con datos seleccionados, es hora de usar Snowpark para crear una etapa de datos habilitados y un objeto de destino (tabla) que contenga archivos JSON como RAW usando el tipo de datos “Variante” de Snowflake que contenga JSON en la tabla en una sola columna<br>no olvide habilitar el entorno de desarrollo como:<br>conda activate snowpark_env</p><p>Las siguientes dos celdas de Jupiter Notebook harán referencia a las bibliotecas (la declaración de importación) y la segunda celda para crear un objeto de sesión que apunte a la instancia de Snowflake con la credencial segura para ejecutar el marco Snowpark:</p><pre>sesion = Session.builder.configs(connection_parameters).create()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRTlEoqRqDoeJOw2LDiseA.png" /><figcaption>Crear los objetos Snowflake(tabla) que contendrán JSON como un raw data (Variant type)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mMDUfoIGnDO-vPKMVhQBsQ.png" /><figcaption>Crear Snowflake internal stage que almacenará JSON como archivo</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FkAZIM4QJX7lOzlLr9Cmw.png" /><figcaption>Convertir JSON en Data object (table) el ejecutar el comando copy into</figcaption></figure><h4>Materialización de Dato : 03_INEGI_dataModeling.ipynb</h4><p>En este archivo de cuaderno Jupyter, transformamos la tabla RAW (que tiene JSON como tipo de datos Variant Snowflake), creamos una vista para consolidar datos, registramos un UDF de Snowpark y creamos una función de ventana para crear la vista de población de datos final basada en resumir los totales de cada entidad federativa (México).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*zKt27S6XaEYI1rl0yRGBGQ.png" /><figcaption>Convertir data RAW (Tabla con JSON) en vista (View) con selección parametrizada</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-TKzFA6N5HYpHLdnrbLNQ.png" /><figcaption>Registro de UDF desde el archivo Internal Stage “entidad.py”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-TEyaJH8kIeoKYGfnFCgFw.png" /><figcaption>Vista final (View) que contiene valores latitud-longitud, población máxima y nombre de entidad</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_SVIkMXSzbx1AX6KPC6VmA.png" /><figcaption>DataFrame con data que será usada para crear la data App</figcaption></figure><h4>Streamlit Data App: 04_Streamlit.py</h4><p>Con todos los datos listos para ser consumidos, es hora de crear su aplicación de datos utilizando el marco Streamlit, no olvide habilitar su entorno de desarrollo como:<br>conda activa snowpark_env</p><p>Then execute the Streamlit app as:<br>streamlit run 04_Streamlit.py</p><p>Esto ejecutará un servidor local integrado siguiendo el código (python), cada componente visual es una variable Streamlit (st) que ha precodificado internamente todas las devoluciones de llamada para la interacción del usuario (reactiva) y mantiene las propiedades como variables, más referencia <a href="https://docs.streamlit.io/">Streamlit documentation</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d146650f37a0acf0bf84e975dc58b1f0/href">https://medium.com/media/d146650f37a0acf0bf84e975dc58b1f0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*roXVZNglAWf0AJ4TXfa7aQ.png" /><figcaption>Data App en modo local</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iL7B5S0PWAbXk2vbJQ8wdA.png" /><figcaption>Data App en modo local</figcaption></figure><h3>Referencias:</h3><p>GitHub repo: <a href="https://github.com/sfc-gh-csuarez/snowpark_inegi">https://github.com/sfc-gh-csuarez/snowpark_inegi</a><br>Snowflake QuickStart: <a href="https://quickstarts.snowflake.com/guide/data_engineering_snowpark_streamlit_inegi/index.html">https://quickstarts.snowflake.com/guide/data_engineering_snowpark_streamlit_inegi/index.html</a><br>Video : <a href="https://www.youtube.com/watch?v=R7Y_xKqwF8U&amp;t=7s">https://www.youtube.com/watch?v=R7Y_xKqwF8U&amp;t=7s</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5418fabe2dd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/ingenier%C3%ADa-y-visualizaci%C3%B3n-de-datos-usando-inegi-y-snowpark-%EF%B8%8F-5418fabe2dd8">Ingeniería y Visualización de Datos usando INEGI y Snowpark❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Activate Local Development Environment for Snowpark/Streamlit ❄️]]></title>
            <link>https://medium.com/snowflake/activate-local-development-environment-for-snowpark-%EF%B8%8F-1ae1a6d7e00d?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ae1a6d7e00d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[anaconda]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[streamlit]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Thu, 25 May 2023 00:11:04 GMT</pubDate>
            <atom:updated>2023-06-06T17:32:21.744Z</atom:updated>
            <content:encoded><![CDATA[<p>In order to enable dev environment to create Snowpark/Streamlit Data App, it is necessary to prepare the development environment beforehand. .<br>This preparation requires some basic knowledge of Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*ucUsv9mVzv9jvCF5eivKaQ.png" /><figcaption>Python, Anaconda, Visual Studio Code, Snowpark and Streamlit</figcaption></figure><h3>Python Installation</h3><p>Snowpark for Python requires Python 3.8.* and it will depend on the operating system MacOS/Linux or Windows OS (32bit or 64bit) to do the installation.<br><strong>Mac<br></strong><a href="https://www.python.org/downloads/release/python-3810/">https://www.python.org/downloads/release/python-3810/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzYn3h38Ij39z08OmOEW4g.png" /><figcaption>Python download for Mac</figcaption></figure><p>Another option to install python is using the Homebrew (<a href="https://brew.sh/">https://brew.sh/</a>) libraries/packages gestures for Mac using command line application (terminal app):</p><pre>brew install python@3.8</pre><p><strong>Windows</strong><br> <a href="https://www.python.org/downloads/">https://www.python.org/downloads/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*X1fa2qB6RsWROBA8bOZa2w.png" /><figcaption>Python download for Windows</figcaption></figure><p>At the end of the installation, activate “Add Python 3.8 in the PATH:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E62SSlwvxVVWamr_4S-JJw.png" /><figcaption>Check the box “Add Python 3.8 to PATH”</figcaption></figure><p>In both cases, check that python is inside the directory PATH for the account profile on the computer.</p><pre>echo $PATH</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdsLZq5wthhdN6YzYM6E0g.png" /></figure><h3>Anaconda Installation</h3><p>Snowflake, through the Anaconda python library repository service, has created a channel validated and security-reviewed for its own and third-party libraries that can be integrated into developments with Snowpark python. One advantage is version control and the creation of local development environments.</p><p><strong>Anaconda</strong> <br> <a href="https://www.anaconda.com/download">https://www.anaconda.com/download</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5sTBjS0nw-Dr-cCYryIV2A.png" /></figure><h4>Create and Activate local development environment (visual mode)</h4><p>It includes Anaconda Navigator that visually allows the management of packages and libraries, including the creation of local development environments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-UA9ght9E0X0nFQerIXAA.png" /><figcaption>Anaconda Navigator and how create a local enviro</figcaption></figure><p>To create a local development environment with Python 3.8.*:</p><ol><li>In Anaconda Navigator click on “Environment”<br>2.Click on the “Create” option<br>3.Choose “Package: Python and from the list of options choose “3.8.*”<br>4.Click on create</li></ol><p>To activate a development environment from Anaconda navigator, previously created in the development environment in the python 3.8.* version, the development environment can be activated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*atA6THRV4j_dAYn0TQonSg.png" /><figcaption>Activate Anaconda Environment</figcaption></figure><h4>Create development environment (command line mode)</h4><p>It is possible to create a development environment from the command line, for them to validate that Anaconda is in the PATH of installed libraries for the current user:</p><pre>echo $PATH</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QK-KYE9DJ4QWdO3Blm5hbw.png" /></figure><p>Validate Anaconda version:</p><pre>conda —-version </pre><p>Create a development environment with Python 3.8.*, in this example you will create the local environment “snowpark_env”:</p><pre>conda create --name snowpark_env python=3.8</pre><p>To activate a previously created development environment:</p><pre>conda activate snowpark_env</pre><p>To deactivate (it does not imply more than stop pointing to the libraries in a development environment):</p><pre>conda deactivate</pre><h4>Snowpark/Streamlit Installation (visual mode)</h4><p>Using Anaconda Navigator, you must choose the local development environment created, and in the library panel look for both Snowpark/Streamlit activate the checkboxes and click the “Apply” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GX6jPjMog8HiOJ1M68jg9w.png" /><figcaption>Install Snowpark/Streamlit from Anaconda Navigator</figcaption></figure><h4>Snowpark/Streamlit Installation (command-line mode)</h4><p>Using the command line (terminal app), where “snowpark_env” is the name of the local development environment in this example:</p><pre>conda install --name snowpark_env snowflake-snowpark-python pandas<br>conda install --name  snowpark_env streamlit</pre><p>Within the same local development environment “snowpark_env”, install Jupyter Notebooks for development with Streamlit.</p><pre>pip install notebook</pre><p>From this point you can add more packages or libraries that are fenced in to the Snowflake Anaconda channel (<a href="https://repo.anaconda.com/pkgs/snowflake">https://repo.anaconda.com/pkgs/snowflake</a>)</p><h4>Install Visual Studio Code</h4><p>Directly from the official site of Microsoft Visual Studio Code (<a href="https://code.visualstudio.com/">https://code.visualstudio.com/</a>) download and install for the OS of the computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uNZf9Hj8IWiEKdPEdmtFAQ.png" /><figcaption>Visual Studio Code — download</figcaption></figure><p>Go to the View / Command Palette menu and type “Shell Command: install ‘code’ command in PATH, this will allow you to open Visual Studio Code from the command line pointing to the current directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYHdfoGR3ntwXW9buep7dw.png" /><figcaption>Enable Shell Command to open VSC from terminal app</figcaption></figure><h3>Create a Session with Snowpark</h3><p>create a directory:</p><pre>mkdir proyecto1 <br>cd proyecto1</pre><p>Inside the “project1” directory, open Visual Studio Code:</p><pre>code .</pre><p>In case of using a Python file (py extension), choose the Python Interpreter in Visual Studio Code, from the View / Command Palette menu and write “Python: Select Interpreter” directly</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BuSD-xAfCvtD9TO_2ehfAw.png" /><figcaption>Select Python Interpreter on VSC</figcaption></figure><p>In case of using Notebook files (ipynb extension), check that the created environment is active within the Visual Studio Code notebook interpreter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*OW-nQMVF2WSsFeoTSCI2CA.png" /><figcaption>On VSC Notebook, over top cell, enable the interpreter to use</figcaption></figure><p>Activate the local development environment of Anaconda where Snowpark and Streamlit were installed</p><pre>conda activate snowpark_env</pre><p>Create Snowflake access credentials from Snowpark<br>For them inside the project directory, we create the “config.py” file and add the following code and fill in the values for each property:</p><pre>connection_parameters = {<br>    &quot;account&quot;: &quot;&lt;account_id&gt;.&lt;account_region_zone&gt;&quot;,<br>    &quot;user&quot;: &quot;&lt;snowflake username&gt;&quot;,<br>    &quot;password&quot;: &quot;&lt;contraseña snowflake username&quot;,<br>    &quot;warehouse&quot;: &quot;&lt;nombre warehouse&gt;&quot;,<br>    &quot;role&quot;: &quot;&lt;nombre rol&gt;&quot;,<br>    &quot;database&quot;: &quot;&lt;nombre base de datos&gt;&quot;,<br>    &quot;schema&quot;: &quot;&lt;nombre esquema&gt;&quot;<br>}</pre><p>The value of the “account” parameter can be found in the Snowflake URL as:<br>https://&lt;account_id&gt;.&lt;account_region_zone&gt;.snowflakecomputing.com</p><p>Example<br>In the Snowflake UI URL:<br><a href="https://ly14496.south-central-us.azure.snowflakecomputing.com/">https://ly14496.south-central-us.azure.snowflakecomputing.com</a><br>the corresponding values are:<br>account_id = ly14496<br>account_region_zone = south-central-us.azure</p><p>So for this example “account” = “ly14496.south-central-us.azure”</p><p>Create a new Python or Notebook file and import Snowpark credentials and libraries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nys-biHdk-TrJDESaqJm8A.png" /><figcaption>At the top of the python/notebook file</figcaption></figure><pre>#Importar librerias<br>from snowflake.snowpark.session import Session<br>from config import connection_parameters</pre><p>Create a Snowpark session</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wTXFv-UKYj-n3Yn_OwzmQ.png" /><figcaption>Create a Snowpark session</figcaption></figure><pre>#Crear sesión y objetos Snowflake<br>sesion = Session.builder.configs(connection_parameters).create()<br>if sesion != None:<br>    print(&quot;Conectado&quot;)<br>    sesion.use_database(&#39;&lt;Database Name&gt;&#39;)<br>    print(sesion.sql(&quot;select current_warehouse()&quot;).collect()) <br><br>else:<br>    print(&quot;Error de conexión&quot;)</pre><p>It will output the name of the active warehouse.</p><p>From here you are ready to go on Snowpark/Streamlit App</p><p><strong>References</strong><br>Snowflake environment activation: <a href="https://docs.snowflake.com/en/developer-guide/snowpark/python/setup.html">https://docs.snowflake.com/en/developer-guide/snowpark/python/setup.html</a></p><p>Create a session with Snowpark: <a href="https://docs.snowflake.com/en/developer-guide/snowpark/python/creating-session.html#label-snowpark-python-creating-session">https://docs.snowflake.com/en/developer-guide/snowpark/python/creating-session.html#label-snowpark-python-creating-session</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ae1a6d7e00d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/activate-local-development-environment-for-snowpark-%EF%B8%8F-1ae1a6d7e00d">Activate Local Development Environment for Snowpark/Streamlit ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Python files on Snowflake Stage for Python Worksheet ❄️]]></title>
            <link>https://medium.com/snowflake/load-python-files-on-snowflake-stage-for-python-worksheet-%EF%B8%8F-e9b89b4f8a5b?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9b89b4f8a5b</guid>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[snowpark]]></category>
            <category><![CDATA[snowpark-python]]></category>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Mon, 22 May 2023 17:30:45 GMT</pubDate>
            <atom:updated>2023-06-07T17:38:33.899Z</atom:updated>
            <content:encoded><![CDATA[<p>Legacy python custom modules and function previously coded can be store on Snowflake and re-used directly on python worksheet using Snowflake UI-visual way!</p><h3>Login Snowflake SnowSight</h3><p>Create/Select Snowflake object to relate with: database, schema, virtual warehouse in order to create an stage object to store python files,<br>in this example:<br> <br> <strong>Database</strong>: Riders<br><strong>Schema</strong>:Public<br><strong>Virtual warehouse</strong>: Python_WH</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*pf7UU7sZiHI6nEuww0gIww.png" /></figure><h3>Create Stage to load python files</h3><p>Having active the database, the Public schema (for this example), click on the “Create” button and choose the “Stage” option and finally “Snowflake Managed” option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*oPKMsHVARbkqWykJXUrogQ.png" /></figure><p>Give the stage a name (in the example “pythonstage”) and activate the “Enable directory table” checkbox to be able to reference the files stored by internal URI in Snowflake</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*Li0XfLYx0XvmXzktwUUKRA.png" /></figure><h3>Load Files Into Stage</h3><p>Once the stage (pythonstage) is created we can load files, to do this click on the “+Files” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*Xy8yn5exG9bjlfzI5MRVOQ.png" /></figure><p>Select files to upload to Snowflake either drag-and-drop or click the “Upload files” button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*ioeo5zbfTGfVg4SIgHiZ5Q.png" /></figure><p>The names of the files will be displayed as a list, click on “Upload”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*casviESID3qyAYLBHWICAQ.png" /></figure><p>Once the file upload process is finished, the list of files that are already in the stage (pythonstage) will be displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*ucIdNtHwtR9rJRyzSa3EHA.png" /></figure><h3>Link files in Python Worksheet</h3><p>Inside a Python Worksheet</p><ol><li>Click on the “Packages” option</li><li>Click on the “Stage Packages” section</li><li>Write the name of the stage starting with @ and the name of the python file (<a href="http://twitter.com/pythonstage/entidad">@pythonstage/entidad</a>.py)</li><li>Click on the “import” button</li><li>Once added click on any space outside the “Stage Packages” box</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*1s4hw0kiQLHlX24WDdsmtw.png" /></figure><p>With this, the methods or functions contained in the python file can be used. Which will allow the function to be executed within the entity.py file existing in the stage (pythonstage)</p><pre>from entidad import nom_entidad;<br><br>def main(session: snowpark.Session):<br>    # Your code goes here, inside the &quot;main&quot; handler.<br>    print(validarMetodo(5))<br>def validarMetodo(id:int):<br>    return nom_entidad(id)</pre><h3>Testing Python Package/Function</h3><p>After running the Python worksheet by pressing “run” button, the result of linking and declaring a function inside Snowflake will be responded</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*f6pV8txSS7InbavvWE8cxg.png" /></figure><p><strong>References</strong>:<br>Python worksheet: <a href="https://docs.snowflake.com/en/developer-guide/snowpark/python/python-worksheets">https://docs.snowflake.com/en/developer-guide/snowpark/python/python-worksheets</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9b89b4f8a5b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/snowflake/load-python-files-on-snowflake-stage-for-python-worksheet-%EF%B8%8F-e9b89b4f8a5b">Load Python files on Snowflake Stage for Python Worksheet ❄️</a> was originally published in <a href="https://medium.com/snowflake">Snowflake Builders Blog: Data Engineers, App Developers, AI, &amp; Data Science</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Data from local Computer Into Snowflake Internal Stage ❄️]]></title>
            <link>https://medium.com/@smca310777/load-data-from-local-computer-into-snowflake-internal-stage-%EF%B8%8F-14c074f71ea?source=rss-c65b400f91c4------2</link>
            <guid isPermaLink="false">https://medium.com/p/14c074f71ea</guid>
            <dc:creator><![CDATA[Carlos Suarez]]></dc:creator>
            <pubDate>Fri, 19 May 2023 16:05:28 GMT</pubDate>
            <atom:updated>2023-05-19T16:05:28.310Z</atom:updated>
            <content:encoded><![CDATA[<p>Using SnowSQL a wonderful CLI(Command Line Interfase) tool provided by Snowflake.</p><p>Sometimes we have the challenge to move data without using 3rd-party ETL/ELT tool because the business policies do not allow secure network zone access. Here Snowflake support loading structured (CSV), semi-structured(JSON) or no-structured (PDF, images) into Snowflake Internal, from there convert files into Snowflake data objects using Snowflake SQL command and functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_bimgD9jwqNJrBXdgnYPg.png" /><figcaption>Process to load data from local storage to Snowflake Internal stage</figcaption></figure><p>Requirements:</p><ul><li>SnowSQL application</li><li>Snowflake SnowSight</li><li>Snowflake user credentials</li></ul><h3>Install SnowSQL</h3><p>Fist, you need download SnowSQL from <a href="http://(https//developers.snowflake.com/snowsql/">Snowflake developers</a> portal and select the corresponding OS and release according to your local equipment</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tF_yqUjzbZGwwB2x-Rw8nA.png" /><figcaption>Snowflake Developers portal — SnowSQL</figcaption></figure><h3>Setting up SnowSQL</h3><p>In order to get secure and authorized access to Snowflake from SnowSQL you need to validate into your class path (depending of your OS) if SnowSQL is include, for instance, on MacOS the shell (.zshrc) of your user profile , no matter if you create an alias or add it directly on the PATH, it should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Wl0R0cOpLO-BWoQOGvbw7Q.png" /></figure><h3>Get the Snowflake Account Info</h3><p>You will need Snowflake account information in order to indicate SnowSQL to point to your Snowflake instance, for you can login your Snowflake account and get the Snowflake URL:<br>1. on the lower bottom corner click on Snowflake icon<br>2. Select the current session<br>3. Click on the small chain icon the copy the Snowflake URL (String)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*gUmCAOIl93oT0_EBLOVtEA.png" /><figcaption>Get Snowflake URL of your cloud instance</figcaption></figure><p>This URL will help us to construct the reference information on SnowSQL, so we must extract from:<br><em>https://</em><strong><em>&lt;account_id&gt;.&lt;account_region_zone&gt;</em></strong><em>.snowflakecomputing.com</em></p><p>For instance in:<br>Snowflake URL : <a href="https://ly14496.south-central-us.azure.snowflakecomputing.com/">https://ly14496.south-central-us.azure.snowflakecomputing.com</a></p><p>the corresponding Account_Identifier is:<br><strong>Account_Identifier</strong> = ly14496.south-central-us.azure</p><p>With that, we can connect from SnowSQL to Snowflake instance like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFp8B9ZBZjzV1kumf9cgfA.png" /><figcaption>SnowSQL command to access Snowflake instance</figcaption></figure><p>The loginName will be your Snowflake username, after run this command, SnowSql will as you for your password.<br>After successful authentication , you need to select your database, schema and virtual warehouse like you do in Snowflake SnowSight, to enable all Snowflake objects with user privileges</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoqSWudDG120ctUVbeTwaA.png" /></figure><pre>use database &lt;Database_Name&gt;;<br>use schema &lt;Schema_Name&gt;;<br>use warehouse &lt;Virtual_Warehouse_Name&gt;;</pre><h3>Create an Snowflake Internal Stage</h3><p>To create an internal stage you can use the following SQL command, this stage is a Snowflake named stage because it’s a database object indeed, which will be referenced as @Stage_Name, there are more parameter than can be include, like type of encryption when put files due to Snowflake by design encrypt all data; for more info on Snowflake <a href="https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage">Documentation</a></p><pre>  create stage if not exists &lt;Stage_Name&gt;;</pre><h3>Load data into Internal Stage</h3><p>having the database, schema, virtual warehouse and named stage created, you can use exclusive SowSQL SQL command to put data into named stage, as example:<br>- Data is on a pre-created <em>data</em> folder (windows OS: c:\data MacOS /data)<br>- File to upload is <em>data.csv</em></p><p>So to upload this file you should execute de command like:</p><pre>#Winodows OS <br>put file://c:\data\data.csv @StageName;<br><br>#Windows OS with spaces on the file name<br>put &#39;file://C:\ruta\directorio\File Name.csv&#39; @StageName;<br><br>#Linux/MacOS<br>put file:///data/data.csv @ @StageName;<br></pre><p>After completion file upload, you can list the files that stage contain as:</p><pre>list @StageName;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tELKG9lUNBoeA5r1eLvj_g.png" /></figure><p>Or into Snowflake SnowSight UI</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8tfQ1IITEos0BRPBTuf8Q.png" /></figure><h3>Copy data from file to Snowflake Object</h3><p>You will need to create a Snowflake object that hold data reference (table) like:</p><pre> create table if not exist &lt;TableName&gt;;</pre><p>Then create a file format, this because CSV files could have different character delimiter for columns values:</p><pre>create file format typeCSV <br>TYPE = &#39;CSV&#39; COMPRESSION = &#39;AUTO&#39; <br>FIELD_DELIMITER = &#39;,&#39; <br>RECORD_DELIMITER = &#39;\n&#39; <br>SKIP_HEADER = 0 <br>FIELD_OPTIONALLY_ENCLOSED_BY = &#39;\042&#39; <br>TRIM_SPACE = FALSE <br>ERROR_ON_COLUMN_COUNT_MISMATCH = FALSE <br>ESCAPE = &#39;NONE&#39; <br>ESCAPE_UNENCLOSED_FIELD = &#39;\134&#39; <br>DATE_FORMAT = &#39;AUTO&#39; <br>TIMESTAMP_FORMAT = &#39;AUTO&#39; NULL_IF = (&#39;&#39;) <br>COMMENT = &#39;CSV File format for load data’;</pre><p>Finally execute te copy process from file in named stage to table:</p><pre>copy into &lt;TableName&gt; <br>from &lt;@SgtageName&gt;/&lt;data.csv.gz&gt;<br>file_format = typeCSV;</pre><p>References:<br>SnowSQL: <a href="https://developers.snowflake.com/snowsql/">https://developers.snowflake.com/snowsql/</a><br>Snowflake Named Stages: <a href="https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage">https://docs.snowflake.com/en/user-guide/data-load-local-file-system-create-stage</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14c074f71ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>