MAS-AI-0000 commited on
Commit
2c99709
·
verified ·
1 Parent(s): 1073599

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -98
app.py CHANGED
@@ -1,98 +1,94 @@
1
- from fastapi import FastAPI, File, UploadFile, Body
2
- from fastapi.responses import RedirectResponse
3
- from fastapi.middleware.cors import CORSMiddleware
4
- from PIL import Image
5
- import io
6
- import numpy as np
7
- from Apps.structure import ImagePredictionResponse, TextPredictionRequest, TextPredictionResponse, PredictionEntry
8
- from Apps.imagePreprocess import profile_image_for_cnn_predict, CNNPredict, ResnetPredict, clip_predict
9
- from Apps.textPreprocess import predict_text
10
- import tensorflow as tf
11
-
12
- origins=[
13
- "http://localhost:5173",
14
- "http://localhost",
15
- "https://authentica-ai.vercel.app",
16
- ]
17
-
18
- app = FastAPI(
19
- title="Authentica API",
20
- description=(
21
- "Simple demo API for image and text prediction. "
22
- "Upload an image to `/predict/image` or POST text to `/predict/text`."
23
- ),
24
- version="0.1.0",
25
- )
26
- app.add_middleware(
27
- CORSMiddleware,
28
- allow_origins=origins,
29
- allow_credentials=True,
30
- allow_methods=["*"],
31
- allow_headers=["*"],
32
- )
33
-
34
- @app.get("/", include_in_schema=False)
35
- async def root():
36
- # Redirect to the automatic Swagger UI provided by FastAPI
37
- return RedirectResponse(url="/docs")
38
-
39
- @app.post(
40
- "/predict/image",
41
- response_model=ImagePredictionResponse,
42
- summary="Predict image using all available models",
43
- description="Upload an image file (jpg/png). It is evaluated on all 3 models and class index/confidence is returned.",
44
- )
45
- async def predict(image: UploadFile = File(...)):
46
- """Accept an image upload and return a prediction using loaded model."""
47
-
48
- image_data = await image.read()
49
- pil_img = Image.open(io.BytesIO(image_data)).convert("RGB")
50
- profile_img = profile_image_for_cnn_predict(pil_img, crop_size=512)
51
- if isinstance(profile_img, str):
52
- return (f"Error processing image: {profile_img}")
53
- else:
54
- print(f"Profile image shape: {profile_img.shape}")
55
- cnnPred = CNNPredict(profile_img)
56
- resnetPred = ResnetPredict(profile_img)
57
- clipPred = clip_predict(pil_img, crop_size=512)
58
- #print(f"CNN Prediction (Real prob): {cnnPred:.4f}")
59
- #print(f"ResNet Prediction (Real prob): {resnetPred:.4f}")
60
- #print(f"CLIP Prediction (AI prob): {clipPred:.4f}")
61
- resnet_class = 1 if resnetPred >= 0.5 else 0
62
- cnn_class = 1 if cnnPred >= 0.5 else 0
63
- clip_class = 0 if clipPred > 0.5 else 1
64
- resnet_conf = resnetPred if resnetPred >= 0.5 else 1 - resnetPred
65
- cnn_conf = cnnPred if cnnPred >= 0.5 else 1 - cnnPred
66
- clip_conf = clipPred if clipPred > 0.5 else 1 - clipPred
67
- #Predicted classes 1 is Real, 0 is AI
68
- predictions = [
69
- PredictionEntry(model="CNN", predicted_class=cnn_class, confidence=round(float(cnn_conf), 4)),
70
- PredictionEntry(model="ResNet", predicted_class=resnet_class, confidence=round(float(resnet_conf), 4)),
71
- PredictionEntry(model="CLIP", predicted_class=clip_class, confidence=round(float(clip_conf), 4)),
72
- ]
73
- return ImagePredictionResponse(predictions=predictions)
74
-
75
- @app.post(
76
- "/predict/text",
77
- response_model=TextPredictionResponse,
78
- summary="Predict text",
79
- description="POST a JSON body with `text` to get a predicted label and confidence.",
80
- )
81
- async def predict_text_endpoint(payload: TextPredictionRequest = Body(...)):
82
- """Accept a text string and return a prediction of whether it's human or AI-generated."""
83
- try:
84
- # Use the text prediction function from textPreprocess.py
85
- result = predict_text(payload.text)
86
-
87
- return TextPredictionResponse(
88
- predicted_class=result["predicted_class"],
89
- confidence=result["confidence"]
90
- )
91
- except Exception as e:
92
- # Return a fallback response in case of error
93
- print(f"Error in text prediction: {e}")
94
- return TextPredictionResponse(predicted_class="Human", confidence=0.5)
95
-
96
- if __name__ == "__main__":
97
- import uvicorn
98
- uvicorn.run(app, host="127.0.0.1", port=8000)
 
