sábado, 31 de agosto de 2024

Working code for trans

 https://www.assemblyai.com/docs/getting-started/transcribe-streaming-audio-from-a-microphone/python

viernes, 30 de agosto de 2024

draw

 import turtle


# Create a turtle screen

screen = turtle.Screen()

screen.bgcolor("black")  # Set the background color to black


# Create a turtle

spiral_turtle = turtle.Turtle()

spiral_turtle.speed(0)  # Set the turtle speed to maximum (no animation)


# Define colors for the spiral

colors = ["red", "orange", "yellow", "green", "blue", "purple"]


# Draw a colorful spiral pattern

for i in range(360):

    spiral_turtle.pencolor(colors[i % 6])  # Cycle through the colors

    spiral_turtle.forward(i * 3 / len(colors))  # Move the turtle forward

    spiral_turtle.left(59)  # Turn the turtle left


# Hide the turtle and finish

spiral_turtle.hideturtle()


# Keep the window open until it is closed by the user

turtle.done()


sábado, 24 de agosto de 2024

Making a request and creating 2 list with key and values

 >>> import requests

>>> info=requests.get('https://ipinfo.io/json').json() 

>>> keys=[k for k in info]

>>> print(keys)

['ip', 'hostname', 'city', 'region', 'country', 'loc', 'org', 'postal', 'timezone', 'readme']

>>> values=[info.get(v) for v in keys]

>>> print(values)

['148.255.218.74', '74.218.255.148.d.dyn.claro.net.do', 'Santo Domingo Este', 'Santo Domingo Province', 'DO', '18.4885,-69.8571', 'AS6400 Compañía Dominicana de Teléfonos S. A.', '11605', 'America/Santo_Domingo', 'https://ipinfo.io/missingauth']

>>> 


Easy method


>>> info.values()

dict_values(['148.255.218.74', '74.218.255.148.d.dyn.claro.net.do', 'Santo Domingo Este', 'Santo Domingo Province', 'DO', '18.4885,-69.8571', 'AS6400 Compañía Dominicana de Teléfonos S. A.', '11605', 'America/Santo_Domingo', 'https://ipinfo.io/missingauth'])

>>> info.keys()

dict_keys(['ip', 'hostname', 'city', 'region', 'country', 'loc', 'org', 'postal', 'timezone', 'readme'])


--------

>>> for a,b in info.items():

...    print(a,b)

... 

ip 148.255.218.74

hostname 74.218.255.148.d.dyn.claro.net.do

city Santo Domingo Este

region Santo Domingo Province

country DO

loc 18.4885,-69.8571

org AS6400 Compañía Dominicana de Teléfonos S. A.

postal 11605

timezone America/Santo_Domingo

readme https://ipinfo.io/missingauth

--------------
info=requests.get('https://ipinfo.io/json').json()

>>> list(info.keys())
['ip', 'hostname', 'city', 'region', 'country', 'loc', 'org', 'postal', 'timezone', 'readme']
>>> list(info.keys())[0]
'ip'
>>> info.get(list(info.keys())[0])
'45.32.165.238'


viernes, 23 de agosto de 2024

extracting int and str from list

lista=[233,5,6,1334,45,'Ambiorix',244,'Bonao']

t=[12345, 54321, 'hello!']


n=[a for a in lista if isinstance(a,int)==True]

s=[a for a in lista if isinstance(a,str)==True]

r= [a.upper() for a in t if isinstance(a,str)==True]

print(r)

['HELLO!']




print("List of numbers : ", n)

print("List of Strings :", s)

Check if list values are string or int

 



list1=[13,34,55,32,12,'mnz','jlz','rc']

res = isinstance(list1[7], str)


i=0

while i <len(list1):

    t=isinstance(list1[i], str)

  

    if t==True:

        

        print(list1[i].upper())

    else:

        print(list1[i] *  2)

    i=i+1

 

miércoles, 21 de agosto de 2024

reading file line by line

 # Define the path to your file

file_path = '/root/log.txt'


# Open the file and read it line by line

try:

    with open(file_path, 'r') as file:

        # Iterate over each line in the file with line numbers

        for line_number, line in enumerate(file, start=1):

            # Print the line number and the line content

            print(f"Line {line_number}: {line.strip()}")

except FileNotFoundError:

    print(f"The file at {file_path} was not found.")

except IOError as e:

    print(f"An I/O error occurred: {e}")


viernes, 16 de agosto de 2024

google tts

 

import os


import logging

import google.cloud.texttospeech as tts

os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/home/ambiorixg12/mycodes/google_speech/voice.json"


