File size: 11,296 Bytes
5c263d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# -------------------------------------------------------------------
# This source file is available under the terms of the
# Pimcore Open Core License (POCL)
# Full copyright and license information is available in
# LICENSE.md which is distributed with this source code.
#
#  @copyright  Copyright (c) Pimcore GmbH (https://www.pimcore.com)
#  @license    Pimcore Open Core License (POCL)
# -------------------------------------------------------------------

import os
import torch

#from .training_status import Status
#from .environment_variable_checker import EnvironmentVariableChecker

#from .training_manager import TrainingManager
#from .image_classification.image_classification_trainer import ImageClassificationTrainer
#from .image_classification.image_classification_parameters import ImageClassificationParameters, map_image_classification_training_parameters, ImageClassificationTrainingParameters 
#from .text_classification.text_classification_trainer import TextClassificationTrainer
#from .text_classification.text_classification_parameters import TextClassificationParameters, map_text_classification_training_parameters, TextClassificationTrainingParameters 


from fastapi import FastAPI, Depends, HTTPException, UploadFile, Form, File, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel
from typing import Annotated


import logging
from pathlib import Path
import tempfile
import sys


from transformers import pipeline

app = FastAPI(
    title="Pimcore Local Inference Service",
    description="This services allows HF inference provider compatible inference to models which are not available at HF inference providers.",
    version="1.0.0"
)

#environmentVariableChecker = EnvironmentVariableChecker()
#environmentVariableChecker.validate_environment_variables()

logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)


class StreamToLogger(object):
    def __init__(self, logger, log_level):
        self.logger = logger
        self.log_level = log_level
        self.linebuf = ''

    def write(self, buf):
        for line in buf.rstrip().splitlines():
            self.logger.log(self.log_level, line.rstrip())

    def flush(self):
        pass

sys.stdout = StreamToLogger(logger, logging.INFO)
sys.stderr = StreamToLogger(logger, logging.ERROR)

#classification_trainer: TrainingManager = TrainingManager()


class ResponseModel(BaseModel):
    """ Default response model for endpoints. """
    message: str
    success: bool = True


# ===========================================
# Security Check
# ===========================================

# security = HTTPBearer()
# def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
#     """Verify the token provided by the user."""

#     token = environmentVariableChecker.get_authentication_token()
    
#     if credentials.credentials != token:
#         raise HTTPException(
#             status_code=status.HTTP_401_UNAUTHORIZED,
#             detail="Invalid token",
#             headers={"WWW-Authenticate": "Bearer"},
#         )
#     return {"token": credentials.credentials}


# ===========================================
# Training Status Endpoints
# ===========================================

# @app.get("/get_training_status")
# async def get_task_status(token_data: dict = Depends(verify_token)):
#     """ Get the status of the currently running training (if any). """
#     status = classification_trainer.get_task_status()
#     return {
#         "project": status.get_project_name(),
#         "progress": status.get_progress(),
#         "task": status.get_task(),
#         "status": status.get_status().value
#     }

# @app.put("/stop_training")
# async def stop_task(token_data: dict = Depends(verify_token)):
#     """ Stop the currently running training (if any). """
#     try: 
#         status = classification_trainer.get_task_status()
#         classification_trainer.stop_task()
#         return ResponseModel(message=f"Training stopped for `{ status.get_project_name() }`")
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")


@app.get("/gpu_check")
async def gpu_check():
    """ Check if a GPU is available """

    gpu = 'GPU not available'
    if torch.cuda.is_available():
        gpu = 'GPU is available'
        print("GPU is available")
    else:
        print("GPU is not available")

    return {'success': True, 'gpu': gpu}


from fastapi import Body
from typing import Optional

class TranslationRequest(BaseModel):
    inputs: str
    parameters: Optional[dict] = None

@app.post(
    "/translation/{model_name:path}/", 
)
async def translation(
    model_name: str,
    body: TranslationRequest = Body(
        ...,
        example={
            "inputs": "I am a car",
            "parameters": {
                "repetition_penalty": 1.6,
            }
        }
    )
):
    """
    Execute translation tasks.

    Args:
        model_name (str): The HuggingFace model name to use for translation.
        body (TranslationRequest): The request payload containing translation parameters.

    Returns:
        list: The translation result(s) as returned by the pipeline.
    """

    try:
        pipe = pipeline("translation", model=model_name)
    except Exception as e:
        logger.error(f"Failed to load model '{model_name}': {str(e)}")
        raise HTTPException(
            status_code=404,
            detail=f"Model '{model_name}' could not be loaded: {str(e)}"
        )

    try:       
        result = pipe(body.inputs, **(body.parameters or {}))
    except Exception as e:
        logger.error(f"Inference failed for model '{model_name}': {str(e)}")
        raise HTTPException(
            status_code=500,
            detail=f"Inference failed: {str(e)}"
        )

    return result