1
+ from fastapi import FastAPI, File, UploadFile, Body
2
+ from fastapi.responses import RedirectResponse
3
+ from fastapi.middleware.cors import CORSMiddleware
4
+ from PIL import Image
5
+ import io
6
+ import numpy as np
7
+ from Apps.structure import ImagePredictionResponse, TextPredictionRequest, TextPredictionResponse, PredictionEntry
8
+ from Apps.imagePreprocess import profile_image_for_cnn_predict, CNNPredict, ResnetPredict, clip_predict
9
+ from Apps.textPreprocess import predict_text
10
+ import tensorflow as tf
11
+
12
+ origins=[
13
+ "http://localhost:5173",
14
+ "http://localhost",
15
+ "https://authentica-ai.vercel.app",
16
+ ]
17
+
18
+ app = FastAPI(
19
+ title="Authentica API",
20
+ description=(
21
+ "Simple demo API for image and text prediction. "
22
+ "Upload an image to `/predict/image` or POST text to `/predict/text`."
23
+ ),
24
+ version="0.1.0",
25
+ )
26
+ app.add_middleware(
27
+ CORSMiddleware,
28
+ allow_origins=origins,
29
+ allow_credentials=True,
30
+ allow_methods=["*"],
31
+ allow_headers=["*"],
32
+ )
33
+
34
+ @app.get("/", include_in_schema=False)
35
+ async def root():
36
+ # Redirect to the automatic Swagger UI provided by FastAPI
37
+ return RedirectResponse(url="/docs")
38
+
39
+ @app.post(
40
+ "/predict/image",
41
+ response_model=ImagePredictionResponse,
42
+ summary="Predict image using all available models",
43
+ description="Upload an image file (jpg/png). It is evaluated on all 3 models and class index/confidence is returned.",
44
+ )
45
+ async def predict(image: UploadFile = File(...)):
46
+ """Accept an image upload and return a prediction using loaded model."""
47
+
48
+ image_data = await image.read()
49
+ pil_img = Image.open(io.BytesIO(image_data)).convert("RGB")
50
+ profile_img = profile_image_for_cnn_predict(pil_img, crop_size=512)
51
+ if isinstance(profile_img, str):
52
+ return (f"Error processing image: {profile_img}")
53
+ else:
54
+ print(f"Profile image shape: {profile_img.shape}")
55
+ cnnPred = CNNPredict(profile_img)
56
+ resnetPred = ResnetPredict(profile_img)
57
+ clipPred = clip_predict(pil_img, crop_size=512)
58
+ #print(f"CNN Prediction (Real prob): {cnnPred:.4f}")
59
+ #print(f"ResNet Prediction (Real prob): {resnetPred:.4f}")
60
+ #print(f"CLIP Prediction (AI prob): {clipPred:.4f}")
61
+ resnet_class = 1 if resnetPred >= 0.5 else 0
62
+ cnn_class = 1 if cnnPred >= 0.5 else 0
63
+ clip_class = 0 if clipPred > 0.5 else 1
64
+ resnet_conf = resnetPred if resnetPred >= 0.5 else 1 - resnetPred
65
+ cnn_conf = cnnPred if cnnPred >= 0.5 else 1 - cnnPred
66
+ clip_conf = clipPred if clipPred > 0.5 else 1 - clipPred
67
+ #Predicted classes 1 is Real, 0 is AI
68
+ predictions = [
69
+ PredictionEntry(model="CNN", predicted_class=cnn_class, confidence=round(float(cnn_conf), 4)),
70
+ PredictionEntry(model="ResNet", predicted_class=resnet_class, confidence=round(float(resnet_conf), 4)),
71
+ PredictionEntry(model="CLIP", predicted_class=clip_class, confidence=round(float(clip_conf), 4)),
72
+ ]
73
+ return ImagePredictionResponse(predictions=predictions)
74
+
75
+ @app.post(
76
+ "/predict/text",
77
+ response_model=TextPredictionResponse,
78
+ summary="Predict text",
79
+ description="POST a JSON body with `text` to get a predicted label and confidence.",
80
+ )
81
+ async def predict_text_endpoint(payload: TextPredictionRequest = Body(...)):
82
+ """Accept a text string and return a prediction of whether it's human or AI-generated."""
83
+ try:
84
+ # Use the text prediction function from textPreprocess.py
85
+ result = predict_text(payload.text)
86
+
87
+ return TextPredictionResponse(
88
+ predicted_class=result["predicted_class"],
89
+ confidence=result["confidence"]
90
+ )
91
+ except Exception as e:
92
+ # Return a fallback response in case of error
93
+ print(f"Error in text prediction: {e}")
94
+ return TextPredictionResponse(predicted_class="Human", confidence=0.5)