sparta02 commited on
Commit
d7f0c69
ยท
verified ยท
1 Parent(s): 470f6bb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -195
app.py CHANGED
@@ -1,195 +1,195 @@
1
- from fastapi import FastAPI, HTTPException
2
- from pydantic import BaseModel
3
- from transformers import AutoTokenizer, AutoModelForCausalLM
4
- import torch
5
- from typing import Optional
6
- import uvicorn
7
-
8
- # ===============================
9
- # FastAPI ์•ฑ ์ดˆ๊ธฐํ™”
10
- # ===============================
11
- app = FastAPI(
12
- title="Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API",
13
- description="ํŒŒ์ธํŠœ๋‹๋œ Gemma ๋ชจ๋ธ์„ ํ†ตํ•ด ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•˜๋Š” API",
14
- version="1.0.0"
15
- )
16
-
17
- # ===============================
18
- # ์ „์—ญ ๋ณ€์ˆ˜ (๋ชจ๋ธ ๋กœ๋“œ)
19
- # ===============================
20
- MODEL_PATH = "./gemma2-finetuned"
21
- tokenizer = None
22
- model = None
23
- device = "cpu" # Hugging Face Spaces๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ CPU
24
-
25
- # ===============================
26
- # ์š”์ฒญ/์‘๋‹ต ๋ชจ๋ธ ์ •์˜
27
- # ===============================
28
- class QuestionRequest(BaseModel):
29
- question: str
30
- max_tokens: Optional[int] = 120
31
- temperature: Optional[float] = 0.3
32
- top_k: Optional[int] = 40
33
- top_p: Optional[float] = 0.8
34
- repetition_penalty: Optional[float] = 1.8
35
-
36
- class Config:
37
- json_schema_extra = {
38
- "example": {
39
- "question": "์˜ค๋‹ต๋…ธํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์ •๋ฆฌํ• ๊นŒ์š”?",
40
- "max_tokens": 120,
41
- "temperature": 0.3
42
- }
43
- }
44
-
45
- class AnswerResponse(BaseModel):
46
- question: str
47
- answer: str
48
- full_output: str
49
- model_path: str
50
- device: str
51
-
52
- class HealthResponse(BaseModel):
53
- status: str
54
- model_loaded: bool
55
- device: str
56
-
57
- # ===============================
58
- # ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ ๋กœ๋“œ
59
- # ===============================
60
- @app.on_event("startup")
61
- async def load_model():
62
- """์„œ๋ฒ„ ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ์„ ๋ฉ”๋ชจ๋ฆฌ์— ๋กœ๋“œ"""
63
- global tokenizer, model
64
-
65
- print("๐Ÿš€ ๋ชจ๋ธ ๋กœ๋“œ ์ค‘...")
66
- try:
67
- tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
68
- model = AutoModelForCausalLM.from_pretrained(MODEL_PATH)
69
- model = model.to(device)
70
- model.eval() # ํ‰๊ฐ€ ๋ชจ๋“œ๋กœ ์„ค์ •
71
- print(f"โœ… ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ! (Device: {device})")
72
- except Exception as e:
73
- print(f"โŒ ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")
74
- raise
75
-
76
- # ===============================
77
- # API ์—”๋“œํฌ์ธํŠธ
78
- # ===============================
79
-
80
- @app.get("/", response_model=dict)
81
- async def root():
82
- """๋ฃจํŠธ ์—”๋“œํฌ์ธํŠธ - API ์ •๋ณด"""
83
- return {
84
- "message": "Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API ์„œ๋ฒ„",
85
- "version": "1.0.0",
86
- "description": "์ˆ˜ํ—˜์ƒ Q&A ๋‹ต๋ณ€ ๋ชจ๋ธ",
87
- "endpoints": {
88
- "health": "GET /health - ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ",
89
- "predict": "POST /predict - ์งˆ๋ฌธ์— ๋‹ต๋ณ€",
90
- "docs": "GET /docs - API ๋ฌธ์„œ"
91
- },
92
- "usage": {
93
- "example": {
94
- "method": "POST",
95
- "url": "/predict",
96
- "body": {
97
- "question": "์˜ค๋‹ต๋…ธํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์ •๋ฆฌํ• ๊นŒ์š”?"
98
- }
99
- }
100
- }
101
- }
102
-
103
- @app.get("/health", response_model=HealthResponse)
104
- async def health_check():
105
- """์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ"""
106
- return HealthResponse(
107
- status="healthy" if model is not None else "model_not_loaded",
108
- model_loaded=model is not None,
109
- device=device
110
- )
111
-
112
- @app.post("/predict", response_model=AnswerResponse)
113
- async def predict(request: QuestionRequest):
114
- """
115
- ์งˆ๋ฌธ์— ๋Œ€ํ•œ ๋‹ต๋ณ€ ์ƒ์„ฑ
116
-
117
- - **question**: ๋‹ต๋ณ€์„ ์›ํ•˜๋Š” ์งˆ๋ฌธ
118
- - **max_tokens**: ์ƒ์„ฑํ•  ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜ (๊ธฐ๋ณธ๊ฐ’: 120)
119
- - **temperature**: ์ƒ์„ฑ ๋‹ค์–‘์„ฑ ์กฐ์ ˆ (๊ธฐ๋ณธ๊ฐ’: 0.3, ๋‚ฎ์„์ˆ˜๋ก ๋ณด์ˆ˜์ )
120
- - **top_k**: ์ƒ์œ„ k๊ฐœ ํ† ํฐ๋งŒ ๊ณ ๋ ค (๊ธฐ๋ณธ๊ฐ’: 40)
121
- - **top_p**: nucleus sampling ํ™•๋ฅ  (๊ธฐ๋ณธ๊ฐ’: 0.8)
122
- - **repetition_penalty**: ๋ฐ˜๋ณต ๋ฐฉ์ง€ ๊ฐ•๋„ (๊ธฐ๋ณธ๊ฐ’: 1.8)
123
- """
124
- if model is None or tokenizer is None:
125
- raise HTTPException(status_code=503, detail="๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")
126
-
127
- try:
128
- # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
129
- prompt = f"์งˆ๋ฌธ: {request.question}\n๋‹ต๋ณ€:"
130
-
131
- # ํ† ํฌ๋‚˜์ด์ง•
132
- inputs = tokenizer(prompt, return_tensors="pt")
133
- inputs = inputs.to(device)
134
-
135
- # ๋‹ต๋ณ€ ์ƒ์„ฑ
136
- with torch.no_grad():
137
- outputs = model.generate(
138
- **inputs,
139
- max_new_tokens=request.max_tokens,
140
- temperature=request.temperature,
141
- top_k=request.top_k,
142
- top_p=request.top_p,
143
- do_sample=True,
144
- repetition_penalty=request.repetition_penalty,
145
- no_repeat_ngram_size=4,
146
- eos_token_id=tokenizer.eos_token_id,
147
- pad_token_id=tokenizer.pad_token_id,
148
- )
149
-
150
- # ๊ฒฐ๊ณผ ๋””์ฝ”๋”ฉ
151
- full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
152
-
153
- # ๋‹ต๋ณ€ ๋ถ€๋ถ„๋งŒ ์ถ”์ถœ
154
- answer_only = full_output
155
- if "๋‹ต๋ณ€:" in full_output:
156
- answer_only = full_output.split("๋‹ต๋ณ€:", 1)[1].strip()
157
-
158
- # ๋‹ค์Œ ์งˆ๋ฌธ์ด ๋‚˜์˜ค๋ฉด ๊ทธ ์ „๊นŒ์ง€๋งŒ ์ถ”์ถœ
159
- if "์งˆ๋ฌธ:" in answer_only:
160
- answer_only = answer_only.split("์งˆ๋ฌธ:", 1)[0].strip()
161
-
162
- # HTML ํƒœ๊ทธ๋‚˜ ์ด์ƒํ•œ ๋ฌธ์ž ์ œ๊ฑฐ
163
- if "<" in answer_only:
164
- answer_only = answer_only.split("<", 1)[0].strip()
165
-
166
- return AnswerResponse(
167
- question=request.question,
168
- answer=answer_only,
169
- full_output=full_output,
170
- model_path=MODEL_PATH,
171
- device=device
172
- )
173
-
174
- except Exception as e:
175
- raise HTTPException(status_code=500, detail=f"๋‹ต๋ณ€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
176
-
177
- # ===============================
178
- # ์„œ๋ฒ„ ์‹คํ–‰
179
- # ===============================
180
- if __name__ == "__main__":
181
- print("="*70)
182
- print("๐Ÿš€ Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API ์„œ๋ฒ„ ์‹œ์ž‘")
183
- print("="*70)
184
- print(f"๐Ÿ“ ์„œ๋ฒ„ ์ฃผ์†Œ: http://0.0.0.0:7860")
185
- print(f"๐Ÿ“š API ๋ฌธ์„œ: http://0.0.0.0:7860/docs")
186
- print(f"๐Ÿ”ง Device: {device}")
187
- print("="*70)
188
-
189
- uvicorn.run(
190
- app,
191
- host="0.0.0.0",
192
- port=7860, # Hugging Face Spaces๋Š” 7860 ํฌํŠธ ์‚ฌ์šฉ
193
- log_level="info"
194
- )
195
-
 
1
+ from fastapi import FastAPI, HTTPException
2
+ from pydantic import BaseModel
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import torch
5
+ from typing import Optional
6
+ import uvicorn
7
+
8
+ # ===============================
9
+ # FastAPI ์•ฑ ์ดˆ๊ธฐํ™”
10
+ # ===============================
11
+ app = FastAPI(
12
+ title="Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API",
13
+ description="ํŒŒ์ธํŠœ๋‹๋œ Gemma ๋ชจ๋ธ์„ ํ†ตํ•ด ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•˜๋Š” API",
14
+ version="1.0.0"
15
+ )
16
+
17
+ # ===============================
18
+ # ์ „์—ญ ๋ณ€์ˆ˜ (๋ชจ๋ธ ๋กœ๋“œ)
19
+ # ===============================
20
+ MODEL_PATH = "./gemma2-finetuned"
21
+ tokenizer = None
22
+ model = None
23
+ device = "cpu" # Hugging Face Spaces๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ CPU
24
+
25
+ # ===============================
26
+ # ์š”์ฒญ/์‘๋‹ต ๋ชจ๋ธ ์ •์˜
27
+ # ===============================
28
+ class QuestionRequest(BaseModel):
29
+ question: str
30
+ max_tokens: Optional[int] = 120
31
+ temperature: Optional[float] = 0.3
32
+ top_k: Optional[int] = 40
33
+ top_p: Optional[float] = 0.8
34
+ repetition_penalty: Optional[float] = 1.8
35
+
36
+ class Config:
37
+ json_schema_extra = {
38
+ "example": {
39
+ "question": "์˜ค๋‹ต๋…ธํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์ •๋ฆฌํ• ๊นŒ์š”?",
40
+ "max_tokens": 120,
41
+ "temperature": 0.3
42
+ }
43
+ }
44
+
45
+ class AnswerResponse(BaseModel):
46
+ question: str
47
+ answer: str
48
+ full_output: str
49
+ model_path: str
50
+ device: str
51
+
52
+ class HealthResponse(BaseModel):
53
+ status: str
54
+ model_loaded: bool
55
+ device: str
56
+
57
+ # ===============================
58
+ # ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ ๋กœ๋“œ
59
+ # ===============================
60
+ @app.on_event("startup")
61
+ async def load_model():
62
+ """์„œ๋ฒ„ ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ์„ ๋ฉ”๋ชจ๋ฆฌ์— ๋กœ๋“œ"""
63
+ global tokenizer, model
64
+
65
+ print("๐Ÿš€ ๋ชจ๋ธ ๋กœ๋“œ ์ค‘...")
66
+ try:
67
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
68
+ model = AutoModelForCausalLM.from_pretrained(MODEL_PATH, trust_remote_code=True)
69
+ model = model.to(device)
70
+ model.eval() # ํ‰๊ฐ€ ๋ชจ๋“œ๋กœ ์„ค์ •
71
+ print(f"โœ… ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ! (Device: {device})")
72
+ except Exception as e:
73
+ print(f"โŒ ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")
74
+ raise
75
+
76
+ # ===============================
77
+ # API ์—”๋“œํฌ์ธํŠธ
78
+ # ===============================
79
+
80
+ @app.get("/", response_model=dict)
81
+ async def root():
82
+ """๋ฃจํŠธ ์—”๋“œํฌ์ธํŠธ - API ์ •๋ณด"""
83
+ return {
84
+ "message": "Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API ์„œ๋ฒ„",
85
+ "version": "1.0.0",
86
+ "description": "์ˆ˜ํ—˜์ƒ Q&A ๋‹ต๋ณ€ ๋ชจ๋ธ",
87
+ "endpoints": {
88
+ "health": "GET /health - ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ",
89
+ "predict": "POST /predict - ์งˆ๋ฌธ์— ๋‹ต๋ณ€",
90
+ "docs": "GET /docs - API ๋ฌธ์„œ"
91
+ },
92
+ "usage": {
93
+ "example": {
94
+ "method": "POST",
95
+ "url": "/predict",
96
+ "body": {
97
+ "question": "์˜ค๋‹ต๋…ธํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์ •๋ฆฌํ• ๊นŒ์š”?"
98
+ }
99
+ }
100
+ }
101
+ }
102
+
103
+ @app.get("/health", response_model=HealthResponse)
104
+ async def health_check():
105
+ """์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ"""
106
+ return HealthResponse(
107
+ status="healthy" if model is not None else "model_not_loaded",
108
+ model_loaded=model is not None,
109
+ device=device
110
+ )
111
+
112
+ @app.post("/predict", response_model=AnswerResponse)
113
+ async def predict(request: QuestionRequest):
114
+ """
115
+ ์งˆ๋ฌธ์— ๋Œ€ํ•œ ๋‹ต๋ณ€ ์ƒ์„ฑ
116
+
117
+ - **question**: ๋‹ต๋ณ€์„ ์›ํ•˜๋Š” ์งˆ๋ฌธ
118
+ - **max_tokens**: ์ƒ์„ฑํ•  ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜ (๊ธฐ๋ณธ๊ฐ’: 120)
119
+ - **temperature**: ์ƒ์„ฑ ๋‹ค์–‘์„ฑ ์กฐ์ ˆ (๊ธฐ๋ณธ๊ฐ’: 0.3, ๋‚ฎ์„์ˆ˜๋ก ๋ณด์ˆ˜์ )
120
+ - **top_k**: ์ƒ์œ„ k๊ฐœ ํ† ํฐ๋งŒ ๊ณ ๋ ค (๊ธฐ๋ณธ๊ฐ’: 40)
121
+ - **top_p**: nucleus sampling ํ™•๋ฅ  (๊ธฐ๋ณธ๊ฐ’: 0.8)
122
+ - **repetition_penalty**: ๋ฐ˜๋ณต ๋ฐฉ์ง€ ๊ฐ•๋„ (๊ธฐ๋ณธ๊ฐ’: 1.8)
123
+ """
124
+ if model is None or tokenizer is None:
125
+ raise HTTPException(status_code=503, detail="๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")
126
+
127
+ try:
128
+ # ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
129
+ prompt = f"์งˆ๋ฌธ: {request.question}\n๋‹ต๋ณ€:"
130
+
131
+ # ํ† ํฌ๋‚˜์ด์ง•
132
+ inputs = tokenizer(prompt, return_tensors="pt")
133
+ inputs = inputs.to(device)
134
+
135
+ # ๋‹ต๋ณ€ ์ƒ์„ฑ
136
+ with torch.no_grad():
137
+ outputs = model.generate(
138
+ **inputs,
139
+ max_new_tokens=request.max_tokens,
140
+ temperature=request.temperature,
141
+ top_k=request.top_k,
142
+ top_p=request.top_p,
143
+ do_sample=True,
144
+ repetition_penalty=request.repetition_penalty,
145
+ no_repeat_ngram_size=4,
146
+ eos_token_id=tokenizer.eos_token_id,
147
+ pad_token_id=tokenizer.pad_token_id,
148
+ )
149
+
150
+ # ๊ฒฐ๊ณผ ๋””์ฝ”๋”ฉ
151
+ full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
152
+
153
+ # ๋‹ต๋ณ€ ๋ถ€๋ถ„๋งŒ ์ถ”์ถœ
154
+ answer_only = full_output
155
+ if "๋‹ต๋ณ€:" in full_output:
156
+ answer_only = full_output.split("๋‹ต๋ณ€:", 1)[1].strip()
157
+
158
+ # ๋‹ค์Œ ์งˆ๋ฌธ์ด ๋‚˜์˜ค๋ฉด ๊ทธ ์ „๊นŒ์ง€๋งŒ ์ถ”์ถœ
159
+ if "์งˆ๋ฌธ:" in answer_only:
160
+ answer_only = answer_only.split("์งˆ๋ฌธ:", 1)[0].strip()
161
+
162
+ # HTML ํƒœ๊ทธ๋‚˜ ์ด์ƒํ•œ ๋ฌธ์ž ์ œ๊ฑฐ
163
+ if "<" in answer_only:
164
+ answer_only = answer_only.split("<", 1)[0].strip()
165
+
166
+ return AnswerResponse(
167
+ question=request.question,
168
+ answer=answer_only,
169
+ full_output=full_output,
170
+ model_path=MODEL_PATH,
171
+ device=device
172
+ )
173
+
174
+ except Exception as e:
175
+ raise HTTPException(status_code=500, detail=f"๋‹ต๋ณ€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
176
+
177
+ # ===============================
178
+ # ์„œ๋ฒ„ ์‹คํ–‰
179
+ # ===============================
180
+ if __name__ == "__main__":
181
+ print("="*70)
182
+ print("๐Ÿš€ Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API ์„œ๋ฒ„ ์‹œ์ž‘")
183
+ print("="*70)
184
+ print(f"๐Ÿ“ ์„œ๋ฒ„ ์ฃผ์†Œ: http://0.0.0.0:7860")
185
+ print(f"๐Ÿ“š API ๋ฌธ์„œ: http://0.0.0.0:7860/docs")
186
+ print(f"๐Ÿ”ง Device: {device}")
187
+ print("="*70)
188
+
189
+ uvicorn.run(
190
+ app,
191
+ host="0.0.0.0",
192
+ port=7860, # Hugging Face Spaces๋Š” 7860 ํฌํŠธ ์‚ฌ์šฉ
193
+ log_level="info"
194
+ )
195
+