Month: June 2024
Copiot en Word no funciona igual que Copilot Web
El mismo Promt relativamente complejo en Word no lo reconoce y en Web funciona perfectamente.
El mismo Promt relativamente complejo en Word no lo reconoce y en Web funciona perfectamente. Read More
extracting car plate from cell
I have to extract car plate from bank reference column. there are more than 10000 lines per month. The position of the car plate in the string varies. The car plate has min of 5 and max 10 alphabet+ numbers in it. What formula can I use for this?
I have to extract car plate from bank reference column. there are more than 10000 lines per month. The position of the car plate in the string varies. The car plate has min of 5 and max 10 alphabet+ numbers in it. What formula can I use for this? Read More
Prepare for Your Next Certification
Introduction
Have you studied for a certification before and struggled with memorizing some of the content you have read?
I have indeed struggled with it! An example is that I studied for the Endpoint Administrator (MD-102) certification, where I had to memorize the different app types in Intune. Do you know what helped me? Flashcards!
I am excited to tell you more about a workshop where you can create your own flashcards later in this blog.
First, I will give you my tips and tricks for studying for a certification.
Studying for a Microsoft Certification
Are you looking at starting with a Microsoft certification and are wondering how to get started? Look no further, I will give you some tips and tricks below.
First of all, I would recommend you take a look at the study guide. For this example, I will be using the MD-102 study guide. The study guide will be give you some insights on how much each topic will be covered in percentage on the exam.
Once you have become familiar with the study guide, it’s time to learn! There isn’t a better place learning, then Microsoft Learn. Here you have free materials that will help you prepare for your exam.
Lastly, you will have to test your knowledge to see if you are ready for the exam. On the MD-102 exam, there are free practice assessments that will give you an idea of whether you are ready for the exam.
I hope these tips and tricks will help you prepare for your certification. If you have any other tips, let us know in the comment section!
Flashcards with Microsoft Fabric and Azure OpenAI
When I had to use flashcards, I always had to create them manually. It takes a lot of time, which is better spent on reading and learning about the certification you are trying to achieve. You wouldn’t believe me if I told you that, with a little work, you could actually use content directly from Microsoft Learn. This workshop will help you create your own flashcards with Fabric and OpenAI.
If you are interested in getting started, I would recommend you take a look at Github.
There is a guide on how to setup the environment for the workshop with step-by-step guidance.
Conclusion
Flashcards are great if you have to memorize certain topics when you are reading content for a certification. It takes a lot of time to create manually, but I hope this solution can help you in the future. It’s important to say that this solution can also help you prepare for certification renewals.
I hope that the tips from this blog can help you get started on your next Microsoft certification!
Microsoft Tech Community – Latest Blogs –Read More
Using MLX Framewrok with Phi-3
Previously, I shared with you how to use Phi-3-mini on AIPC’s NPU and iPhone. Some people want to know more about the experience of using macOS and how to use Apple Silicon to accelerate SLM models. This blog will share with you relevant knowledge, including how to use Apple MLX Framework to accelerate Phi-3-mini operation, fine-tune, and combine Llama.cpp for quantitative operation.
What’s MLX Framework
MLX is an array framework for machine learning research on Apple silicon, brought to you by Apple machine learning research.
MLX is designed by machine learning researchers for machine learning researchers. The framework is intended to be user-friendly, but still efficient to train and deploy models. The design of the framework itself is also conceptually simple. We intend to make it easy for researchers to extend and improve MLX with the goal of quickly exploring new ideas.
LLMs can be accelerated in Apple Silicon devices through MLX, and models can be run locally very conveniently.
Installation
Installing MLX is easy, you will need Python 3.11.x+, then install it in the terminal
pip install mlx-lm
Run MLX’s instructions
1. Running Phi-3-mini in Terminal with MLX
python -m mlx_lm.generate –model microsoft/Phi-3-mini-4k-instruct –max-token 2048 –prompt “<|user|>nCan you introduce yourself<|end|>n<|assistant|>”
2. Quantizing Phi-3-mini with MLX in Terminal
python -m mlx_lm.convert –hf-path microsoft/Phi-3-mini-4k-instruct
3. Running Phi-3-mini with MLX in Jupyter Notebook
Note: Please read Inference Phi-3 with Apple MLX Framework to Learn more
Fine-tuning with MLX Framework
We generally need GPU acceleration to complete model training or fine-tuning, but in Apple devices you can use Apple silicon’s MPS(Metal Performance Shaders) to replace the GPU to complete model training and fine-tuning.
What’s Metal Performance Shaders
The Metal Performance Shaders framework contains a collection of highly optimized compute and graphics shaders that are designed to integrate easily and efficiently into your Metal app. These data-parallel primitives are specially tuned to take advantage of the unique hardware characteristics of each GPU family to ensure optimal performance.
Sample – Using LoRA to fine-tuning Phi-3-mini with MLX
1. Data preparation
By default, MLX Framework requires the jsonl format of train, test, and eval, and is combined with Lora to complete fine-tuning jobs.
Note:
jsonl data format :
{“text”: “<|user|>nWhen were iron maidens commonly used? <|end|>n<|assistant|> nIron maidens were never commonly used <|end|>”}
{“text”: “<|user|>nWhat did humans evolve from? <|end|>n<|assistant|> nHumans and apes evolved from a common ancestor <|end|>”}
{“text”: “<|user|>nIs 91 a prime number? <|end|>n<|assistant|> nNo, 91 is not a prime number <|end|>”}
….
Our example uses TruthfulQA’s data , but the amount of data is relatively insufficient, so the fine-tuning results are not necessarily the best. It is recommended that learners use better data based on their own scenarios to complete.
The data format is combined with the Phi-3 template
Please download data from this link , please inculde all .jsonl in data folder
2. Fine-tuning in your terminal
Please run this command in terminal
python -m mlx_lm.lora –model microsoft/Phi-3-mini-4k-instruct –train –data ./data –iters 1000
Note: This is LoRA fine-tuning, MLX framework not published QLoRA
3. Run Fine-tuning adapter to test
You can run fine-tuning adapter in terminal,like this
python -m mlx_lm.generate –model microsoft/Phi-3-mini-4k-instruct –adapter-path ./adapters –max-token 2048 –prompt “Why do chameleons change colors? “ –eos-token “<|end|>”
and run original model to compare result
python -m mlx_lm.generate –model microsoft/Phi-3-mini-4k-instruct –max-token 2048 –prompt “Why do chameleons change colors? “ –eos-token “<|end|>”
You can try to compare the results of Fine-tuning with the original model
4. Merge adapters to generate new models
python -m mlx_lm.fuse –model microsoft/Phi-3-mini-4k-instruct
5. Running quantified fine-tuning models using ollama
Before use, please configure your llama.cpp environment
git clone https://github.com/ggerganov/llama.cpp.git
cd llama.cpp
pip install -r requirements.txt
python convert.py ‘Your meger model path’ –outfile phi-3-mini-ft.gguf –outtype f16
Note:
Now supports quantization conversion of fp32, fp16 and INT 8
The merged model is missing tokenizer.model, please download it from https://huggingface.co/microsoft/Phi-3-mini-4k-instruct
set Ollma Model file(If not install ollama ,please read [Ollama QuickStart](../02.QuickStart/Ollama_QuickStart.md)
FROM ./phi-3-mini-ft.gguf
PARAMETER stop “<|end|>”
run command in terminal
ollama create phi3ft -f Modelfile
ollama run phi3ft “Why do chameleons change colors?”
Note: Please read Fine-tuning Phi-3 with Apple MLX Framework to Learn more
Resources
Read Phi-3 CookBook https://aka.ms/phi-3cookbook
MLX framework Repo https://github.com/ml-explore
Learn more about MLX Framework https://ml-explore.github.io/mlx/
Hugging face Phi-3 Family https://huggingface.co/collections/microsoft/phi-3-6626e15e9585a200d2d761e3
Microsoft Tech Community – Latest Blogs –Read More
Can I replace the vehicle physics in Carla with a custom vehicle model?
I want to create a vehicle dynamics model using MATLAB/Simulink and replace the vehicle model in Carla with it.
Thank youI want to create a vehicle dynamics model using MATLAB/Simulink and replace the vehicle model in Carla with it.
Thank you I want to create a vehicle dynamics model using MATLAB/Simulink and replace the vehicle model in Carla with it.
Thank you carla, vehicle dynamics MATLAB Answers — New Questions
MATLAB does not launch correctly
I have installed MATLAB 2023b and I already have MATLAB 2022b. When I tried to launch MATLAB 2023b, unfortunately, MATLAB 2022b launched instead.
I really appreciate any help.
Thanks in advance.I have installed MATLAB 2023b and I already have MATLAB 2022b. When I tried to launch MATLAB 2023b, unfortunately, MATLAB 2022b launched instead.
I really appreciate any help.
Thanks in advance. I have installed MATLAB 2023b and I already have MATLAB 2022b. When I tried to launch MATLAB 2023b, unfortunately, MATLAB 2022b launched instead.
I really appreciate any help.
Thanks in advance. launching MATLAB Answers — New Questions
License checkout failed. License Manager Error -39 User/host not on INCLUDE list for Simulink_Compiler.
Hello,
I’m trying to run a MATLAB demo application "Generate and Deploy a MATLAB App with SimAppTemplate for a Model" which generates a MATLAB App from the model. When I run the command from the demo, I get this error:
openExample(‘simulinkcompiler/GenerateAndDeployAMATLABAppForAModelExample’)
open_system(‘f14_mod’)
simulink.compiler.genapp(‘f14_mod’, ‘AppName’, ‘f14app’,’Template’, ‘SimAppTemplate’);
Error using simulink.compiler.genapp
License checkout failed.
License Manager Error -39
User/host not on INCLUDE list for Simulink_Compiler.
Contact your License Administrator to review the Options File.
Troubleshoot this issue by visiting:
https://www.mathworks.com/support/lme/39
Diagnostic Information:
Feature: Simulink_Compiler
License path:
27000@de0-viaas-1360.eu.airbus.corp,27000@de0-viaas-1361.eu.airbus.corp,27000@de0-viaas-1362.eu.airbus.corp;C:UsersMWAGNLSHAppDataRoamingMathWorksMATLABR2024a_licenses;C:Program
FilesMATLABR2024alicenseslicense.dat;C:Program FilesMATLABR2024alicensesnetwork.lic
Licensing error: -39,147.
It looks like there is a problem getting a license or my PC is not in a specific list: "User/host not on INCLUDE list for Simulink_Compiler." Can someone help me with this problem?
BTW when I run the "ver" command I see the license in the List.
……
Simulink Coder Version 24.1 (R2024a)
Simulink Compiler Version 24.1 (R2024a)
Simulink Control Design Version 24.1 (R2024
……
Best regardsHello,
I’m trying to run a MATLAB demo application "Generate and Deploy a MATLAB App with SimAppTemplate for a Model" which generates a MATLAB App from the model. When I run the command from the demo, I get this error:
openExample(‘simulinkcompiler/GenerateAndDeployAMATLABAppForAModelExample’)
open_system(‘f14_mod’)
simulink.compiler.genapp(‘f14_mod’, ‘AppName’, ‘f14app’,’Template’, ‘SimAppTemplate’);
Error using simulink.compiler.genapp
License checkout failed.
License Manager Error -39
User/host not on INCLUDE list for Simulink_Compiler.
Contact your License Administrator to review the Options File.
Troubleshoot this issue by visiting:
https://www.mathworks.com/support/lme/39
Diagnostic Information:
Feature: Simulink_Compiler
License path:
27000@de0-viaas-1360.eu.airbus.corp,27000@de0-viaas-1361.eu.airbus.corp,27000@de0-viaas-1362.eu.airbus.corp;C:UsersMWAGNLSHAppDataRoamingMathWorksMATLABR2024a_licenses;C:Program
FilesMATLABR2024alicenseslicense.dat;C:Program FilesMATLABR2024alicensesnetwork.lic
Licensing error: -39,147.
It looks like there is a problem getting a license or my PC is not in a specific list: "User/host not on INCLUDE list for Simulink_Compiler." Can someone help me with this problem?
BTW when I run the "ver" command I see the license in the List.
……
Simulink Coder Version 24.1 (R2024a)
Simulink Compiler Version 24.1 (R2024a)
Simulink Control Design Version 24.1 (R2024
……
Best regards Hello,
I’m trying to run a MATLAB demo application "Generate and Deploy a MATLAB App with SimAppTemplate for a Model" which generates a MATLAB App from the model. When I run the command from the demo, I get this error:
openExample(‘simulinkcompiler/GenerateAndDeployAMATLABAppForAModelExample’)
open_system(‘f14_mod’)
simulink.compiler.genapp(‘f14_mod’, ‘AppName’, ‘f14app’,’Template’, ‘SimAppTemplate’);
Error using simulink.compiler.genapp
License checkout failed.
License Manager Error -39
User/host not on INCLUDE list for Simulink_Compiler.
Contact your License Administrator to review the Options File.
Troubleshoot this issue by visiting:
https://www.mathworks.com/support/lme/39
Diagnostic Information:
Feature: Simulink_Compiler
License path:
27000@de0-viaas-1360.eu.airbus.corp,27000@de0-viaas-1361.eu.airbus.corp,27000@de0-viaas-1362.eu.airbus.corp;C:UsersMWAGNLSHAppDataRoamingMathWorksMATLABR2024a_licenses;C:Program
FilesMATLABR2024alicenseslicense.dat;C:Program FilesMATLABR2024alicensesnetwork.lic
Licensing error: -39,147.
It looks like there is a problem getting a license or my PC is not in a specific list: "User/host not on INCLUDE list for Simulink_Compiler." Can someone help me with this problem?
BTW when I run the "ver" command I see the license in the List.
……
Simulink Coder Version 24.1 (R2024a)
Simulink Compiler Version 24.1 (R2024a)
Simulink Control Design Version 24.1 (R2024
……
Best regards license, error: -39, simulink_compiler, .compiler.genapp, user/host not on include list MATLAB Answers — New Questions
Getting Namespaces are not supported error during build
Getting the below error for a adaptive autosar model during build
Error:Unexpected or internal error encountered in "in CGIR: B:matlabsrccg_irbaseNamespace.cpp line 13: B:matlabsrccg_irbaseNamespace.cpp(13): In getOrCreateChild: Assertion failed: !aName.empty() Anonymous Namespaces are not supported
". Please report this to MathWorks if you can cause it to recurGetting the below error for a adaptive autosar model during build
Error:Unexpected or internal error encountered in "in CGIR: B:matlabsrccg_irbaseNamespace.cpp line 13: B:matlabsrccg_irbaseNamespace.cpp(13): In getOrCreateChild: Assertion failed: !aName.empty() Anonymous Namespaces are not supported
". Please report this to MathWorks if you can cause it to recur Getting the below error for a adaptive autosar model during build
Error:Unexpected or internal error encountered in "in CGIR: B:matlabsrccg_irbaseNamespace.cpp line 13: B:matlabsrccg_irbaseNamespace.cpp(13): In getOrCreateChild: Assertion failed: !aName.empty() Anonymous Namespaces are not supported
". Please report this to MathWorks if you can cause it to recur namespaces MATLAB Answers — New Questions
150Hz Sine wave in MATLAB simulink
When I feed 150 Hz to a sine wave block with scope settings of 0.04 seconds of time span and 0.00166 as sample time, my output wave looks like a triangle wave rather than a sine wave. How do I make it appear as a sine wave?When I feed 150 Hz to a sine wave block with scope settings of 0.04 seconds of time span and 0.00166 as sample time, my output wave looks like a triangle wave rather than a sine wave. How do I make it appear as a sine wave? When I feed 150 Hz to a sine wave block with scope settings of 0.04 seconds of time span and 0.00166 as sample time, my output wave looks like a triangle wave rather than a sine wave. How do I make it appear as a sine wave? matlab, simulink, sinewave, scope MATLAB Answers — New Questions
How to deploy Angular + Java Springboot into Azure app service using Azure Release Pipeline ?
Hi everyone. Good morning/evening.
We are working on developing a new POC application & need some help with the Azure CI/CD pipeline. Our application is based on frontend as angular & backend as java springboot. We were able to run the build pipeline successfully and publish the artifacts to JFrog artifactory. However, the next challenge we have is how to deploy it to an Azure App Service.
Our frontend is running on Angular 16 and backend is java springboot. We have 2 separate artifacts, frontend is generating a dist folder wrapped with tar.gz file & backend is generating a jar file. How can we deploy this together into an Azure App Service using azure devops release pipeline?
Hi everyone. Good morning/evening.We are working on developing a new POC application & need some help with the Azure CI/CD pipeline. Our application is based on frontend as angular & backend as java springboot. We were able to run the build pipeline successfully and publish the artifacts to JFrog artifactory. However, the next challenge we have is how to deploy it to an Azure App Service. Our frontend is running on Angular 16 and backend is java springboot. We have 2 separate artifacts, frontend is generating a dist folder wrapped with tar.gz file & backend is generating a jar file. How can we deploy this together into an Azure App Service using azure devops release pipeline? Read More
Not able to integrate ai multi service
HI am having just the hardest time trying to integrate the Azure AI multi-service in to any sort of copilot (teams, copilot studio, 365 in ms 365 app or teams app or outlooks app, or any copilot. It seems impossible to get this in to a copilot or any ai bot. Any help at all? With at least services like Decision, L, S, V and DI. or – at least least – V, L, DI. Thanks! Matt
HI am having just the hardest time trying to integrate the Azure AI multi-service in to any sort of copilot (teams, copilot studio, 365 in ms 365 app or teams app or outlooks app, or any copilot. It seems impossible to get this in to a copilot or any ai bot. Any help at all? With at least services like Decision, L, S, V and DI. or – at least least – V, L, DI. Thanks! Matt Read More
“Organize mail by thread” for Outlook for Mac
Hello, when do you think we can expect the “Organize mail by thread” feature for Outlook for Mac?
Hello, when do you think we can expect the “Organize mail by thread” feature for Outlook for Mac? Read More
Can anyone record me an easy to use Windows screen recorder?
Sometimes I need to record tutorial videos on my computer for our customers. I search and found that Xbox game bar is a good option. I use it, it did capture my screen. However, it failed to record popup from the software and did not capture all my operations.
Can anyone record me a simple screen recorder for PC? It should allow me to:
Record part of my screenRecord app and file explorer Record screen and webcam at the same timeCapture screen in high resolution
I really need to have such a screen recorder for my work. Thanks!
Please don’t record me OBS studio. I downloaded the open-source app and used it. Sorry, it is so hard for me to record selected area of my screen. It seems that I need to input the distance by pixels.
Sometimes I need to record tutorial videos on my computer for our customers. I search and found that Xbox game bar is a good option. I use it, it did capture my screen. However, it failed to record popup from the software and did not capture all my operations. Can anyone record me a simple screen recorder for PC? It should allow me to: Record part of my screenRecord app and file explorer Record screen and webcam at the same timeCapture screen in high resolution I really need to have such a screen recorder for my work. Thanks!Please don’t record me OBS studio. I downloaded the open-source app and used it. Sorry, it is so hard for me to record selected area of my screen. It seems that I need to input the distance by pixels. Read More
Project Online – Project Owner is changing to old owner automatically.
In project online the owner of project keeps changing to previous(old) owner automatically. Even if we change it back to new owner after some days it will revert back to old owner. Can anyone help me solving this issue.
In project online the owner of project keeps changing to previous(old) owner automatically. Even if we change it back to new owner after some days it will revert back to old owner. Can anyone help me solving this issue. Read More
Windows Login MFA via Intune
Dear Experts,
Does Microsoft support MFA on windows login via Intune?
I know there are third party tools for this but can we enforce windows login MFA via Intune?
Dear Experts,Does Microsoft support MFA on windows login via Intune?I know there are third party tools for this but can we enforce windows login MFA via Intune? Read More
Create Your First Visual Agent Using AOAI and AI Search – Search Product Catalog Images
Search Product Catalog Images Using Azure Search and OpenAI with Langchain
In the ever-evolving landscape of retail, businesses are continually seeking innovative solutions to streamline their operations and enhance customer experiences. One such breakthrough is the implementation of artificial intelligence (AI) to search product catalog images efficiently. This transformative technology not only simplifies the search process but also empowers businesses to provide personalized and seamless shopping experiences for their customers.
The Need for AI in Product Catalog Image Search: Traditional methods of searching through product catalogs involve manual tagging and categorization, which can be time-consuming and prone to human error. As the volume of products in a catalog grows, managing and searching for specific items becomes a daunting task. AI, particularly computer vision, addresses these challenges by automating the recognition and categorization of products in images.
Key Features of AI-Powered Product Catalog Image Search:
Object Recognition and Tagging: AI algorithms can identify and tag objects within images, providing accurate and consistent categorization of products. This reduces the reliance on manual tagging, ensuring that products are correctly labeled in the catalog.
Visual Similarity Search: AI enables visual similarity search, allowing users to find products based on visual attributes rather than relying solely on text-based queries. This feature is especially valuable for customers who may struggle to describe a product in words but can easily recognize it visually.
Enhanced Product Discovery: By understanding the visual characteristics of products, AI facilitates a more sophisticated recommendation system. Customers can discover related or complementary items, leading to increased cross-selling opportunities and a more engaging shopping experience.
Improved Accuracy and Efficiency: AI-powered image recognition is highly accurate and can process large volumes of images in a fraction of the time it would take a human. This efficiency not only reduces operational costs but also enhances the speed at which customers can find and purchase products.
Integration with E-Commerce Platforms: AI-driven image search can seamlessly integrate with existing e-commerce platforms, making it easy for businesses to adopt this technology without major disruptions. This integration allows for a smoother transition and ensures that the AI-enhanced search becomes an integral part of the overall shopping experience.
Now lets try to implement this with Azure OpenAI.
Firs you need to import some libraries
import azure.cognitiveservices.speech as speechsdk
import datetime
import io
import json
import math
import matplotlib.pyplot as plt
import numpy as np
import openai
import os
import random
import requests
import sys
import time
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes import SearchIndexerClient
from azure.search.documents.indexes.models import (
SearchIndexerDataContainer,
SearchIndexerDataSourceConnection,
)
from azure.storage.blob import BlobServiceClient, generate_blob_sas, BlobSasPermissions
from azure.cognitiveservices.speech import (
AudioDataStream,
SpeechConfig,
SpeechSynthesizer,
SpeechSynthesisOutputFormat,
)
from azure.cognitiveservices.speech.audio import AudioOutputConfig
from azure.search.documents.models import VectorizedQuery,VectorizableTextQuery
from dotenv import load_dotenv
from io import BytesIO
from IPython.display import Audio
from PIL import Image
import os
import base64
import re
from datetime import datetime, timedelta
import requests
import os
from tenacity import (
Retrying,
retry_if_exception_type,
wait_random_exponential,
stop_after_attempt
)
import json
import mimetypes
Initiate some environmental variable for your
Azure OpenAI Endpoint
Azure Cognitive Service End point
Azure Search End point
load_dotenv(“azure.env”)
# Azure Open AI
openai_api_type = os.getenv(“azure”)
openai_api_base = os.getenv(“AZURE_OPENAI_ENDPOINT”)
openai_api_version = os.getenv(“AZURE_API_VERSION”)
openai_api_key = os.getenv(“AZURE_OPENAI_KEY”)
# Azure Cognitive Search
acs_endpoint = os.getenv(“ACS_ENDPOINT”)
acs_key = os.getenv(“ACS_KEY”)
# Azure Computer Vision 4
acv_key = os.getenv(“ACV_KEY”)
acv_endpoint = os.getenv(“ACV_ENDPOINT”)
blob_connection_string = os.getenv(“BLOB_CONNECTION_STRING”)
container_name = os.getenv(“CONTAINER_NAME”)
# Azure Cognitive Search index name to create
index_name = “azure-fashion-demo”
# Azure Cognitive Search api version
api_version = “2023-02-01-preview”
Now lets create a function to create text embedding using vision API
def text_embedding(prompt):
“””
Text embedding using Azure Computer Vision 4.0
“””
version = “?api-version=” + api_version + “&modelVersion=latest”
vec_txt_url = f”{acv_endpoint}/computervision/retrieval:vectorizeText{version}”
headers = {“Content-type”: “application/json”, “Ocp-Apim-Subscription-Key”: acv_key}
payload = {“text”: prompt}
response = requests.post(vec_txt_url, json=payload, headers=headers)
if response.status_code == 200:
text_emb = response.json().get(“vector”)
return text_emb
else:
print(f”Error: {response.status_code} – {response.text}”)
return None
Lets Now lets create a function to create Image embedding using vision API
def image_embedding(image_path):
url = f”{acv_endpoint}/computervision/retrieval:vectorizeImage”
mime_type, _ = mimetypes.guess_type(image_path)
headers = {
“Content-Type”: mime_type,
“Ocp-Apim-Subscription-Key”: acv_key
}
for attempt in Retrying(
retry=retry_if_exception_type(requests.HTTPError),
wait=wait_random_exponential(min=15, max=60),
stop=stop_after_attempt(15)
):
with attempt:
with open(image_path, ‘rb’) as image_data:
response = requests.post(url, params=params, headers=headers, data=image_data)
if response.status_code != 200:
response.raise_for_status()
vector = response.json()[“vector”]
return vector
Next thing we require is to create a function which takes a text prompt as input and search Azure Search for most relevant images. Here Buy Now Link is a dummy link which can be replaced with actual product URL
def prompt_search(prompt, topn=5, disp=False):
“””
Azure Cognitive visual search using a prompt
“””
results_list = []
# Initialize the Azure Cognitive Search client
search_client = SearchClient(acs_endpoint, index_name, AzureKeyCredential(acs_key))
blob_service_client = BlobServiceClient.from_connection_string(blob_connection_string)
container_client = blob_service_client.get_container_client(container_name)
# Perform vector search
vector_query = VectorizedQuery(vector=text_embedding(prompt), k_nearest_neighbors=topn, fields=”image_vector”)
response = search_client.search(
search_text=prompt, vector_queries= [vector_query], select=[“description”], top = 2
)
for nb, result in enumerate(response, 1):
blob_name = result[“description”] + “.jpg”
blob_client = container_client.get_blob_client(blob_name)
image_url = blob_client.url
sas_token = generate_blob_sas(
blob_service_client.account_name,
container_name,
blob_name,
account_key=blob_client.credential.account_key,
permission=BlobSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1)
)
sas_url = blob_client.url + “?” + sas_token
results_list.append({“buy_now_link” : sas_url,”price_of_the_product”: result[“description”], “product_image_url”: sas_url})
return results_list
Lets ingest some Product Images to the Azure Search. Here we are basically the idea is we have folder called images having all the product images stored. We are basically creating a container and uploading all the images from the folder to the specific container.
EMBEDDINGS_DIR = “embeddings”
os.makedirs(EMBEDDINGS_DIR, exist_ok=True)
image_directory = os.path.join(‘images’)
embedding_directory = os.path.join(’embeddings’)
output_json_file = os.path.join(embedding_directory, ‘output.jsonl’)
for root, dirs, files in os.walk(image_directory):
for file in files:
local_file_path = os.path.join(root, file)
blob_name = os.path.relpath(local_file_path, image_directory)
with open(local_file_path, “rb”) as data:
blob_client.upload_blob(data, overwrite=True)
Next we will create the embedding of the product images and store the same locally in the embedding directory. Point to note is that we have used only 2 metadata id and description. You can basically extend to many more metadata like price, buy now link etc.
with open(output_json_file, ‘w’) as outfile:
for idx, image_path in enumerate(os.listdir(image_directory)):
if image_path:
try:
vector = image_embedding(os.path.join(image_directory, image_path))
except Exception as e:
print(f”Error processing image at index {idx}: {e}”)
vector = None
filename, _ = os.path.splitext(os.path.basename(image_path))
result = {
“id”: f'{idx}’,
“image_vector”: vector,
“description”: filename
}
outfile.write(json.dumps(result))
outfile.write(‘n’)
outfile.flush()
print(f”Results are saved to {output_json_file}”)
Now since have created the local embedding file , we can upload the same into a Azure Search. Before that lets create an index .
from azure.search.documents.indexes import SearchIndexClient
from azure.search.documents.indexes.models import (
SimpleField,
SearchField,
SearchFieldDataType,
VectorSearch,
HnswAlgorithmConfiguration,
VectorSearchProfile,
SearchIndex
)
credential = AzureKeyCredential(acs_key)
# Create a search index
index_client = SearchIndexClient(endpoint=acs_endpoint, credential=credential)
fields = [
SimpleField(name=”id”, type=SearchFieldDataType.String, key=True),
SearchField(name=”description”, type=SearchFieldDataType.String, sortable=True, filterable=True, facetable=True),
SearchField(
name=”image_vector”,
hidden=True,
type=SearchFieldDataType.Collection(SearchFieldDataType.Single),
searchable=True,
vector_search_dimensions=1024,
vector_search_profile_name=”myHnswProfile”
),
]
# Configure the vector search configuration
vector_search = VectorSearch(
algorithms=[
HnswAlgorithmConfiguration(
name=”myHnsw”
)
],
profiles=[
VectorSearchProfile(
name=”myHnswProfile”,
algorithm_configuration_name=”myHnsw”,
)
],
)
# Create the search index with the vector search configuration
index = SearchIndex(name=index_name, fields=fields, vector_search=vector_search)
result = index_client.create_or_update_index(index)
print(f”{result.name} created”)
Once you have created the index , you can upload the locally stored index file.
from azure.search.documents import SearchClient
import json
data = []
with open(output_json_file, ‘r’) as file:
for line in file:
# Remove leading/trailing whitespace and parse JSON
json_data = json.loads(line.strip())
data.append(json_data)
search_client = SearchClient(endpoint=acs_endpoint, index_name=index_name, credential=credential)
results = search_client.upload_documents(data)
for result in results:
print(f’Indexed {result.key} with status code {result.status_code}’)
Congratulations you have finally ready to implement your Agent using OpenAI
Lets create tool called image search which will be used by the Agent
from typing import Optional
from langchain_core.callbacks import CallbackManagerForToolRun
from langchain_core.tools import BaseTool
from util import prompt_search
class ImageSearchResults(BaseTool):
“””Tool that queries the Fashion Image Search API and gets back json.”””
name: str = “image_search_results_json”
description: str = (
“A wrapper around Image Search. “
“Useful for when you need search fashion images related to cloth , shoe etc”
“Input should be a search query. Output is a JSON array of the query results”
)
num_results: int = 4
def _run(
self,
query: str,
run_manager: Optional[CallbackManagerForToolRun] = None,
) -> str:
“””Use the tool.”””
return str(prompt_search(prompt = query, topn=self.num_results))
Here we will be using Langchain to implement our Fashion Agent called Luca
from langchain_core.prompts.chat import (
BaseMessagePromptTemplate,
ChatPromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
PromptTemplate,
)
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
from langchain_core.runnables import Runnable, RunnablePassthrough
from langchain_community.tools.convert_to_openai import format_tool_to_openai_function
from langchain_core.utils.function_calling import convert_to_openai_function
from langchain.agents.output_parsers.openai_functions import (
OpenAIFunctionsAgentOutputParser,
)
from langchain.agents.format_scratchpad.openai_functions import (
format_to_openai_function_messages,
)
from langchain.agents import AgentExecutor
from langchain_openai import AzureChatOpenAI
from langchain_core.runnables import RunnableConfig
from custom_tool import ImageSearchResults
import openai
Lets initialize our LLM
from langchain_openai import AzureChatOpenAI
llm = AzureChatOpenAI(
api_key=os.environ[“AZURE_OPENAI_KEY”],
api_version=”2023-12-01-preview”,
azure_endpoint=os.environ[“AZURE_OPENAI_ENDPOINT”],
model=”gpt-4-turbo”,
)
llm(messages=[HumanMessage(content = “Hi”)])
prefix=”””You are Luca a helpful Fashion Agent who help people navigating and buying products online
Note:
\ Show Prices always in INR
\ Always try user to buy from the buy now link provided”””
suffix = “”
Lets attach tool we created, here we are using LCEL to implement out agent
tools = [ImageSearchResults(num_results=5)]
llm_with_tools = llm.bind(
functions=[convert_to_openai_function(t) for t in tools]
)
messages = [
SystemMessage(content=prefix),
HumanMessagePromptTemplate.from_template(“{input}”),
AIMessage(content=suffix),
MessagesPlaceholder(variable_name=”agent_scratchpad”),
]
input_variables = [“input”, “agent_scratchpad”]
prompt = ChatPromptTemplate(input_variables=input_variables, messages=messages)
agent = (
RunnablePassthrough.assign(
agent_scratchpad=lambda x: format_to_openai_function_messages(
x[“intermediate_steps”]
)
)
| prompt
| llm_with_tools
| OpenAIFunctionsAgentOutputParser()
)
Congratulation !! You are ready to test your Agent
response = agent_executor.invoke(
{
“input”: “I am looking for some summer dress as I am travelling to new Delhi”,
“chat_history”: [
HumanMessage(content=”hi! my name is bob”),
AIMessage(content=”Hello Bob! How can I assist you today?”),
],
}
)
Hurray !! You are now ready to deploy this Agent to a Enterprise App with some good looking UI.
Here is the reference github repo with all the code artifact.
https://github.com/monuminu/AOAI_Samples/tree/main/content_product_tagging
Favor : Please clap if you like this and Follow me for more such content.
References:
Microsoft Tech Community – Latest Blogs –Read More
export an fbx file or directly import it into to unreal engine
Perhaps, an FBX could be used to ‘cover’ a robot or a rigid body tree in the VIRTUAL WORLD and then be exported to the UNREAL ENGINE either as a SKELETAL MESH, FBX, or as a data flow of movements to the UNREAL ENGINE.Perhaps, an FBX could be used to ‘cover’ a robot or a rigid body tree in the VIRTUAL WORLD and then be exported to the UNREAL ENGINE either as a SKELETAL MESH, FBX, or as a data flow of movements to the UNREAL ENGINE. Perhaps, an FBX could be used to ‘cover’ a robot or a rigid body tree in the VIRTUAL WORLD and then be exported to the UNREAL ENGINE either as a SKELETAL MESH, FBX, or as a data flow of movements to the UNREAL ENGINE. fbx, unreal engine MATLAB Answers — New Questions
fmi2ExitInitializationMode error
Hello Team,
I am importing one FMU from GT suite (2024 build 1 version) to matlab (2021b) , and giving 3 inputs to calculate one output, but when I try to run them model, I am getting an error stating " An error occurred while running the simulation and the simulation was terminated
Caused by:
Error in supplied FMU: An error occurred in function ‘fmi2ExitInitializationMode’ for block ‘GT_FMU/FMU’ during simulation. To debug your FMU file, select the "Enable FMU Debug Logging" check box. For more information, see the FMU troubleshooting documentation. "
Please help me with this.Hello Team,
I am importing one FMU from GT suite (2024 build 1 version) to matlab (2021b) , and giving 3 inputs to calculate one output, but when I try to run them model, I am getting an error stating " An error occurred while running the simulation and the simulation was terminated
Caused by:
Error in supplied FMU: An error occurred in function ‘fmi2ExitInitializationMode’ for block ‘GT_FMU/FMU’ during simulation. To debug your FMU file, select the "Enable FMU Debug Logging" check box. For more information, see the FMU troubleshooting documentation. "
Please help me with this. Hello Team,
I am importing one FMU from GT suite (2024 build 1 version) to matlab (2021b) , and giving 3 inputs to calculate one output, but when I try to run them model, I am getting an error stating " An error occurred while running the simulation and the simulation was terminated
Caused by:
Error in supplied FMU: An error occurred in function ‘fmi2ExitInitializationMode’ for block ‘GT_FMU/FMU’ during simulation. To debug your FMU file, select the "Enable FMU Debug Logging" check box. For more information, see the FMU troubleshooting documentation. "
Please help me with this. fmu, gtsuite, matlab compiler, simulink, fixed step MATLAB Answers — New Questions
FMU run time issue
Hello Team,
I have a thermal model with conductive elements and have created a cylindrical cell model in Matlab 2021b, when I try to connect the cylindrical cells parallelly with current input and run the model for 10 sec it is taking 50 min of compliation time, 10 min of initilization time and 2 min of run time.
As the compilation time is too large, I converted the cell model to FMU and use the FMU inplace of open simscape mode and run the model for 10 sec and I observed that the compilation time is negligable, initilization time is around 10 min and the runtime is roughly about 70 min for 10sec of simulation time.
How to make this FMU model run with Realtime factor?
Please guide us with this.
Thanks in advanceHello Team,
I have a thermal model with conductive elements and have created a cylindrical cell model in Matlab 2021b, when I try to connect the cylindrical cells parallelly with current input and run the model for 10 sec it is taking 50 min of compliation time, 10 min of initilization time and 2 min of run time.
As the compilation time is too large, I converted the cell model to FMU and use the FMU inplace of open simscape mode and run the model for 10 sec and I observed that the compilation time is negligable, initilization time is around 10 min and the runtime is roughly about 70 min for 10sec of simulation time.
How to make this FMU model run with Realtime factor?
Please guide us with this.
Thanks in advance Hello Team,
I have a thermal model with conductive elements and have created a cylindrical cell model in Matlab 2021b, when I try to connect the cylindrical cells parallelly with current input and run the model for 10 sec it is taking 50 min of compliation time, 10 min of initilization time and 2 min of run time.
As the compilation time is too large, I converted the cell model to FMU and use the FMU inplace of open simscape mode and run the model for 10 sec and I observed that the compilation time is negligable, initilization time is around 10 min and the runtime is roughly about 70 min for 10sec of simulation time.
How to make this FMU model run with Realtime factor?
Please guide us with this.
Thanks in advance fmu, simscape, thermal, runtime, compilation, initilization MATLAB Answers — New Questions
How to read value from spreadsheet while using symbolic math tool?
How to read the values of A0 and A1 from the spreadsheet where A0 and A1 have more than one values? A1 has real and imaginary part which are in separate columns in the spreadsheet.
For example, the following code has fixed (single) value for A0 and A1, but what if multiple values are to be read:
Q = @(v) sym(v);
A0 = Q(‘1.5207’);
A1 = Q(‘0.853721-1.816893i’);
Note: Quote (”) has significant effect in this case, see below.How to read the values of A0 and A1 from the spreadsheet where A0 and A1 have more than one values? A1 has real and imaginary part which are in separate columns in the spreadsheet.
For example, the following code has fixed (single) value for A0 and A1, but what if multiple values are to be read:
Q = @(v) sym(v);
A0 = Q(‘1.5207’);
A1 = Q(‘0.853721-1.816893i’);
Note: Quote (”) has significant effect in this case, see below. How to read the values of A0 and A1 from the spreadsheet where A0 and A1 have more than one values? A1 has real and imaginary part which are in separate columns in the spreadsheet.
For example, the following code has fixed (single) value for A0 and A1, but what if multiple values are to be read:
Q = @(v) sym(v);
A0 = Q(‘1.5207’);
A1 = Q(‘0.853721-1.816893i’);
Note: Quote (”) has significant effect in this case, see below. import data from spreadsheet, symbolic math toolbox MATLAB Answers — New Questions