embeded/FPGA - ALTERA2026. 5. 8. 12:28

9년 전에 조사한 적이 있었네 -_-

2017.12.26 - [embeded/FPGA - ALTERA] - GHDL - 시뮬레이터

 

$ ghdl
Command 'ghdl' not found, but can be installed with:
sudo snap install ghdl         # version 3.0.0, or
sudo apt  install ghdl-common  # version 1.0.0+dfsg-6
See 'snap info ghdl' for additional versions.

$ sudo apt  install ghdl-common
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following NEW packages will be installed:
  ghdl-common
0 upgraded, 1 newly installed, 0 to remove and 54 not upgraded.
Need to get 154 kB of archives.
After this operation, 2,444 kB of additional disk space will be used.
Get:1 http://kr.archive.ubuntu.com/ubuntu jammy/universe amd64 ghdl-common amd64 1.0.0+dfsg-6 [154 kB]
Fetched 154 kB in 0s (4,318 kB/s)   
Selecting previously unselected package ghdl-common.
(Reading database ... 304538 files and directories currently installed.)
Preparing to unpack .../ghdl-common_1.0.0+dfsg-6_amd64.deb ...
Unpacking ghdl-common (1.0.0+dfsg-6) ...
Setting up ghdl-common (1.0.0+dfsg-6) ...
Processing triggers for man-db (2.10.2-1) ...

$ sudo apt-get install ghdl*
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Note, selecting 'ghdl-gcc' for glob 'ghdl*'
Note, selecting 'ghdl-mcode' for glob 'ghdl*'
Note, selecting 'ghdl-common' for glob 'ghdl*'
Note, selecting 'ghdl-llvm' for glob 'ghdl*'
Note, selecting 'ghdl' for glob 'ghdl*'
ghdl-common is already the newest version (1.0.0+dfsg-6).
The following additional packages will be installed:
  gcc-10-base libgnat-10
Suggested packages:
  gtkwave
The following NEW packages will be installed:
  gcc-10-base ghdl ghdl-gcc ghdl-llvm ghdl-mcode libgnat-10
0 upgraded, 6 newly installed, 0 to remove and 54 not upgraded.
Need to get 15.5 MB of archives.
After this operation, 60.5 MB of additional disk space will be used.
Do you want to continue? [Y/n] y 

 

[링크 : https://github.com/ghdl/setup-ghdl]

[링크 : https://askubuntu.com/questions/1199027/ghdl-in-ubuntu-18-040-lts-gtkwave-vlsi-fpga-vhdl]

[링크 : https://github.com/ghdl/ghdl/releases]

 

by gpt  

test.vhd
entity test is
end;

architecture sim of test is
begin
    process
    begin
        report "Hello GHDL";
        wait;
    end process;
end;

컴파일:

ghdl -a test.vhd

엘라보레이션:

ghdl -e test

실행:

ghdl -r test

출력:

Hello GHDL
5. GTKWave 함께 설치 (파형 보기)

보통 같이 설치합니다.

sudo apt install gtkwave

VCD 생성 실행 예시:

ghdl -r test --vcd=test.vcd
gtkwave test.vcd

 

먼가 되긴한데.. 문법이 다른가?

$ cat test.vhd 
entity test is
end;

architecture sim of test is
begin
    process
    begin
        report "Hello GHDL";
        wait;
    end process;
end;

$ ghdl -a 7seg.vhdl 


$ ghdl -r test
test.vhd:8:9:@0ms:(report note): Hello GHDL

$ ghdl -r test --vcd=test.vcd
test.vhd:8:9:@0ms:(report note): Hello GHDL

$ gtkwave test.vcd
Gtk-Message: 12:29:46.165: Failed to load module "canberra-gtk-module"

GTKWave Analyzer v3.3.104 (w)1999-2020 BSI

No symbols in VCD file..nothing to do!


$ sudo apt install libcanberra-gtk-module libcanberra-gtk3-module


$ gtkwave test.vcd

GTKWave Analyzer v3.3.104 (w)1999-2020 BSI

No symbols in VCD file..nothing to do!

$ cat test.vcd
$date
  Fri May  8 12:29:32 2026
$end
$version
  GHDL v0
$end
$timescale
  1 fs
$end
$scope module standard $end
$upscope $end
$scope module test $end
$upscope $end
$enddefinitions $end
#0


Posted by 구차니

llama-swap / llama.cpp 설정

이상하게도 gemma4-e2b의 경우 용량이 작아서 그런가 -sm none을 안주면 오히려 에러가 난다.

$ cat config.yaml 
models:
  gemma4-e2b:
    cmd: /mnt/Downloads/llama-b8925/llama-server --port ${PORT} --model /mnt/Downloads/model/gemma4-e2b/gemma-4-E2B-it-Q4_K_M.gguf -mm ./model/gemma4-e2b/mmproj-F16.gguf -sm none
  gemma4-e4b:
    cmd: /mnt/Downloads/llama-b8925/llama-server --port ${PORT} --model /mnt/Downloads/model/gemma4-e4b/gemma-4-E4B-it-Q4_K_M.gguf -mm ./model/gemma4-e4b/mmproj-F16.gguf
  gemma4-26B_img:
    cmd: /mnt/Downloads/llama-b8925/llama-server --port ${PORT} --model /mnt/Downloads/model/gemma4-26b/gemma-4-26B-A4B-it-UD-IQ2_M.gguf -mm ./model/gemma4-26b/mmproj-F16.gguf
  qwen3.6-35b_img:
    cmd: /mnt/Downloads/llama-b8925/llama-server --port ${PORT} --model /mnt/Downloads/model/qwen3.6_35B/Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf -mm ./model/qwen3.6_35B/mmproj-F16.gguf
  qwen3.6-35b:
    cmd: /mnt/Downloads/llama-b8925/llama-server --port ${PORT} --model /mnt/Downloads/model/qwen3.6_35B/Qwen3.6-35B-A3B-UD-Q2_K_XL.gguf

 

opencode 설정

이걸 추가한다고 바로 되는건 아닌 것 같고

~/.config/opencode$ cat opencode.json 
{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "llama.cpp": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "llama-server (local)",
      "options": {
        "baseURL": "http://127.0.0.1:8080/v1"
      },
      "models": {
        "gemma4-e2b": {
          "name": "gemma4 e2b (local)",
          "limit": {
            "context": 128000,
            "output": 65536
          }
        }
      }
    }
  }
}

[링크 : https://opencode.ai/docs/providers#llamacpp]

 

opencode 에서 /connect 명령을 통해 좀 더 해주어야 로컬에서 돌아간다.

 

 

 

 

심심하니 한번 로컬로 작성 시도!

 

오오 로컬 잡아먹는다 ㅋㅋㅋ

(요건 gpu0 에 e2b / gpu1에는 stable diffusion)

 

opencode.json 파일 추가!

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "llama.cpp": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "llama-server (local)",
      "options": {
        "baseURL": "http://127.0.0.1:8080/v1"
      },
      "models": {
        "gemma4-e2b": {
          "name": "gemma4 e2b (local)",
          "limit": {
            "context": 128000,
            "output": 65536
          }
        },
        "qwen3.6-35b": {
          "name": "qwen3.6-35b (local)",
          "limit": {
            "context": 65536,
            "output": 65536
          }
        }
      }
    }
  }
}

 