# ===========================================
# Fine-Tuning Image Classification 
# ===========================================

# @app.post(
#     "/training/image_classification", 
#     response_model=ResponseModel
# )
# async def image_classification(
#     training_params: Annotated[ImageClassificationTrainingParameters, Depends(map_image_classification_training_parameters)],
#     training_data_zip: Annotated[UploadFile, File(description="The ZIP file containing the training data, with a folder per class which contains images belonging to that class.")],
#     token_data: dict = Depends(verify_token),
#     project_name: str = Form(description="The name of the project. Will also be used as name of resulting model that will be created after fine tuning and as the name of the repository at huggingface."),
#     source_model_name: str = Form('google/vit-base-patch16-224-in21k', description="The source model to be used as basis for fine tuning."),
# ):
#     """
#     Start fine tuning an image classification model with the provided data.
#     """

#     # check if training is running, if so then exit
#     status = classification_trainer.get_task_status()
#     if status.get_status() == Status.IN_PROGRESS or status.get_status() == Status.CANCELLING:
#         raise HTTPException(status_code=405, detail="Training is already in progress.")

#     # Ensure the uploaded file is a ZIP file
#     if not training_data_zip.filename.endswith(".zip"):
#         raise HTTPException(status_code=422, detail="Uploaded file is not a zip file.")

#     try:
#         # Create a temporary directory to extract the contents
#         tmp_path = os.path.join(tempfile.gettempdir(), 'training_data')
#         path = Path(tmp_path)
#         path.mkdir(parents=True, exist_ok=True)

#         contents = await training_data_zip.read()
#         zip_path = os.path.join(tmp_path, 'image_classification_data.zip')
#         with open(zip_path, 'wb') as temp_file:
#             temp_file.write(contents)

#         # prepare parameters
#         parameters = ImageClassificationParameters(
#             training_files_path=tmp_path,
#             training_zip_file_path=zip_path,
#             project_name=project_name,
#             source_model_name=source_model_name,
#             training_parameters=training_params
#         )

#         # start training
#         await classification_trainer.start_training(ImageClassificationTrainer(), parameters)
        
#         return ResponseModel(message="Training started.")
    
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")




# ===========================================
# Fine-Tuning Text Classification 
# ===========================================

# @app.post(
#     "/training/text_classification", 
#     response_model=ResponseModel
# )
# async def text_classificaiton(
#     training_params: Annotated[TextClassificationTrainingParameters, Depends(map_text_classification_training_parameters)],
#     training_data_csv: Annotated[UploadFile, File(description="The CSV file containing the training data, necessary columns `value` (text data) and `target` (classification).")],
#     token_data: dict = Depends(verify_token),
#     project_name: str = Form(description="The name of the project. Will also be used as name of resulting model that will be created after fine tuning and as the name of the repository at huggingface."),
#     training_csv_limiter: str = Form(';', description="The delimiter used in the CSV file."),   
#     source_model_name: str = Form('distilbert/distilbert-base-uncased'),
# ):
#     """Start fine tuning an text classification model with the provided data."""

#     # check if training is running, if so then exit
#     status = classification_trainer.get_task_status()
#     if status.get_status() == Status.IN_PROGRESS or status.get_status() == Status.CANCELLING:
#         raise HTTPException(status_code=405, detail="Training is already in progress")

#     # Ensure the uploaded file is a CSV file
#     if not training_data_csv.filename.endswith(".csv"):
#         raise HTTPException(status_code=422, detail="Uploaded file is not a csv file.")

#     try:
#         # Create a temporary directory to extract the contents
#         tmp_path = os.path.join(tempfile.gettempdir(), 'training_data')
#         path = Path(tmp_path)
#         path.mkdir(parents=True, exist_ok=True)

#         contents = await training_data_csv.read()
#         csv_path = os.path.join(tmp_path, 'data.csv')
#         with open(csv_path, 'wb') as temp_file:
#             temp_file.write(contents)

#         # prepare parameters
#         parameters = TextClassificationParameters(
#             training_csv_file_path=csv_path,
#             training_csv_limiter=training_csv_limiter,
#             project_name=project_name,
#             source_model_name=source_model_name,
#             training_parameters=training_params
#         )

#         # start training
#         await classification_trainer.start_training(TextClassificationTrainer(), parameters)
        
#         return ResponseModel(message="Training started.")
    
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"An error occurred: {str(e)}")