def text_to_wav(voice_name: str, text: str):

    language_code = "-".join(voice_name.split("-")[:2])

    text_input = tts.SynthesisInput(text=text)

    voice_params = tts.VoiceSelectionParams(

        language_code=language_code, name=voice_name

    )

    audio_config = tts.AudioConfig(audio_encoding=tts.AudioEncoding.LINEAR16)


    client = tts.TextToSpeechClient()

    response = client.synthesize_speech(

        input=text_input,

        voice=voice_params,

        audio_config=audio_config,

    )


    filename = f"{voice_name}.wav"

    with open(filename, "wb") as out:

        out.write(response.audio_content)

        print(f'Generated speech saved to "{filename}"')


text_to_wav("en-US-Studio-O", "What is the temperature in New York?")




https://codelabs.developers.google.com/codelabs/cloud-text-speech-python3#5

https://cloud.google.com/text-to-speech/docs/libraries?hl=es-419


https://github.com/googleapis/google-cloud-python/tree/main/packages/google-cloud-texttospeech/samples/generated_samples

request and urlib

 >> ip=json.loads(urllib.request.urlopen('https://ipinfo.io/json').read().decode('utf-8')).get('ip')

 ip_r=requests.get('https://ipinfo.io/json').json().get('ip')

jueves, 15 de agosto de 2024

reading json

 import urllib.request

import json


# Open the URL and read the content as bytes

info = urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_2066892.json ')

content = info.read()


# Decode the bytes to a string

content_str = content.decode('utf-8')


# Parse the JSON string into a Python dictionary

data = json.loads(content_str)


# Initialize the counter

total_count = 0


# Iterate through the comments and sum up the counts

for comment in data.get('comments', []):

    total_count += comment.get('count', 0)


# Print the total count of comments

print(f"Total count of comments: {total_count}")




//////////////////////






>>> info=json.loads(urllib.request.urlopen('https://ipinfo.io/json').read().decode('utf-8'))


1)  urllib.request.urlopen('https://ipinfo.io/json').read().decode()
a) Open the url

b) read the data as byte class

c) decode by data to utf as string object

 d) json.loads(str object)  // create dict from the string object

print(info)  // dict

{'ip': '148.0.197.54', 'hostname': '54.197.0.148.d.dyn.claro.net.do', 'city': 'Santo Domingo', 'region': 'Nacional', 'country': 'DO', 'loc': '18.4719,-69.8923', 'org': 'AS6400 Compañía Dominicana de Teléfonos S. A.', 'postal': '10201', 'timezone': 'America/Santo_Domingo', 'readme': 'https://ipinfo.io/missingauth'}


  // get dict value


>> ip=json.loads(urllib.request.urlopen('https://ipinfo.io/json').read().decode('utf-8')).get('ip')
 ip_r=requests.get('https://ipinfo.io/json').json().get('ip')
>>> print(ip)   
'148.0.197.54'



lunes, 12 de agosto de 2024

PYTHON XML 1

 To complete this assignment, you need to write a Python script that reads XML data from a given URL, parses the XML to extract numbers from `<count>` tags, and then computes the sum of these numbers. Here's a step-by-step guide on how to do this using Python's `xml.etree.ElementTree` for XML parsing and `urllib` for fetching the XML data.


### **Python Script for Extracting and Summing XML Data**


1. **Import Necessary Modules:**

   - Use `urllib.request` to fetch the XML data from the URL.

   - Use `xml.etree.ElementTree` to parse and navigate the XML data.


2. **Fetch and Parse XML Data:**

   - Retrieve the XML data using the URL.

   - Parse the XML data into an ElementTree object.


3. **Extract Data and Compute the Sum:**

   - Use XPath to find all `<count>` elements.

   - Convert the text content of each `<count>` element to an integer and compute the sum.


Here’s a complete Python script to achieve this:


```python

import urllib.request

import xml.etree.ElementTree as ET


def main():

    # Prompt for URL input

    url = input('Enter location: ')

    print('Retrieving', url)

    

    # Fetch the XML data

    response = urllib.request.urlopen(url)

    data = response.read()

    

    # Convert bytes to string and parse the XML

    tree = ET.fromstring(data)

    

    # Find all <count> elements using XPath

    counts = tree.findall('.//count')

    

    # Compute the sum of all counts

    total_sum = sum(int(count.text) for count in counts)

    

    # Print the number of <count> elements and the sum

    print('Count:', len(counts))

    print('Sum:', total_sum)


if __name__ == "__main__":

    main()

```


### **Explanation of the Code:**


