yongyeol commited on
Commit
855f2cd
·
verified ·
1 Parent(s): 2b108d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -38
app.py CHANGED
@@ -2,58 +2,50 @@ import os, io, base64, tempfile, requests
2
  import gradio as gr
3
  from PIL import Image
4
 
5
- # ─────────────────────────────────────────────────────────────
6
- # 1. 환경 변수 & HF Inference API 설정
7
- # ─────────────────────────────────────────────────────────────
8
- HF_TOKEN = os.getenv("HF_TOKEN")
9
  if not HF_TOKEN:
10
- raise RuntimeError("HF_TOKEN 비밀 값이 설정되어 있지 않습니다. Spaces Settings → Secrets에서 등록해 주세요.")
11
 
12
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
13
  CAPTION_API = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-base"
14
  MUSIC_API = "https://api-inference.huggingface.co/models/facebook/musicgen-small"
15
 
16
- # ─────────────────────────────────────────────────────────────
17
- # 2. 이미지 캡션 생성 (BLIP-base via API)
18
- # ─────────────────────────────────────────────────────────────
19
  def generate_caption(image_pil: Image.Image) -> str:
20
  buf = io.BytesIO()
21
  image_pil.save(buf, format="PNG")
22
- buf.seek(0)
 
 
23
 
24
- # binary upload 방식
25
- response = requests.post(CAPTION_API, headers=HEADERS, data=buf.getvalue(), timeout=60)
26
- response.raise_for_status()
27
- result = response.json()
28
- # API 응답: [{"generated_text": "..."}]
29
- return result[0]["generated_text"]
30
-
31
- # ─────────────────────────────────────────────────────────────
32
- # 3. MusicGen-small 음악 생성 (10초, via API)
33
- # ─────────────────────────────────────────────────────────────
34
  def generate_music(prompt: str, duration: int = 10) -> str:
35
  payload = {"inputs": prompt, "parameters": {"duration": duration}}
36
- response = requests.post(MUSIC_API, headers=HEADERS, json=payload, timeout=120)
37
- response.raise_for_status()
38
-
39
- # API 응답은 WAV 바이너리
40
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
41
- tmp.write(response.content)
42
  tmp.close()
43
  return tmp.name
44
 
45
- # ─────────────────────────────────────────────────────────────
46
  # 4. 전체 파이프라인
47
- # ─────────────────────────────────────────────────────────────
48
  def process(image):
49
  caption = generate_caption(image)
50
  audio = generate_music(f"A cheerful melody inspired by: {caption}")
51
  return caption, audio
52
 
53
- # ──────────────────────────────────────────────────────────���──
54
- # 5. Gradio 인터페이스
55
- # ─────────────────────────────────────────────────────────────
56
- # 5. Gradio 인터페이스 ──────────────────────────────────────
57
  demo = gr.Interface(
58
  fn=process,
59
  inputs=gr.Image(type="pil"),
@@ -61,14 +53,10 @@ demo = gr.Interface(
61
  gr.Text(label="AI가 생성한 그림 설명"),
62
  gr.Audio(label="생성된 AI 음악 (MusicGen)")
63
  ],
64
- title="🎨 AI 그림-음악 생성기 (Inference API 버전)",
65
- description="이미지를 업로드하면 BLIP-base가 설명을 생성하고, "
66
- "해당 설명으로 MusicGen-small이 10초 음악을 만듭니다.",
67
- # concurrency_count=1 ← 삭제
68
- queue=True # (선택) 동시 요청을 큐잉하려면 이렇게만 두세요
69
- # cache_examples=False # 필요하면 유지
70
- )
71
-
72
 
73
  if __name__ == "__main__":
74
  demo.launch()
 
2
  import gradio as gr
3
  from PIL import Image
4
 
5
+ # ───────────────────────────────────────────────
6
+ # 1. HF Inference API 준비
7
+ # ───────────────────────────────────────────────
8
+ HF_TOKEN = os.getenv("HF_TOKEN") # Spaces → Settings → Secrets
9
  if not HF_TOKEN:
10
+ raise RuntimeError("HF_TOKEN 비밀값이 없습니다. Settings → Secrets 등록하세요.")
11
 
12
  HEADERS = {"Authorization": f"Bearer {HF_TOKEN}"}
13
  CAPTION_API = "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-base"
14
  MUSIC_API = "https://api-inference.huggingface.co/models/facebook/musicgen-small"
15
 
16
+ # ───────────────────────────────────────────────
17
+ # 2. 캡션 생성 함수
18
+ # ───────────────────────────────────────────────
19
  def generate_caption(image_pil: Image.Image) -> str:
20
  buf = io.BytesIO()
21
  image_pil.save(buf, format="PNG")
22
+ resp = requests.post(CAPTION_API, headers=HEADERS, data=buf.getvalue(), timeout=60)
23
+ resp.raise_for_status()
24
+ return resp.json()[0]["generated_text"]
25
 
26
+ # ───────────────────────────────────────────────
27
+ # 3. 음악 생성 함수
28
+ # ───────────────────────────────────────────────
 
 
 
 
 
 
 
29
  def generate_music(prompt: str, duration: int = 10) -> str:
30
  payload = {"inputs": prompt, "parameters": {"duration": duration}}
31
+ resp = requests.post(MUSIC_API, headers=HEADERS, json=payload, timeout=120)
32
+ resp.raise_for_status()
 
 
33
  tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".wav")
34
+ tmp.write(resp.content)
35
  tmp.close()
36
  return tmp.name
37
 
38
+ # ───────────────────────────────────────────────
39
  # 4. 전체 파이프라인
40
+ # ───────────────────────────────────────────────
41
  def process(image):
42
  caption = generate_caption(image)
43
  audio = generate_music(f"A cheerful melody inspired by: {caption}")
44
  return caption, audio
45
 
46
+ # ───────────────────────────────────────────────
47
+ # 5. Gradio UI
48
+ # ───────────────────────────────────────────────
 
49
  demo = gr.Interface(
50
  fn=process,
51
  inputs=gr.Image(type="pil"),
 
53
  gr.Text(label="AI가 생성한 그림 설명"),
54
  gr.Audio(label="생성된 AI 음악 (MusicGen)")
55
  ],
56
+ title="🎨 AI 그림-음악 생성기 (Inference API)",
57
+ description="이미지를 업로드하면 BLIP-base가 설명을 만들고, "
58
+ "해당 설명으로 MusicGen-small이 10초 음악을 생성합니다."
59
+ ).queue() # 필요하면 이렇게 체이닝으로 큐 활성화
 
 
 
 
60
 
61
  if __name__ == "__main__":
62
  demo.launch()