Spaces:
Runtime error
Runtime error
File size: 4,392 Bytes
880a3ee 2c2434b 7f25d73 2c2434b 50230bf 2c2434b 55dc152 1c98694 880a3ee 2c2434b a3de917 2c2434b a3de917 2c2434b 50230bf cf2491c a3de917 2c2434b a3de917 880a3ee 97efcb8 880a3ee 97efcb8 880a3ee 2c2434b f439788 55dc152 1c98694 f439788 07d4dbb 4012d7a 7f25d73 4012d7a 7f25d73 4012d7a 7f25d73 4012d7a 7f25d73 4012d7a |
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 |
from fastapi import FastAPI
import pickle
import uvicorn
import pandas as pd
import shutil
import cv2
import tensorflow as tf
import os
from flask import Flask, jsonify, request, flash, redirect, url_for
from pyngrok import ngrok
from fastapi import FastAPI, HTTPException, File, UploadFile, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from file_processing import FileProcess
from get_load_data import GetLoadData
from data_preprocess import DataProcessing
from train_pred import TrainPred
app = FastAPI()
public_url = "https://lambang0902-test-space.hf.space"
app.mount("/static", StaticFiles(directory="static"), name="static")
# Tempat deklarasi variabel-variabel penting
filepath = ""
list_class = ['Diamond','Oblong','Oval','Round','Square','Triangle']
list_folder = ['Training', 'Testing']
face_crop_img = True
face_landmark_img = True
landmark_extraction_img = True
# -----------------------------------------------------
# -----------------------------------------------------
# Tempat deklarasi model dan sejenisnya
selected_model = tf.keras.models.load_model(f'models/fc_model_1.h5', compile=False)
# face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml')
# mp_drawing = mp.solutions.drawing_utils
# mp_face_mesh = mp.solutions.face_mesh
# drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)
# -----------------------------------------------------
# -----------------------------------------------------
# Tempat setting server
UPLOAD_FOLDER = './upload'
UPLOAD_MODEL = './models'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg','zip','h5'}
# -----------------------------------------------------
#Endpoints
#Root endpoints
@app.get("/")
async def root():
# Dapatkan URL publik dari ngrok
ngrok_url = "Tidak Ada URL Publik (ngrok belum selesai memulai)"
return {"message": "Hello, World!", "ngrok_url": ngrok_url}
#-----------------------------------------------------
data_processor = DataProcessing()
data_train_pred = TrainPred()
import random
def preprocessing(filepath):
folder_path = './static/temporary'
shutil.rmtree(folder_path)
os.mkdir(folder_path)
# data_processor.detect_landmark(data_processor.face_cropping_pred(filepath))
data_processor.enhance_contrast_histeq(data_processor.face_cropping_pred(filepath))
files = os.listdir(folder_path)
index = 0
for file_name in files:
file_ext = os.path.splitext(file_name)[1]
new_file_name = str(index) + "_" + str(random.randint(1, 100000)) + file_ext
os.rename(os.path.join(folder_path, file_name), os.path.join(folder_path, new_file_name))
index += 1
# print("Tungu sampai selesaiii")
# train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1 / 255.)
# test_datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1 / 255.)
# ## -------------------------------------------------------------------------
# ## API UNTUK MELAKUKAN PROSES PREDIKSI
# ## -------------------------------------------------------------------------
@app.post('/upload/file',tags=["Predicting"])
async def upload_file(picture: UploadFile):
file_extension = picture.filename.split('.')[-1].lower()
if file_extension not in ALLOWED_EXTENSIONS:
raise HTTPException(status_code=400, detail='Invalid file extension')
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
file_path = os.path.join(UPLOAD_FOLDER, secure_filename(picture.filename))
with open(file_path, 'wb') as f:
f.write(picture.file.read())
try:
processed_img = preprocessing(cv2.imread(file_path))
except Exception as e:
os.remove(file_path)
raise HTTPException(status_code=500, detail=f'Error processing image: {str(e)}')
return JSONResponse(content={'message': 'File successfully uploaded'}, status_code=200)
# @app.get('/get_images', tags=["Predicting"])
# def get_images():
# folder_path = "./static/temporary"
# files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f))]
# urls = []
# for i in range(0, 3):
# url = f'{public_url}/static/temporary/{files[i]}'
# urls.append(url)
# bentuk, persentase = data_train_pred.prediction(selected_model)
# return {'urls': urls, 'bentuk_wajah':bentuk[0], 'persen':persentase}
|