1. **Fetching the Data:**

   ```python

   url = input('Enter location: ')

   response = urllib.request.urlopen(url)

   data = response.read()

   ```

   - Prompts the user for the URL and retrieves the XML data from that URL.


2. **Parsing the XML Data:**

   ```python

   tree = ET.fromstring(data)

   ```

   - Parses the XML data into an `ElementTree` object.


3. **Extracting `<count>` Elements:**

   ```python

   counts = tree.findall('.//count')

   ```

   - Uses XPath to find all `<count>` elements in the XML.


4. **Summing the Values:**

   ```python

   total_sum = sum(int(count.text) for count in counts)

   ```

   - Extracts the text from each `<count>` element, converts it to an integer, and computes the total sum.


5. **Output the Results:**

   ```python

   print('Count:', len(counts))

   print('Sum:', total_sum)

   ```

   - Prints the total number of `<count>` elements and the computed sum.


### **Running the Script:**


1. Save the script as `solution.py`.

2. Run the script using Python:

   ```bash

   python3 solution.py

   ```

3. Enter the URL when prompted, and the script will display the total count of `<count>` elements and their sum.


This script is designed to handle the XML format provided and can be adapted for similar XML data structures.

domingo, 11 de agosto de 2024

BeautifulSoup

 from urllib.request import urlopen

from bs4 import BeautifulSoup


# The URL of the page to scrape

url = 'https://py4e-data.dr-chuck.net/comments_42.html'


# Fetch the HTML content from the URL

html = urlopen(url).read()


# Parse the HTML with BeautifulSoup

soup = BeautifulSoup(html, 'html.parser')


# Now you can prettify and print the parsed HTML

print(soup.prettify())


https://beautiful-soup-4.readthedocs.io/en/latest/


sábado, 10 de agosto de 2024

Ollama

 import ollama


# Step 1: Pull the model

ollama.pull(model='llama2')


# Step 2: Use the model in a chat

response = ollama.chat(model='llama2', messages=[

  {

    'role': 'user',

    'content': 'Why is the sky blue?',

  },

])


print(response)

///////////////////////////////


import ollama
import time

# Function to pull the model with retries
def pull_model_with_retries(model_name, retries=3, delay=5):
    for attempt in range(retries):
        try:
            print(f"Pulling model '{model_name}', attempt {attempt + 1}")
            ollama.pull(model=model_name)
            print(f"Successfully pulled model '{model_name}'")
            return True
        except Exception as e:
            print(f"Failed to pull model '{model_name}' on attempt {attempt + 1}: {e}")
            if attempt < retries - 1:
                print(f"Retrying in {delay} seconds...")
                time.sleep(delay)
    print(f"Failed to pull model '{model_name}' after {retries} attempts")
    return False

# Attempt to pull the model with retries
if pull_model_with_retries('llama2'):
    # If successful, proceed with the chat
    response = ollama.chat(model='llama2', messages=[
      {
        'role': 'user',
        'content': 'Why is the sky blue?',
      },
    ])
    print(response)
else:
    print("Unable to pull model 'llama2'. Please check your connection and try again.")


###########################

import ollama

# List of potential smaller models (example names)
models = ['llama2-small', 'llama2-mini', 'llama2-base']

# Attempt to pull each model until one succeeds
for model in models:
    try:
        print(f"Attempting to pull model: {model}")
        ollama.pull(model=model)
        print(f"Successfully pulled model: {model}")
        
        # Use the model in a chat after successful pull
        response = ollama.chat(model=model, messages=[
          {
            'role': 'user',
            'content': 'Why is the sky blue?',
          },
        ])
        
        print(response)
        break
    except Exception as e:
        print(f"Failed to pull model {model}: {e}")

print("Finished pulling models.")

jueves, 8 de agosto de 2024

Working with datetime time and datetime object

>>> datetime.datetime.now()

datetime.datetime(2024, 8, 11, 21, 12, 36, 860592)

>>> datetime.datetime.now().time()

datetime.time(21, 12, 41, 511824)

>>> datetime.datetime.now().date()

datetime.date(2024, 8, 11)


>>> datetime.datetime.now()

datetime.datetime(2024, 8, 10, 11, 30, 45, 554555)


>>> datetime.datetime.now().year

2024

>>> datetime.datetime.now().month

8

>>> datetime.datetime.now().day

10


 Creating datetime.time object

time=datetime.time(23,59)

Getting hour

time.hour

23

Getting minutes   


time.minute

59

----------

Getting current datetime and time object

>>> datetime.datetime.now()
datetime.datetime(2024, 8, 8, 11, 37, 6, 478499)

Getting time  object

