multifuly commited on
Commit
ed9c7a2
·
verified ·
1 Parent(s): aaf7f4d

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +15 -0
  2. README.md +43 -355
  3. app.py +67 -0
  4. requirements.txt +5 -0
Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contrastive Embedding API — Hugging Face Spaces (Docker)
2
+ # 올릴 파일: app.py, requirements.txt, Dockerfile, README.md
3
+ FROM python:3.11-slim
4
+
5
+ RUN useradd -m -u 1000 user
6
+ WORKDIR /app
7
+
8
+ COPY --chown=user requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ COPY --chown=user app.py .
12
+
13
+ ENV PORT=7860
14
+ EXPOSE 7860
15
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -1,355 +1,43 @@
1
- ---
2
- tags:
3
- - sentence-transformers
4
- - sentence-similarity
5
- - feature-extraction
6
- - dense
7
- - generated_from_trainer
8
- - dataset_size:1556
9
- - loss:TripletLoss
10
- base_model: jhgan/ko-sroberta-multitask
11
- widget:
12
- - source_sentence: 개발 준비하고 있어
13
- sentences:
14
- - '[자격증명: 전기기사] 자격증명: 전기기사 | 유형: 국가기술자격 | 분야: 전기 | NCS분류: 전기.전자 | 시행기관: 한국산업인력공단
15
- | 등급: 기사 | 관련전공: ICT로봇공학전공, 휴먼지능로봇공학과, 휴먼・로봇융합전공, 지능형로봇융합전공, 지능로봇학과'
16
- - '[자격증명: SQL개발자(SQLD)] 자격증명: SQL개발자(SQLD) | 유형: 국가민간자격 | 분야: 정보술 | NCS분류: 정보통신
17
- | 시행기관: 한국데이터산업진흥원 | 등급: 1 | 관련전공: IT미디어공학과, IT·디자인융합학부, ICT융합콘텐츠전공, 인공지능융합전공,
18
- 인공지능소프트웨어전공'
19
- - '[자격증명: SQL개발자(SQLD)] 자격증명: SQL개발자(SQLD) | 유형: 국가민간자격 | 분야: 정보기술 | NCS분류: 정보통신
20
- | 시행기관: 한국데이터산업진흥원 | 등급: 1 | 관련전공: IT미디어공학과, IT·디자인융합학부, ICT융합콘텐츠전공, 인공지능융합전공,
21
- 인공지능소프트웨어전공'
22
- - source_sentence: '전공: 국어국문학과 학년: 3학년 희망직무: 개발 관심 자격증: 없음 취득 자격증: 없음 목적: 입문, 취업 준비'
23
- sentences:
24
- - '[자격증명: 철도운송산업기사] 자격증명: 철도운송산업기사 | 유형: 국가기술자격 | 분야: 철도운전.운송 | NCS분류: 운전.운송 | 시행기관:
25
- 한국산업인력공단 | 등급: 산업기사 | 관련전공: 철도전기기관사과, 철도교통학부, 철도운수설비과, 철도운전제어공학과, 철도차량운전과'
26
- - '[자격증명: 데이터분석준전문가(ADsP)] 자격증명: 데이터분석준전문가(ADsP) | 유형: 국가민간자격 | 분야: 정보기술 | NCS분류:
27
- 정보통신 | 시행기관: (재)한국데이터진흥원 | 등급: 1 | 관련전공: 모바일시스템공학과, 모바일융합공학과, 전자공학부모바일공학전공, 전자정보공학부,
28
- IT융합학부'
29
- - '[자격증명: 컴퓨터활용능력 2급] 자격증명: 컴퓨터활용능력 2급 | 유형: 국가기술자격 | 분야: 사업관리 | NCS분류: 사업관리 | 관련전공:
30
- IT학부, AI・데이터공학부, AI・빅데이터학과, AI・컴퓨터공학과, AI빅데이터전공'
31
- - source_sentence: '전공: 소프트웨어학과 학년: 4학년 희망직무: 실무 관심 자격증: 없음 취득 자격증: 정보처리기사 목적: 취업
32
- 준비'
33
- sentences:
34
- - '[자격증명: 측량및지형간정보기사] 자격증명: 측량및지형공간정보기사 | 유형: 국가기술자격 | 분야: 정보기술 | NCS분류: 정보통신 |
35
- 시행기관: 한국산업인력공단 | 등급: 기사 | 관련전공: 지리학과, 지리학과(자연계열), 지적학전공, 지적학과, 위치정보시스템학과'
36
- - '[자격증명: 데이터분석준전문가(ADsP)] 자격증명: 데이터분석준전문가(ADsP) | 유형: 국가민간자격 | 분야: 정보기술 | NCS분류:
37
- 정보통신 | 시행기관: (재)한국데이터진흥원 | 등급: 1 | 관련전공: 모바일시스템공학과, 모바일융합공학과, 전자공학부모바일공학전공, 전자정보공학부,
38
- IT융합학부'
39
- - '[자격증명: SQL개발자(SQLD)] 자격증명: SQL개발자(SQLD) | 유형: 국가민간격 | 분야: 정보기술 | NCS분류: 정보통신
40
- | 시행기관: 한국데이터산업진흥원 | 등급: 1 | 관련전공: IT미디어공학과, IT·디자인융합학부, ICT융합콘텐츠전공, 인공지능융합전공,
41
- 인공지능소프트웨어전공'
42
- - source_sentence: 비전공자인데 개발 공부 시작했어
43
- sentences:
44
- - '[자격증명: 종자기사] 자격증명: 종자기사 | 유형: 국가기술자격 | 분야: 농업 | NCS분류: 농림어업 | 시행기관: 한국산업인력공단
45
- | 등급: 기사 | 관련전공: 식량자원과학과, 식량생명공학과, 생물자원과학부, 자원공학과, 식의약자원개발학과'
46
- - '[자격증명: 빅데이터분석기사] 자격증명: 빅데이터분석기사 | 유형: 국가기술자격 | 분야: 정보기술 | NCS분류: 정보통신 | 시행기관:
47
- 한국산업인력공단 | 등급: 기사'
48
- - '[자격증명: 정보처리기사] 자격증명: 정보처리기사 | 유형: 국가기술자격 | 분야: 정보기술 | NCS분류: 정보통신 | 시행기관: 한국산업인력공단
49
- | 등급: 기사 | 관련전공: 지능・데이터융합학부, 인공지능융합공학부, 첨단공학부, 소프트웨어학부, 정보전자공학과'
50
- - source_sentence: '전공: 경영정보학과 학년: 4학년 희망직무: 사무 관심 자격증: 없음 취득 자격증: 없음 목적: 취업 준비'
51
- sentences:
52
- - '[자격증명: 종자기사] 자격증명: 종자기사 | 유형: 국가기술자격 | 분야: 농업 | NCS분류: 농림어업 | 시행기관: 한국산업인력공단
53
- | 등급: 기사 | 관련전공: 식량자원과학과, 식량생명공학과, 생물자원과학부, 자원공학과, 식의약자원개발학과'
54
- - '[자격증명: 컴퓨터활용능력 2급] 자격증명: 컴퓨터활용능력 2급 | 유형: 국가기술자격 | 분야: 사업관리 | NCS분류: 사업관리 | 관련전공:
55
- IT학부, AI・데이터공학부, AI・빅데이터학과, AI・컴퓨터공학과, AI빅데이터전공'
56
- - '[자격증명: 빅데이터분석기사] 자격증명: 빅데이터분석기사 | 유형: 국가기술자격 | 분야: 정보기술 | NCS분류: 정보통신 | 시행기관:
57
- 한국산업인력공단 | 등급: 기사'
58
- pipeline_tag: sentence-similarity
59
- library_name: sentence-transformers
60
- ---
61
-
62
- # SentenceTransformer based on jhgan/ko-sroberta-multitask
63
-
64
- This is a [sentence-transformers](https://www.SBERT.net) model finetuned from [jhgan/ko-sroberta-multitask](https://huggingface.co/jhgan/ko-sroberta-multitask). It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
65
-
66
- ## Model Details
67
-
68
- ### Model Description
69
- - **Model Type:** Sentence Transformer
70
- - **Base model:** [jhgan/ko-sroberta-multitask](https://huggingface.co/jhgan/ko-sroberta-multitask) <!-- at revision ab957ae6a91e99c4cad36d52063a2a9cf1bf4419 -->
71
- - **Maximum Sequence Length:** 256 tokens
72
- - **Output Dimensionality:** 768 dimensions
73
- - **Similarity Function:** Cosine Similarity
74
- <!-- - **Training Dataset:** Unknown -->
75
- <!-- - **Language:** Unknown -->
76
- <!-- - **License:** Unknown -->
77
-
78
- ### Model Sources
79
-
80
- - **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
81
- - **Repository:** [Sentence Transformers on GitHub](https://github.com/huggingface/sentence-transformers)
82
- - **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
83
-
84
- ### Full Model Architecture
85
-
86
- ```
87
- SentenceTransformer(
88
- (0): Transformer({'max_seq_length': 256, 'do_lower_case': False, 'architecture': 'RobertaModel'})
89
- (1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
90
- )
91
- ```
92
-
93
- ## Usage
94
-
95
- ### Direct Usage (Sentence Transformers)
96
-
97
- First install the Sentence Transformers library:
98
-
99
- ```bash
100
- pip install -U sentence-transformers
101
- ```
102
-
103
- Then you can load this model and run inference.
104
- ```python
105
- from sentence_transformers import SentenceTransformer
106
-
107
- # Download from the 🤗 Hub
108
- model = SentenceTransformer("sentence_transformers_model_id")
109
- # Run inference
110
- sentences = [
111
- '전공: 경영정보학과 학년: 4학년 희망직무: 사무 관심 자격증: 없음 취득 자격증: 없음 목적: 취업 준비',
112
- '[자격증명: 컴퓨터활용능력 2급] 자격증명: 컴퓨터활용능력 2급 | 유형: 국가기술자격 | 분야: 사업관리 | NCS분류: 사업관리 | 관련전공: IT학부, AI・데이터공학부, AI・빅데이터학과, AI・컴퓨터공학과, AI빅데이터전공',
113
- '[자격증명: 종자기사] 자격증명: 종자기사 | 유형: 국가기술자격 | 분야: 농업 | NCS분류: 농림어업 | 시행기관: 한국산업인력공단 | 등급: 기사 | 관련전공: 식량자원과학과, 식량생명공학과, 생물자원과학부, 자원공학과, 식의약자원개발학과',
114
- ]
115
- embeddings = model.encode(sentences)
116
- print(embeddings.shape)
117
- # [3, 768]
118
-
119
- # Get the similarity scores for the embeddings
120
- similarities = model.similarity(embeddings, embeddings)
121
- print(similarities)
122
- # tensor([[ 1.0000, 0.3410, -0.1606],
123
- # [ 0.3410, 1.0000, -0.0415],
124
- # [-0.1606, -0.0415, 1.0000]])
125
- ```
126
-
127
- <!--
128
- ### Direct Usage (Transformers)
129
-
130
- <details><summary>Click to see the direct usage in Transformers</summary>
131
-
132
- </details>
133
- -->
134
-
135
- <!--
136
- ### Downstream Usage (Sentence Transformers)
137
-
138
- You can finetune this model on your own dataset.
139
-
140
- <details><summary>Click to expand</summary>
141
-
142
- </details>
143
- -->
144
-
145
- <!--
146
- ### Out-of-Scope Use
147
-
148
- *List how the model may foreseeably be misused and address what users ought not to do with the model.*
149
- -->
150
-
151
- <!--
152
- ## Bias, Risks and Limitations
153
-
154
- *What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
155
- -->
156
-
157
- <!--
158
- ### Recommendations
159
-
160
- *What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
161
- -->
162
-
163
- ## Training Details
164
-
165
- ### Training Dataset
166
-
167
- #### Unnamed Dataset
168
-
169
- * Size: 1,556 training samples
170
- * Columns: <code>sentence_0</code>, <code>sentence_1</code>, and <code>sentence_2</code>
171
- * Approximate statistics based on the first 1000 samples:
172
- | | sentence_0 | sentence_1 | sentence_2 |
173
- |:--------|:----------------------------------------------------------------------------------|:------------------------------------------------------------------------------------|:------------------------------------------------------------------------------------|
174
- | type | string | string | string |
175
- | details | <ul><li>min: 5 tokens</li><li>mean: 25.75 tokens</li><li>max: 58 tokens</li></ul> | <ul><li>min: 35 tokens</li><li>mean: 94.18 tokens</li><li>max: 119 tokens</li></ul> | <ul><li>min: 48 tokens</li><li>mean: 83.42 tokens</li><li>max: 110 tokens</li></ul> |
176
- * Samples:
177
- | sentence_0 | sentence_1 | sentence_2 |
178
- |:---------------------------------------------------------------------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
179
- | <code>전공: 컴퓨터공학과 학년: 3학년 희망직무: 데이터분석 관심 자격증: 정보처리기사 취득 자격증: 없음 목적: 직무 관련 자격증 추천</code> | <code>[자격증명: SQL개발자(SQLD)] 자격증명: SQL개발자(SQLD) \| 유형: 국가민간자격 \| 분야: 정보기술 \| NCS분류: 정보통신 \| 시행기관: 한국데이터산업진흥원 \| 등급: 1 \| 관련전공: IT미디어공학과, IT·디자인융합학부, ICT융합콘텐츠전공, 인공지능융합전공, 인공지능소프트웨어전공</code> | <code>[자격증명: 측량및지형공간정보기술사] 자격증명: 측량및지형공간정보기술사 \| 유형: 국가기술자격 \| 분야: 정보기술 \| NCS분류: 정보통신 \| 등급: 기술사</code> |
180
- | <code>IT 쪽 취업하고 싶어</code> | <code>[자격증명: SQL개발자(SQLD)] 자격증명: SQL개발자(SQLD) \| 유형: 국가민간자격 \| 분야: 정보기술 \| NCS분류: 정보통신 \| 시행기관: 한국데이터산업진흥원 \| 등급: 1 \| 관련전공: IT미디어공학과, IT·디자인융합학부, ICT융합콘텐츠전공, 인공지능융합전공, 인공지능소프트웨어전공</code> | <code>[자격증명: 종자기사] 자격증명: 종자기사 \| 유형: 국가기술자격 \| 분야: 농업 \| NCS분류: 농림어업 \| 시행기관: 한국산업인력공단 \| 등급: 기사 \| 관련전공: 식량자원과학과, 식량생명공학과, 생물자원과학부, 자원공학과, 식의약자원개발학과</code> |
181
- | <code>전공: 산업데이터공학 학년: 2학년 희망직무: 개발 관심 자격증: 없음 취득 자격증: 없음 목적: 직무 관련 자격증 추천</code> | <code>[자격증명: 데이터분석준전문가(ADsP)] 자격증명: 데이터분석준전문가(ADsP) \| 유형: 국가민간자격 \| 분야: 정보기술 \| NCS분류: 정보통신 \| 시행기관: (재)한국데이터진흥원 \| 등급: 1 \| 관련전공: 모바일시스템공학과, 모바일융합공학과, 전자공학부모바일공학전공, 전자정보공학부, IT융합학부</code> | <code>[자격증명: 측량및지형공간정보기사] 자격증명: 측량및지형공간정보기사 \| 유형: 국가기술자격 \| 분야: 정보기술 \| NCS분류: 정보통신 \| 시행기관: 한국산업인력공단 \| 등급: 기사 \| 관련전공: 지리학과, 지리학과(자연계열), 지적학전공, 지적학과, 위치정보시스템학과</code> |
182
- * Loss: [<code>TripletLoss</code>](https://sbert.net/docs/package_reference/sentence_transformer/losses.html#tripletloss) with these parameters:
183
- ```json
184
- {
185
- "distance_metric": "TripletDistanceMetric.COSINE",
186
- "triplet_margin": 0.2
187
- }
188
- ```
189
-
190
- ### Training Hyperparameters
191
- #### Non-Default Hyperparameters
192
-
193
- - `per_device_train_batch_size`: 16
194
- - `per_device_eval_batch_size`: 16
195
- - `num_train_epochs`: 1
196
- - `multi_dataset_batch_sampler`: round_robin
197
-
198
- #### All Hyperparameters
199
- <details><summary>Click to expand</summary>
200
-
201
- - `do_predict`: False
202
- - `eval_strategy`: no
203
- - `prediction_loss_only`: True
204
- - `per_device_train_batch_size`: 16
205
- - `per_device_eval_batch_size`: 16
206
- - `gradient_accumulation_steps`: 1
207
- - `eval_accumulation_steps`: None
208
- - `torch_empty_cache_steps`: None
209
- - `learning_rate`: 5e-05
210
- - `weight_decay`: 0.0
211
- - `adam_beta1`: 0.9
212
- - `adam_beta2`: 0.999
213
- - `adam_epsilon`: 1e-08
214
- - `max_grad_norm`: 1
215
- - `num_train_epochs`: 1
216
- - `max_steps`: -1
217
- - `lr_scheduler_type`: linear
218
- - `lr_scheduler_kwargs`: None
219
- - `warmup_ratio`: None
220
- - `warmup_steps`: 0
221
- - `log_level`: passive
222
- - `log_level_replica`: warning
223
- - `log_on_each_node`: True
224
- - `logging_nan_inf_filter`: True
225
- - `enable_jit_checkpoint`: False
226
- - `save_on_each_node`: False
227
- - `save_only_model`: False
228
- - `restore_callback_states_from_checkpoint`: False
229
- - `use_cpu`: False
230
- - `seed`: 42
231
- - `data_seed`: None
232
- - `bf16`: False
233
- - `fp16`: False
234
- - `bf16_full_eval`: False
235
- - `fp16_full_eval`: False
236
- - `tf32`: None
237
- - `local_rank`: -1
238
- - `ddp_backend`: None
239
- - `debug`: []
240
- - `dataloader_drop_last`: False
241
- - `dataloader_num_workers`: 0
242
- - `dataloader_prefetch_factor`: None
243
- - `disable_tqdm`: False
244
- - `remove_unused_columns`: True
245
- - `label_names`: None
246
- - `load_best_model_at_end`: False
247
- - `ignore_data_skip`: False
248
- - `fsdp`: []
249
- - `fsdp_config`: {'min_num_params': 0, 'xla': False, 'xla_fsdp_v2': False, 'xla_fsdp_grad_ckpt': False}
250
- - `accelerator_config`: {'split_batches': False, 'dispatch_batches': None, 'even_batches': True, 'use_seedable_sampler': True, 'non_blocking': False, 'gradient_accumulation_kwargs': None}
251
- - `parallelism_config`: None
252
- - `deepspeed`: None
253
- - `label_smoothing_factor`: 0.0
254
- - `optim`: adamw_torch_fused
255
- - `optim_args`: None
256
- - `group_by_length`: False
257
- - `length_column_name`: length
258
- - `project`: huggingface
259
- - `trackio_space_id`: trackio
260
- - `ddp_find_unused_parameters`: None
261
- - `ddp_bucket_cap_mb`: None
262
- - `ddp_broadcast_buffers`: False
263
- - `dataloader_pin_memory`: True
264
- - `dataloader_persistent_workers`: False
265
- - `skip_memory_metrics`: True
266
- - `push_to_hub`: False
267
- - `resume_from_checkpoint`: None
268
- - `hub_model_id`: None
269
- - `hub_strategy`: every_save
270
- - `hub_private_repo`: None
271
- - `hub_always_push`: False
272
- - `hub_revision`: None
273
- - `gradient_checkpointing`: False
274
- - `gradient_checkpointing_kwargs`: None
275
- - `include_for_metrics`: []
276
- - `eval_do_concat_batches`: True
277
- - `auto_find_batch_size`: False
278
- - `full_determinism`: False
279
- - `ddp_timeout`: 1800
280
- - `torch_compile`: False
281
- - `torch_compile_backend`: None
282
- - `torch_compile_mode`: None
283
- - `include_num_input_tokens_seen`: no
284
- - `neftune_noise_alpha`: None
285
- - `optim_target_modules`: None
286
- - `batch_eval_metrics`: False
287
- - `eval_on_start`: False
288
- - `use_liger_kernel`: False
289
- - `liger_kernel_config`: None
290
- - `eval_use_gather_object`: False
291
- - `average_tokens_across_devices`: True
292
- - `use_cache`: False
293
- - `prompts`: None
294
- - `batch_sampler`: batch_sampler
295
- - `multi_dataset_batch_sampler`: round_robin
296
- - `router_mapping`: {}
297
- - `learning_rate_mapping`: {}
298
-
299
- </details>
300
-
301
- ### Framework Versions
302
- - Python: 3.12.12
303
- - Sentence Transformers: 5.2.3
304
- - Transformers: 5.0.0
305
- - PyTorch: 2.10.0+cu128
306
- - Accelerate: 1.12.0
307
- - Datasets: 4.0.0
308
- - Tokenizers: 0.22.2
309
-
310
- ## Citation
311
-
312
- ### BibTeX
313
-
314
- #### Sentence Transformers
315
- ```bibtex
316
- @inproceedings{reimers-2019-sentence-bert,
317
- title = "Sentence-BERT: Sentence Embeddings using Siamese BERT-Networks",
318
- author = "Reimers, Nils and Gurevych, Iryna",
319
- booktitle = "Proceedings of the 2019 Conference on Empirical Methods in Natural Language Processing",
320
- month = "11",
321
- year = "2019",
322
- publisher = "Association for Computational Linguistics",
323
- url = "https://arxiv.org/abs/1908.10084",
324
- }
325
- ```
326
-
327
- #### TripletLoss
328
- ```bibtex
329
- @misc{hermans2017defense,
330
- title={In Defense of the Triplet Loss for Person Re-Identification},
331
- author={Alexander Hermans and Lucas Beyer and Bastian Leibe},
332
- year={2017},
333
- eprint={1703.07737},
334
- archivePrefix={arXiv},
335
- primaryClass={cs.CV}
336
- }
337
- ```
338
-
339
- <!--
340
- ## Glossary
341
-
342
- *Clearly define terms in order to be accessible across audiences.*
343
- -->
344
-
345
- <!--
346
- ## Model Card Authors
347
-
348
- *Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
349
- -->
350
-
351
- <!--
352
- ## Model Card Contact
353
-
354
- *Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
355
- -->
 
1
+ ---
2
+ title: CertWeb Contrastive Embedding API
3
+ sdk: docker
4
+ app_port: 7860
5
+ ---
6
+
7
+ # Contrastive Embedding API
8
+
9
+ CertWeb RAG용 **질의 → 768-dim 벡터** 임베딩을 Hugging Face Spaces에서 서빙합니다.
10
+ 모델은 HF **모델 리포**에서 로드하며, 이 Space 리포에는 모델 파일을 올리지 않습니다.
11
+
12
+ ## 1. 모델 리포에 올리기
13
+
14
+ `HUGGINGFACE_UPLOAD.md` §2 참고: `model.safetensors`, `config.json`, `tokenizer*.json`, `config_sentence_transformers.json`, `modules.json`, `1_Pooling/config.json` 등.
15
+
16
+ ## 2. Space 만들
17
+
18
+ 1. **New Space** → 이름 예: `certweb-contrastive-embed`, **SDK: Docker** 선택.
19
+ 2. 아래 **올릴 파일 목록**의 파일만 Space 리포에 업로드:
20
+ - `app.py`, `requirements.txt`, `Dockerfile`, `README.md`
21
+ 3. Space **Settings** → **Variables**:
22
+ - `HF_MODEL_ID`: 모델 repo ID (예: `your-org/your-model-id`)
23
+ - (비공개 리포면) `HF_TOKEN`: HF 토큰
24
+
25
+ ## 3. CertWeb 백엔드에 연결
26
+
27
+ Render `.env`:
28
+
29
+ ```env
30
+ RAG_CONTRASTIVE_ENABLE=true
31
+ RAG_CONTRASTIVE_EMBEDDING_URL=https://<your-org>-certweb-contrastive-embed.hf.space
32
+ ```
33
+
34
+ Space가 하는 **API URL** (예: `https://xxx.hf.space` 또는 별도 API 경로)을 그대로 넣으면 됩니다.
35
+
36
+ ## API 규약
37
+
38
+ - **POST /**
39
+ Body: `{"inputs": "질의 열"}`
40
+ Response: `[[float, ...]]` (768-dim 벡터 1개를 리스트로 감싼 형태)
41
+
42
+ - **GET /health**
43
+ Response: `{"status": "ok", "model_loaded": true}`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hugging Face Spaces (Docker) — Contrastive 질의 임베딩 API.
3
+
4
+ 모델은 HF Hub에서 로드 (환경변수 HF_MODEL_ID, 예: <org>/<model-id>).
5
+ POST로 텍스트 받아 768-dim 벡터 반환. 백엔드 RAG_CONTRASTIVE_EMBEDDING_URL 연동용.
6
+
7
+ 환경변수:
8
+ - HF_MODEL_ID: SentenceTransformer 모델 ID (필수)
9
+ - HF_TOKEN: 비공개 리포 접근용 토큰 (선택)
10
+ """
11
+ import os
12
+ from typing import List, Union
13
+
14
+ from fastapi import FastAPI
15
+ from fastapi.middleware.cors import CORSMiddleware
16
+ from pydantic import BaseModel
17
+
18
+ MODEL_ID = (os.environ.get("HF_MODEL_ID") or "").strip()
19
+ HF_TOKEN = (os.environ.get("HF_TOKEN") or "").strip() or None
20
+
21
+ model = None
22
+
23
+ app = FastAPI(title="Contrastive Embedding API")
24
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
25
+
26
+
27
+ class EmbedRequest(BaseModel):
28
+ """백엔드 contrastive_retriever가 보내는 형식."""
29
+ inputs: str
30
+
31
+
32
+ def load_model():
33
+ global model
34
+ from sentence_transformers import SentenceTransformer
35
+ print(f"[Embed] 모델 로딩: {MODEL_ID}")
36
+ model = SentenceTransformer(MODEL_ID, token=HF_TOKEN)
37
+ print("[Embed] 로드 완료.")
38
+
39
+
40
+ @app.on_event("startup")
41
+ def startup():
42
+ if MODEL_ID:
43
+ load_model()
44
+ else:
45
+ print("[Embed] HF_MODEL_ID 미설정. 설정 후 재시작.")
46
+
47
+
48
+ @app.post("/")
49
+ def embed(body: EmbedRequest) -> Union[List[List[float]], dict]:
50
+ """
51
+ 질의 문자열을 768-dim 벡터로 변환.
52
+ 응답: [[float,...]] (백엔드가 기대하는 형식) 또는 {"embedding": [float,...]}
53
+ """
54
+ global model
55
+ if not model:
56
+ return {"embedding": [], "error": "HF_MODEL_ID not set"}
57
+ text = (body.inputs or "").strip()
58
+ if not text:
59
+ return {"embedding": [], "error": "empty inputs"}
60
+ vec = model.encode([text], normalize_embeddings=True)
61
+ # 백엔드: list of list 또는 {"embedding": ...} 둘 다 처리
62
+ return vec.tolist()
63
+
64
+
65
+ @app.get("/health")
66
+ def health():
67
+ return {"status": "ok", "model_loaded": model is not None}
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ fastapi>=0.100.0
2
+ uvicorn[standard]>=0.22.0
3
+ sentence-transformers>=2.2.0
4
+ torch>=2.0.0
5
+ pydantic>=2.0.0