gemma4-e2b 에서 qwen3.6-35b로 환승!

 

인사 받기 참 힘드네 ㅋㅋㅋ

 

그래도 100% 꾹꾹 하는데 소비전력은 150 W 급 * 2 이라..

Posted by 구차니

엥.. 왜 갑자기 안되지 싶은데

-sm none 으로 해결

Posted by 구차니

0 번 부터 시작임

Launching Web UI with arguments: --server-name=0.0.0.0 --device-id=1

[링크 : https://github.com/AUTOMATIC1111/stable-diffusion-webui/discussions/10665]

Posted by 구차니

다시 해보니 telegram은 ogg로 보내는데 이걸 넣으면 wav가 아니라서 배째는거라

ffmpeg을 통해서 ogg를 wav로 바꾸고 하니 먼가 처리를 한다.

다만 소리 크기가 작아서 인가 은근히 인식율이 떨이지네.. (gemma4:e2b)

 

----

ollama 통해서 하고 있는데 미구현인가..

아니면  gemma4:e2b가 ollama에서 할 때 오디오는 미지원인건가... 이건 어떻게 확인하지?

그 와중에 왜 이미지로 인식하냐?

--- [Prompt to AI] (Model: gemma4:e2b) ---
[{'role': 'user', 'content': [{'type': 'text', 'text': '이 내용을 분석해줘'}, {'type': 'input_audio', 'input_audio': {'data': 'encoded data', 'format': 'wav'}}]}]


 {'error': {'message': 'Failed to create new sequence: failed to process inputs: imageunknown format', 'type': 'api_error', 'param': None, 'code': None}}
 

 

$ ollama show gemma4:e2b
  Model
    architecture        gemma4    
    parameters          5.1B      
    context length      131072    
    embedding length    1536      
    quantization        Q4_K_M    
    requires            0.20.0    

  Capabilities
    completion    
    vision        
    audio         
    tools         
    thinking      

  Parameters
    temperature    1       
    top_k          64      
    top_p          0.95    

  License
    Apache License               
    Version 2.0, January 2004    
    ...                          

 

import OpenAI from "openai";
const openai = new OpenAI();

// Fetch an audio file and convert it to a base64 string
const url = "https://cdn.openai.com/API/docs/audio/alloy.wav";
const audioResponse = await fetch(url);
const buffer = await audioResponse.arrayBuffer();
const base64str = Buffer.from(buffer).toString("base64");

const response = await openai.chat.completions.create({
  model: "gpt-audio",
  modalities: ["text", "audio"],
  audio: { voice: "alloy", format: "wav" },
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: "What is in this recording?" },
        { type: "input_audio", input_audio: { data: base64str, format: "wav" }}
      ]
    }
  ],
  store: true,
});

console.log(response.choices[0]);

