---
# System prepended metadata

title: Hugging Face Demo教學
tags: [GDG]

---

# Hugging Face Demo教學
[課程簡報](https://www.canva.com/design/DAGVb9sQi60/XzdsDswTkjgr7AJNnEBHxg/edit?utm_content=DAGVb9sQi60&utm_campaign=designshare&utm_medium=link2&utm_source=sharebutton)

## Demo
### 1. AI Playground 建立自己的影像辨識模型
* [AI Playground](https://ai.codinglab.tw/aiplayground)
>這裡可以利用匯出python檔獲取上課資料
### 2. 將模型透過colab上傳huggingface
1. 切換GPU
![截圖 2024-11-06 凌晨12.36.20](https://hackmd.io/_uploads/HkloFpDbye.png)

![截圖 2024-11-13 凌晨12.01.41](https://hackmd.io/_uploads/rJethlbzJl.png)

2. 上傳檔案
:::danger
這裡要記得新增資料夾，把名子改成aiplayground，然後再把裡面的tools.py上傳進去
:::
![截圖 2024-11-06 凌晨12.37.05](https://hackmd.io/_uploads/ByeaK6PW1x.png)
3. 在huggingface上獲取token
![截圖 2024-11-06 凌晨12.39.04](https://hackmd.io/_uploads/Skv4caD-1g.png)

![截圖 2024-11-13 凌晨12.20.55](https://hackmd.io/_uploads/SJ68Zb-Gkl.png)
>記得打勾這些

![截圖 2024-11-13 凌晨12.26.32](https://hackmd.io/_uploads/r1a0-b-fyx.png)

4. 執行下方程式碼
:::success
1. 執行main，測試模型
```python=
# -*- coding: utf-8 -*-

import numpy as np
from aiplayground.tool import Tool

classes_label = ['類別 1', '類別 2']

## 準備一張預測照片
predict_img = r'test1.png'

## 讀取照片
img = Tool().open_img(predict_img)
img = Tool().normalize(img)
imgs = np.expand_dims(img, 0)
## 讀取模型
model = Tool().load('model.h5')
## 預測答案
result_prob = model.predict(imgs).tolist()[0]
max_index = result_prob.index(max(result_prob))
print(classes_label[max_index], result_prob[max_index])
```
2. 下載huggingface套件
```bash
!pip install huggingface_hub
```
3. 利用acess token與huggingface連線
```python=
from huggingface_hub import login
login(token="your_acess_token")
```
4. 上傳檔案
>要記得設定repo_id沒有這個庫也行
```python=
from huggingface_hub import HfApi

api = HfApi()
model_path = "model.h5"
repo_id = "your_account/repo_name"  # 替換為您的用戶名和模型名稱

# 創建 repository 並上傳文件
api.create_repo(repo_id=repo_id, exist_ok=True)
api.upload_file(
    path_or_fileobj=model_path,
    path_in_repo="model.h5",#這裡舉例為模型檔案
    repo_id=repo_id,
    commit_message="Initial model upload"
)
```
>這裡是上傳其他檔案，舉例main.py
```python=
from huggingface_hub import HfApi

# 指定文件路徑和 repository ID
file_path = "/content/main.py"  # 替換為您想上傳的檔案的路徑

# 創建 HfApi 對象並上傳文件
api = HfApi()
api.upload_file(
    path_or_fileobj=file_path,
    path_in_repo="main.py",  # 在 repository 中的保存路徑和文件名
    repo_id=repo_id,
    commit_message="Add main.py file"
)

```
>如果是上傳整個資料夾的話可以這麼做
```python=
from huggingface_hub import upload_folder

# 替換為您專案資料夾的路徑，在這個專案底下操作的話名稱是content
folder_path = "/content"  

# 上傳資料夾到 Hugging Face Hub
upload_folder(folder_path=folder_path, repo_id=repo_id, commit_message="Upload entire project folder")
```
:::

5. 最後到自己的檔案就可以看到自己上傳的repo了
![截圖 2024-11-13 凌晨12.38.51](https://hackmd.io/_uploads/H1m3VWbM1x.png)

## 程式範例
* [ai_test實作demo](https://colab.research.google.com/drive/1JZQXqoSEb2IYojqEcYuVtbYbJXzhK7bz?usp=sharing)