datetime.datetime.now().time()
datetime.time(11, 37, 34, 900228)

Getting hour

 datetime.datetime.now().time().hour

11

Minute
tetime.datetime.now().time().minute
39


Getting formated time object from the time object

datetime.time(23,59).strftime('%H:%S:%p')

'23:00:PM'


getting  same  hour and minute   but  from now date time object


datetime.datetime.now().strftime('%H:%S:%p')

'11:17:AM'


Creating an str list with time

>>> time= str(datetime.datetime.now().time()).split(':')

>>> time

['21', '03', '06.749331']


Other example

>>> datetime.datetime.now()
datetime.datetime(2024, 8, 11, 21, 7, 35, 295040)

>>> str(datetime.datetime.now())
'2024-08-11 21:07:46.766833'

>>> str(datetime.datetime.now()).split(" ")
['2024-08-11', '21:08:23.892977']

>>> str(datetime.datetime.now()).split(" ")[0]
'2024-08-11'

Calculating the missing days for dic


>>> dic=datetime.datetime(2024, 12, 1, 0, 0)

>>> dic-datetime.datetime.now()

datetime.timedelta(days=111, seconds=7993, microseconds=258309)


https://www.programiz.com/python-programming/datetime/strftime

Format Code List

The table below shows all the codes that you can pass to the strftime() method.

DirectiveMeaningExample
%aAbbreviated weekday name.Sun, Mon, ...
%AFull weekday name.Sunday, Monday, ...
%wWeekday as a decimal number.0, 1, ..., 6
%dDay of the month as a zero-padded decimal.01, 02, ..., 31
%-dDay of the month as a decimal number.1, 2, ..., 30
%bAbbreviated month name.Jan, Feb, ..., Dec
%BFull month name.January, February, ...
%mMonth as a zero-padded decimal number.01, 02, ..., 12
%-mMonth as a decimal number.1, 2, ..., 12
%yYear without century as a zero-padded decimal number.00, 01, ..., 99
%-yYear without century as a decimal number.0, 1, ..., 99
%YYear with century as a decimal number.2013, 2019 etc.
%HHour (24-hour clock) as a zero-padded decimal number.00, 01, ..., 23
%-HHour (24-hour clock) as a decimal number.0, 1, ..., 23
%IHour (12-hour clock) as a zero-padded decimal number.01, 02, ..., 12
%-IHour (12-hour clock) as a decimal number.1, 2, ... 12
%pLocale’s AM or PM.AM, PM
%MMinute as a zero-padded decimal number.00, 01, ..., 59
%-MMinute as a decimal number.0, 1, ..., 59
%SSecond as a zero-padded decimal number.00, 01, ..., 59
%-SSecond as a decimal number.0, 1, ..., 59
%fMicrosecond as a decimal number, zero-padded on the left.000000 - 999999
%zUTC offset in the form +HHMM or -HHMM. 
%ZTime zone name. 
%jDay of the year as a zero-padded decimal number.001, 002, ..., 366
%-jDay of the year as a decimal number.1, 2, ..., 366
%UWeek number of the year (Sunday as the first day of the week). All days in a new year preceding the first Sunday are considered to be in week 0.00, 01, ..., 53
%WWeek number of the year (Monday as the first day of the week). All days in a new year preceding the first Monday are considered to be in week 0.00, 01, ..., 53
%cLocale’s appropriate date and time representation.Mon Sep 30 07:06:05 2013
%xLocale’s appropriate date representation.09/30/13
%XLocale’s appropriate time representation.07:06:05
%%A literal '%' character.%




jueves, 1 de agosto de 2024

Using list and tuple for grouping dict based on a conditional value

# Online Python compiler (interpreter) to run Python online.

# Write Python 3 code in this online editor and 


st={'Ambiorix':90,'Katherine':89,'Armando':88,'Ruth':77,'Rosa':60,'Pedro':63,'Maria':74,'Jesus':100,'Juan':99}



tp=[tp for tp in st.items()]

print(tp)


for a in tp:

    if a[1]  >=70 and a[1]  <=79:

        print(a)

        

        

print('----------------')


def getrange(st,z,y):

    tp=[tp for tp in st.items()]

    

    for a in tp:

       if a[1]  >=z and a[1]  <=y:

        print(a)



getrange(st,0,69)

    

[('Ambiorix', 90), ('Katherine', 89), ('Armando', 88), ('Ruth', 77), ('Rosa', 60), ('Pedro', 63), ('Maria', 74), ('Jesus', 100), ('Juan', 99)]
('Ruth', 77)
('Maria', 74)
----------------
('Rosa', 60)
('Pedro', 63)