[링크 : https://developers.openai.com/api/docs/guides/audio?example=audio-in]

 

 

[링크 : https://community.openai.com/t/how-can-i-pass-a-system-prompt-and-audio-user-input-to-get-a-text-output-back/1002483/3]

[링크 : https://github.com/ggml-org/llama.cpp/issues/21868]

Posted by 구차니

어떻게 쓰지 싶었는데, 2025년 5월 15일 내용에 이미 아래의 모델들이 지원되고 있었다

[링크 : https://ollama.com/blog/multimodal-models]

[링크 :https://ollama.com/search?c=vision]

 

아래 파일 경로가

/home/minimonk/1804-lubuntu-default-wallpaper.png 인데

절대경로 넣어주면 알아서 읽어서 본다.

헐..(!)

 

$ ollama run gemma4:e2b
>>> what do you see in this image?  /home/minimonk/1804-lubuntu-default-wall
... paper.png
Added image '/home/minimonk/1804-lubuntu-default-wallpaper.png'
Thinking...
Here's a thinking process to analyze the image and generate the 
description:

1.  **Analyze the Request:** The user provided an image and asked, "what 
do you see in this image?"

2.  **Examine the Image (Visual Analysis):**
    *   **Overall Impression/Mood:** The image is dark, deep, atmospheric, 
and somewhat cosmic or abstract.
    *   **Colors:** The dominant colors are deep blues (teal/cyan), 
vibrant purples (magenta/violet), and some lighter, soft areas.
    *   **Texture/Pattern:** The background is not uniformly smooth. It 
features nebulous areas and scattered dots.
    *   **Specific Elements:**
        *   **Background:** Deep blue/purple gradient.
        *   **Texture/Effects:** There are faint, wispy clouds or nebulas, 
especially in the upper right area, suggesting a cosmic or smoky effect.
        *   **Particles:** Numerous small, scattered white or 
light-colored dots (specks of light/stars/dust) are distributed across the 
frame.
        *   **Light/Glow:** There is a soft, glowing, lighter purple/pink 
area, particularly visible towards the right.

3.  **Synthesize the Description (Drafting the Response):** Combine the 
observations into a coherent description. Start with the general theme and 
then detail the specific elements.

    *   *(Initial thought: It's a space background.)*
    *   *(Refinement: It's an abstract digital art piece, often called a 
cosmic or nebula background.)*

4.  **Review and Refine (Adding evocative language):** Ensure the 
description is accurate and engaging. (Self-Correction: Avoid making 
definitive claims like "it is space," but use terms that imply it, like 
"nebula" or "cosmic.")

5.  **Final Output Generation.** (This leads to the provided good 
response.)
...done thinking.

This image is an **abstract, atmospheric background**, often resembling a 
**cosmic or nebula scene**.

Here is a detailed breakdown of what I see:

1.  **Color Palette:** The dominant colors are deep and rich, featuring a 
strong gradient blend of **deep blues** and **vibrant purples/magentas**.
2.  **Texture/Atmosphere:** The background has a soft, smoky, or nebulous 
quality, suggesting deep space or an ethereal cloud formation. There are 
lighter, diffused areas, particularly on the right side, which glow with 
pink and purple hues.
3.  **Particles:** The image is scattered with numerous small, bright 
**white dots**, which give the impression of stars, dust, or glittering 
particles floating in the dark space.
4.  **Overall Mood:** The image evokes a feeling of depth, mystery, 
serenity, and vastness. It is highly typical of digital art used as 
wallpapers or abstract graphics.

 

llama.cpp로 개고생 하던게 이렇게 쉽게 되다니 ㅠㅠ

'프로그램 사용 > ai 프로그램' 카테고리의 다른 글

stable diffusion gpu 선택하기  (0) 2026.05.08
openai api .. 오디오 처리 성공  (0) 2026.05.07
RAG, 시도 (openAI 사용하지 않는 방향)  (0) 2026.05.07
opencode + llama.cpp  (0) 2026.05.06
llm tts?  (0) 2026.05.05
Posted by 구차니
Programming/qt2026. 5. 7. 15:13

내가 원하던  mainwindow의 내용을 다른 위젯으로 변경하기

[링크 : https://doc.qt.io/qt-6/qmainwindow.html#setCentralWidget]

[링크 : https://wikidocs.net/156100]

 

새 다이얼로그 창을 열고 숨기기

[링크 : https://toytvstory.tistory.com/1422]


replacewidget()

주로 한개의 위젯을 바꾸지, 창을 바꾸는 용도는 아닌듯?

[링크 : https://stackoverflow.com/questions/35382622/replace-a-widget-in-qt]

[링크 : https://doc.qt.io/qt-6/qlayout.html#replaceWidget]

 

 

Posted by 구차니

검색 증강 생성(Retrieval Augmented Generation)

[링크 : https://aws.amazon.com/ko/what-is/retrieval-augmented-generation/]

[링크 : https://blog.kakaocloud.com/98]

 

랭체인이 시작이군.

import os
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain.vectorstores import Chroma
from langchain.embeddings import OpenAIEmbeddings
from langchain.chains import RetrievalQA
from langchain.document_loaders import PyPDFLoader
import urllib.request
import gradio as gr

[링크 : https://wikidocs.net/288616]

 

+

2026.05.13 실패중

pip install langchain_openai langchain_community pypdf chromadb
pip install langchain gradio

 

몇개는 지금 시점에서 langchain_classic 으로 해야지 호출된다. 곧(?) deprecated 되겠네 -_-

import os
from langchain_openai import ChatOpenAI
from langchain_classic.chains import RetrievalQA
from langchain_classic.document_loaders import PyPDFLoader
from langchain_classic.embeddings import OpenAIEmbeddings
from langchain_classic.prompts import PromptTemplate
from langchain_classic.vectorstores import Chroma
import urllib.request
import gradio as gr

os.environ['OPENAI_API_KEY'] ="dummy"

urllib.request.urlretrieve("https://debix-oss.oss-cn-hongkong.aliyuncs.com/debix/IMX8MPRM%20Rev.%201.06.pdf", filename="IMX8MPRM.pdf")
loader = PyPDFLoader("IMX8MPRM.pdf")
texts = loader.load_and_split()
print('문서의 수 :', len(texts))

[링크 : https://www.reddit.com/r/LangChain/comments/1q88edw/facing_langchain_module_import_issue_no_module/?tl=ko]

[링크 : https://wikidocs.net/232860]

 

문서의 수는 페이지랑 비슷하게 나온다.

>>> print(texts[0])
page_content='i.MX 8M Plus Applications Processor
Reference Manual
Document Number: IMX8MPRM
Rev. 1, 06/2021' metadata={'producer': 'Antenna House PDF Output Library 6.1.425 (Linux64); modified using iText® 5.1.3 ©2000-2011 1T3XT BVBA', 'creator': 'AH XSL Formatter V6.1 MR2 for Linux64 : 6.1.6.12685 (2013/09/18 10:39JST)', 'creationdate': '2021-06-10T11:46:47-07:00', 'author': 'NXP Semiconductors', 'fslditapluginversion': '20160510', 'fslssdsversion': '4.7.1', 'keywords': 'Applications processors\r\nMachine learning\r\nArtificial Intelligence\r\nIOT Solutions\r\nVoice control\r\nVoice assistant\r\ni.MX\r\nVision Solutions\r\nMulti Display\r\nIntegrated ISP\r\nNPU\r\nArm core\r\nPower Efficient processor', 'moddate': '2021-06-11T13:46:30-05:00', 'subject': 'i.MX 8M Plus Applications Processor Reference Manual', 'title': 'i.MX 8M Plus Applications Processor Reference Manual', 'trapped': '/False', 'source': 'IMX8MPRM.pdf', 'total_pages': 7406, 'page': 0, 'page_label': '1'}

 

요렇게 생긴 페이지가

 

아래와 같이 저장된다. 그냥.. 모든 텍스트는 다 저장되는 느낌?

>>> print(texts[2])
page_content='Contents
Section number Title Page
Chapter 1
Introduction
1.1 Product Overview ........................................................................................................................................................ 9
1.2 Target Applications.......................................................................................................................................................9
1.3 Acronyms and Abbreviations....................................................................................................................................... 9
1.4 Architectural Overview.................................................................................................................................................12
Chapter 2
Memory Map
2.1 Memory system overview.............................................................................................................................................23
2.2 Cortex-A53 Memory Map ........................................................................................................................................... 24
2.3 Cortex-M7 Memory Map..............................................................................................................................................26
2.4 DMA memory maps..................................................................................................................................................... 29
2.5 AIPS Memory Maps..................................................................................................................................................... 30
2.6 DAP Memory Map....................................................................................................................................................... 36
2.7 Audio Processor Memory Map.....................................................................................................................................38
2.8 HDMI_TX Subsystem Memory Map........................................................................................................................... 38
Chapter 3
Security
3.1 System Security............................................................................................................................................................ 41
3.2 Resource Domain Controller (RDC)............................................................................................................................ 44
Chapter 4
Arm Platform and Debug
4.1 Arm Cortex A53 Platform (A53)..................................................................................................................................91
4.2 Arm Cortex M7 Platform (CM7)..................................................................................................................................97
4.3 Messaging Unit (MU)...................................................................................................................................................99
4.4 Semaphore (SEMA4)....................................................................................................................................................143
4.5 On-Chip RAM Memory Controller (OCRAM)............................................................................................................161
4.6 Network Interconnect Bus System (NIC).....................................................................................................................164
i.MX 8M Plus Applications Processor Reference Manual, Rev. 1, 06/2021
NXP Semiconductors 3' metadata={'producer': 'Antenna House PDF Output Library 6.1.425 (Linux64); modified using iText® 5.1.3 ©2000-2011 1T3XT BVBA', 'creator': 'AH XSL Formatter V6.1 MR2 for Linux64 : 6.1.6.12685 (2013/09/18 10:39JST)', 'creationdate': '2021-06-10T11:46:47-07:00', 'author': 'NXP Semiconductors', 'fslditapluginversion': '20160510', 'fslssdsversion': '4.7.1', 'keywords': 'Applications processors\r\nMachine learning\r\nArtificial Intelligence\r\nIOT Solutions\r\nVoice control\r\nVoice assistant\r\ni.MX\r\nVision Solutions\r\nMulti Display\r\nIntegrated ISP\r\nNPU\r\nArm core\r\nPower Efficient processor', 'moddate': '2021-06-11T13:46:30-05:00', 'subject': 'i.MX 8M Plus Applications Processor Reference Manual', 'title': 'i.MX 8M Plus Applications Processor Reference Manual', 'trapped': '/False', 'source': 'IMX8MPRM.pdf', 'total_pages': 7406, 'page': 2, 'page_label': '3'}

 

크흑.. 벌써 나오는 deprecated의 향연

>>> embedding = OpenAIEmbeddings(chunk_size=100)
<stdin>:1: LangChainDeprecationWarning: The class `OpenAIEmbeddings` was deprecated in LangChain 0.0.9 and will be removed in 1.0. An updated version of the class exists in the `langchain-openai package and should be used instead. To use it run `pip install -U `langchain-openai` and import as `from `langchain_openai import OpenAIEmbeddings``.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/falinux/.local/lib/python3.10/site-packages/langchain_core/_api/deprecation.py", line 258, in warn_if_direct_instance
    return wrapped(self, *args, **kwargs)
  File "/home/falinux/.local/lib/python3.10/site-packages/pydantic/main.py", line 263, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for OpenAIEmbeddings
  Value error, Did not find openai_api_key, please add an environment variable `OPENAI_API_KEY` which contains it, or pass `openai_api_key` as a named parameter. [type=value_error, input_value={'chunk_size': 100, 'mode...20, 'http_client': None}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.13/v/value_error

 

OPENAI_API_KEY 가 등록안했을 경우 발생하는 에러

>>> OpenAIEmbeddings()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/falinux/.local/lib/python3.10/site-packages/pydantic/main.py", line 263, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
  File "/home/falinux/.local/lib/python3.10/site-packages/langchain_openai/embeddings/base.py", line 448, in validate_environment
    self.async_client = openai.AsyncOpenAI(
  File "/home/falinux/.local/lib/python3.10/site-packages/openai/_client.py", line 587, in __init__
    raise OpenAIError(
openai.OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

 

머든 langchain_classic 이면 해결

embedding = OpenAIEmbeddings(chunk_size=100)

 

일단 여기서.. openAI api키를 진짜로 발급받지 않으면 안넘어 간다. 젠장

vectordb = Chroma.from_documents(
    documents=texts,
    embedding=embedding)

 

evaluation 하려면 결제해야하나? 와.. 짜증나네 ㅠㅠ

openai.RateLimitError: Error code: 429 - {'error': {'message': 'You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.', 'type': 'insufficient_quota', 'param': None, 'code': 'insufficient_quota'}}

 

 

+ 다시!

망할 그래픽이 구형이라 안되는건 어쩔수 없는데..

BAAI/bge-m3는 6132MB나 VRAM을 드시네. ㄷㄷ

 

2026.05.14

import os
from langchain_openai import ChatOpenAI
from langchain_classic.chains import RetrievalQA
from langchain_classic.document_loaders import PyPDFLoader
from langchain_classic.prompts import PromptTemplate
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma

import urllib.request
import gradio as gr

urllib.request.urlretrieve("https://github.com/chatgpt-kr/openai-api-tutorial/raw/main/ch07/2020_%EA%B2%BD%EC%A0%9C%EA%B8%88%EC%9C%B5%EC%9A%A9%EC%96%B4%20700%EC%84%A0_%EA%B2%8C%EC%8B%9C.pdf", filename="2020_경제금융용어 700선_게시.pdf")

loader = PyPDFLoader("2020_경제금융용어 700선_게시.pdf")
texts = loader.load_and_split()
print('문서의 수 :', len(texts))

embedding = HuggingFaceEmbeddings(
    model_name="BAAI/bge-m3",
    model_kwargs={"device": "cpu"}
)

vectordb = Chroma.from_documents(
    documents=texts,
    embedding=embedding
)

print(vectordb._collection.count())
366
for key in vectordb._collection.get():
...   print(key)
...
ids
embeddings
documents
uris
included
data
metadatas

documents = vectordb._collection.get()['documents']
print('청크의 개수 :', len(documents))
청크의 개수 : 366
print('-' * 50)
--------------------------------------------------
print('0번 청크 출력 :', documents[0])
0번 청크 출력 : iii
찾아보기
한국은행은 국민들이 경제 및 금융에 대한 이해도를 높이고 경제에 관한 합리적인
의사결정 능력을 키울 수 있도록 현장 경제교육, 온라인 경제교육, 경제교육 콘텐츠
개발 등 대국민 경제교육을 다양하게 수행해 오고 있습니다 .
이의 일환으로 2018년
 경제금융용어 700선
 을 발간하였는데 그간 동 책자에 대한
수요가 꾸준히 늘어남에 따라 이번에 추가로 발간하게 되었습니다 .
지난번 내용과 같이 통화정책, 실물경제, 금융안정, 지급결제 등 한국은행 주요
업무를 이해하는데 필요한 전문 용어와 경제·금융 흐름을 이해하는데 도움이 되는
시사 경제금융 용어들을 수록하였습니다. 용어해설은 개념과 도입 배경, 의미, 적용
사례 등을 담아 쉽게 이해할 수 있도록 하였습니다. 또한 e-book으로도 제작하여
독자들의 편의성과 가독성을 높였습니다 .
코로나 19로 이전에 경험하지 못한 경제위기를 겪으면서 경제·금융 현상에 대한
일반인들의 관심도가 이전에 비해 높아졌습니다. 아무쪼록 이 책자가 한국은행의 주요
정책과 국내외 경제를 이해하는 데 조금이나마 도움이 되기를 바라겠습니다. 끝으로
경제금융용어 700선
  집필에 참여해주신 경제교육실 교수님들과 용어 집필에 좋은
의견을 주신 관련부서 여러분께 감사드립니다 .
2020년 8월
한국은행 경제교육실장 박 철 원
머 리 말

embeddings = vectordb._collection.get(include=['embeddings'])['embeddings']
print('임베딩 벡터의 개수 :', len(embeddings))
임베딩 벡터의 개수 : 366
print('0번 청크의 임베딩 값 출력 :', embeddings[0])
0번 청크의 임베딩 값 출력 : [ 0.00253409 -0.00188405 -0.05017297 ...  0.03743017 -0.00941579
 -0.04372674]
print('0번 청크의 임베딩 값의 길이 :', len(embeddings[0]))
0번 청크의 임베딩 값의 길이 : 1024
metadatas = vectordb._collection.get()['metadatas']
print('metadatas의 개수 :', len(metadatas))
metadatas의 개수 : 366
print('0번 청크의 출처 :', metadatas[0])
0번 청크의 출처 : {'creationdate': 'January 31, 2018 16:21', 'page': 3, 'moddate': 'January 31, 2018 16:21', 'producer': 'Smart PDF Imposition 1.0', 'page_label': '4', 'total_pages': 371, 'creator': 'Smart PDF Imposition 1.0', 'creationdate--text': 'January 31, 2018 16:21', 'title': '°æÁ¦±ÝÀ¶¿ë¾î 700¼±-ÃÖÁ¾.PDF', 'source': '2020_경제금융용어 700선_게시.pdf', 'author': 'INSUNG DATA INC.', 'subject': 'CoreImposition PDF 1.0 Output', 'moddate--text': 'January 31, 2018 16:21'}

docs = retriever.invoke("비트코인이 궁금해")
print('유사 문서 개수 :', len(docs))
유사 문서 개수 : 2
print('--' * 20)
----------------------------------------
print('첫번째 유사 문서 :', docs[0])
첫번째 유사 문서 : page_content='139

비트코인
비트코인(bitcoin)은 가상통화(암호통화)이자 디지털 지급시스템이다. 비트코인 시스템
은 중앙 저장소 또는 단일 관리자가 없기 때문에 최초의 탈중앙화된 디지털통화라고 불린다.
이는 사토시 나카모토라는 사람(집단)에 의해 만들어져서 2009년 개방형 소프트웨어로
배포되었다. 이 시스템은 공유형(peer-to-peer)이며, 거래는 중개자 없이 블록체인 소프트
웨어를 이용하는 참여자(nodes) 사이에 직접 이뤄진다. 이런 거래들은 공유(P2P) 네트워크
상 참여자의 작업증명(proof-of-work)을 통해 검증되고 공개된 분산원장인 블록체인에
기록된다. 승인된 거래의 새 그룹인 한 블록은 대략 10분에 한 번씩 만들어져서 블록체인에
추가되고 신속하게 모든 참여자에게 보내어진다. 비트코인은 대규모 전기를 사용하는
컴퓨터 처리 능력(power)을 활용해서 이뤄지는 기록보관 서비스인 채굴(mining)에 대한
보상으로 발행되고 있으며 다른 통화・상품・용역 등과 교환되어가고 있다. 중앙은행이
발행한 법정화폐가 아닌 비트코인은 비트코인 플랫폼에서 거래되며 투자대상으로서도
관심을 받고 있다. 하지만 급등한 가격 및 심한 변동 폭으로 거품논란이 크다. 또한 익명성으
로 자금세탁 등 불법거래에 악용될 소지가 많아 중국 등 일부 국가에서 비트코인 등 가상통
화의 거래를 규제하고 있다. 일본의 경우 비트코인의 거래이익에 대해 세금을 부과한다.
비트코인은 추가되는 한 블록당 새로 12.5비트코인을 보상하는데(2016.7월 현재), 21만개
가 채굴될 때(대략 4년)마다 그 보상이 반으로 줄어든다. 비트코인의 총량은 21백만개이며
2140년경 모두 채굴될 것으로 전망된다. 비트코인은 그 시스템의 설계시 그 수량을 한정시
켜 놓았기 때문에 원칙적으로 인플레이션에 의해 가치가 떨어질 수 있는 화폐와 다른
속성을 지닌다. 한편 2017년 8월 1일 비트코인(classic bitcoin)에서 ‘비트코인캐시’(BCH)가,
10월 25일 ‘비트코인골드’(BTG)가 하드포크(hard-fork)되어 별도로 거래되고 있다.
 연관검색어 : 가상통화, 작업증명, 블록체인
빅데이터
빅데이터(big data)란 복잡하고 다양한 대규모 데이터세트 자체는 물론 이 데이터세트
로부터 정보를 추출하고 결과를 분석하여 더 큰 가치를 창출하는 기술을 뜻한다. 수치
데이터 등 기존의 정형화된 정보뿐 아니라 텍스트 ・이미지・오디오・로그기록 등 여러
형태의 비정형 정보가 데이터로 활용된다. 최근 모바일기기와 SNS 이용 보편화, 사물인
빅데이터 ∙' metadata={'title': '°æÁ¦±ÝÀ¶¿ë¾î 700¼±-ÃÖÁ¾.PDF', 'creationdate--text': 'January 31, 2018 16:21', 'producer': 'Smart PDF Imposition 1.0', 'page_label': '156', 'moddate--text': 'January 31, 2018 16:21', 'moddate': 'January 31, 2018 16:21', 'source': '2020_경제금융용어 700선_게시.pdf', 'page': 155, 'creator': 'Smart PDF Imposition 1.0', 'creationdate': 'January 31, 2018 16:21', 'subject': 'CoreImposition PDF 1.0 Output', 'total_pages': 371, 'author': 'INSUNG DATA INC.'}
print('두번째 유사 문서 :', docs[1])
두번째 유사 문서 : page_content='6
경제금융용어 700선
가상통화공개(ICO)
가상통화(ICO; Initial Coin Offering) 공개는 주로 혁신적인 신생기업(startup)이 암호
화화폐(cryptocurrency) 또는 디지털 토큰(digital token, 일종의 투자증명)을 이용하여
자금을 조달할 수 있는 크라우드펀딩(crowd funding)의 한 방식이다. 가상통화공개
(ICO)에서 새로 발행된 암호화화폐는 법화(legal tender) 또는 비트코인 등 기존의 가상
통화와 교환되어 투자자에게 팔린다. 이 용어는 거래소에 상장하려는 기업이 투자자에게
자기 주식을 처음 공개적으로 매도하는 기업공개(IPO; Initial Public Offering)에서 연유
되었다고 볼 수 있다. 기업공개(IPO)에 참여한 투자자는 해당 기업의 소유권과 관련하여
주식을 획득한다. 반면 가상통화공개(ICO)에 참여한 투자자는 해당 신생기업의 코인
(coins) 또는 토큰을 얻는데, 이는 해당 기업이 제안한 프로젝트가 나중에 성공했을
경우 평가될 수 있는 가치(value)로 볼 수 있다. ICO는 주로 블록체인플랫폼인 이더리움
(Etherium)에서 이뤄지고 있다. 우리나라의 경우 현재 금지하고 있으며 앞으로 ICO에
대한 논의를 거쳐 유사수신행위 또는 증권관련 법률로 규제할 것으로 보인다 .
 연관검색어 : 가상통화, 블록체인, 비트코인, 빅데이터, 크라우드펀딩, 핀테크
간접금융/직접금융
경제에는 자금 잉여주체와 자금 부족주체가 존재하게 되는데 이들 사이에 은행이나
저축은행 신용협동기구 등 금융기관이 개입하여 자금을 중개하는 방식을 간접금융
(indirect financing)이라고 한다. 즉 금융기관이 일반 대중으로부터 예금을 받아 이를
자신의 명의로 기업 등 다른 경제주체에게 대출해 주는 방식이다. 한편 주식, 채권
발행의 경우와 같이 자금수요자가 금융기관을 통하지 않고 금융시장에서 직접 필요자금
을 조달하는 방식을 직접금융(direct financing)이라고 한다. 간접금융에서는 은행이
중추적인 기능을 하고, 직접금융에서는 주식과 채권이 거래되는 자본시장이 중요한
역할을 수행한다. 직접금융과 간접금융은 상호 경쟁적일 뿐만 아니라 보완적이기도
하므로 두 금융방식이 균형적으로 발전될 필요가 있다. 직접금융과 간접금융의 상대적
비중이 어느 정도이어야 이상적인지는 해당 국가의 경제발전단계나 경제구조에 따라
달라질 수밖에 없다. 예를 들면 중소기업의 비중이 높은 국가일수록 정보의 비대칭성
문제를 완화하기 위해 간접금융이 더 중요하고, 혁신산업에 의해 주도되는 경제일수록' metadata={'producer': 'Smart PDF Imposition 1.0', 'moddate': 'January 31, 2018 16:21', 'subject': 'CoreImposition PDF 1.0 Output', 'creationdate--text': 'January 31, 2018 16:21', 'creationdate': 'January 31, 2018 16:21', 'page': 22, 'creator': 'Smart PDF Imposition 1.0', 'source': '2020_경제금융용어 700선_게시.pdf', 'total_pages': 371, 'title': '°æÁ¦±ÝÀ¶¿ë¾î 700¼±-ÃÖÁ¾.PDF', 'page_label': '23', 'author': 'INSUNG DATA INC.', 'moddate--text': 'January 31, 2018 16:21'}


 

BAAI/bge-small-en-v1.5
intfloat/multilingual-e5-base

'프로그램 사용 > ai 프로그램' 카테고리의 다른 글

openai api .. 오디오 처리 성공  (0) 2026.05.07
ollama multimodal gemma4:e2b 테스트  (0) 2026.05.07
opencode + llama.cpp  (0) 2026.05.06
llm tts?  (0) 2026.05.05
stablie diffusion 모델 변경 / 다운로드 하기  (0) 2026.05.05
Posted by 구차니
Linux/Ubuntu2026. 5. 6. 22:29

예전에 우분투에서 이상하게 반응이 느렸던 문제로 찾았던건데

llm 에서 한글 발음을 영어로 적게 해서 이걸 festival 통해 wav로 생성하고

메신저로 넘기게 하면 어떨려나?

 

echo "linuxquestions.org" > mytext.txt
text2wave -o mytext.wav myaudio.txt

[링크 : https://wiki.linuxquestions.org/wiki/Text2wave]

[링크 : https://wiki.archlinux.org/title/Festival]

[링크 : https://manpages.ubuntu.com/manpages/resolute/man1/festival.1.html]

[링크 : https://manpages.ubuntu.com/manpages/trusty/man1/text2wave.1.html]

 

+

2026.05.07

ai 가라사대~

설치된 음성은 festival 실행해서 괄호넣어서 하면 나오는데

$ festival

Festival Speech Synthesis System 2.5.0:release December 2017
Copyright (C) University of Edinburgh, 1996-2010. All rights reserved.

clunits: Copyright (C) University of Edinburgh and CMU 1997-2010
clustergen_engine: Copyright (C) Carnegie Mellon University 2005-2017
hts_engine: 
The HMM-Based Speech Synthesis Engine "hts_engine API"
hts_engine API version 1.07 (http://hts-engine.sourceforge.net/)
Copyright (C) The HMM-Based Speech Synthesis Engine "hts_engine API"
Version 1.07 (http://hts-engine.sourceforge.net/)
Copyright (C) 2001-2012 Nagoya Institute of Technology
              2001-2008 Tokyo Institute of Technology
All rights reserved.

All rights reserved.
For details type `(festival_warranty)'
festival> voice.list
#<CLOSURE nil (begin "(voice.list)
List of all (potential) voices in the system.  This checks the voice-location
list of potential voices found be scanning the voice-path at start up time.
These names can be used as arguments to voice.description and
voice.describe." (mapcar car voice-locations))>
festival> (voice.list) 
(kal_diphone)

 

festvox로 추가 음성을 설치할 수 있다고 한다.

$ apt-cache search festvox*
flite - Small run-time speech synthesis engine
flite1-dev - Small run-time speech synthesis engine - development files
freetts - 음성 합성 시스템
libflite1 - 작은 런타임 음성 합성 엔진 - 공유 라이브러리
festvox-ca-ona-hts - Catalan female speaker for festival, 16kHz HTS
festvox-czech-dita - Czech adult female speaker "dita" for Festival
festvox-czech-krb - Czech child male speaker "krb" for Festival
festvox-czech-machac - Czech adult male speaker "machac" for Festival
festvox-czech-ph - Czech male speaker for Festival
festvox-hi-nsk - Hindi male speaker for festival
festvox-italp16k - Italian female speaker for Festival
festvox-itapc16k - Italian male speaker for Festival
festvox-kallpc16k - American English male speaker for festival, 16khz sample rate
festvox-kallpc8k - American English male speaker for festival, 8khz sample rate
festvox-kdlpc16k - American English male speaker for festival, 16khz sample rate
festvox-kdlpc8k - American English male speaker for festival, 8khz sample rate
festvox-mr-nsk - Marathi male speaker for festival
festvox-ru - Russian male speaker for Festival
festvox-suopuhe-common - Common files for Festival Finnish speakers
festvox-suopuhe-lj - Finnish female speaker for Festival
festvox-suopuhe-mv - Finnish male speaker for festival
festvox-te-nsk - Telugu (te) male speaker for festival
festvox-us-slt-hts - : US English voice for Festival. 32kHz sample rate, HTS
festvox-don - minimal British English male speaker for festival
festvox-ellpc11k - Castilian Spanish male speaker for Festival
festvox-en1 - mbrola-en1 voice support for festival
festvox-rablpc16k - British English male speaker for festival, 16khz sample rate
festvox-rablpc8k - British English male speaker for festival, 8khz sample rate
festvox-us1 - mbrola-us1 voice support for festival
festvox-us2 - mbrola-us2 voice support for festival
festvox-us3 - mbrola-us3 voice support for festival

 

echo "Hello" | festival --tts --voice voice_kal_diphone

(Parameter.set 'Duration_Stretch 1.3) ; 느리게
(set! duffint_params '((start 120) (end 140))) ; 피치 변경

 

For example
will make everything speak more slowly.

[링크 : https://www.cstr.ed.ac.uk/projects/festival/manual/festival_19.html#SEC72]

  [링크 : https://www.cstr.ed.ac.uk/projects/festival/manual/]

 

festival> help
"The Festival Speech Synthesizer System: Help

Getting Help
  (doc '<SYMBOL>)   displays help on <SYMBOL>
  (manual nil)      displays manual in local netscape
  C-c               return to top level
  C-d or (quit)     Exit Festival
(If compiled with editline)
  M-h               displays help on current symbol  
  M-s               speaks help on current symbol  
  M-m               displays relevant manual page in local netscape
  TAB               Command, symbol and filename completion
  C-p or up-arrow   Previous command
  C-b or left-arrow Move back one character
  C-f or right-arrow 
                    Move forward one character
  Normal Emacs commands work for editing command line

Doing stuff
  (SayText TEXT)      Synthesize text, text should be surrounded by
                      double quotes
  (tts FILENAME nil)  Say contexts of file, FILENAME should be 
                      surrounded by double quotes
  (voice_rab_diphone) Select voice (Britsh Male)
  (voice_kal_diphone) Select voice (American Male)
"

 

 

'Linux > Ubuntu' 카테고리의 다른 글

luit  (0) 2026.03.23
ubuntu 22.04 bgr 패널 대응  (0) 2025.12.29
clamav  (0) 2025.12.22
evince (리눅스 pdf 뷰어) 네비게이션  (0) 2025.12.11
ubuntu 22.04 bgr subpixel 대응 찾기 실패  (0) 2025.11.25
Posted by 구차니

N - Number of image size in batch size

H - Height of image

W - Width of image

C- number of Channel of the image

 

NCHW는 Channel First (red channel image + blue ...)

NHWC는 Channel Last (rgb pixel image)

 

[링크 : https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/features/nhwc.html]

 

어떻게 보면 레이어 별로 처리하게 하는게 유리할수도 있을 것 같기도 한데 서로 tradeoff가 존재할 것 같다.

 

NCHW - (64,3,512,512)

NHWC - (64,512,512,3)

[링크 : https://medium.com/@gonchogo/nhwc-vs-nchw-1504d2621b5e]

 

GPU - NCHW

CPU - NHWC

tensorRT는 NHWC에서 최고의 효율

[링크 : https://seungwoo-dev.tistory.com/6]

Posted by 구차니