11import base64
22import json
3+ import os
34
5+ from django .conf import settings
46from django .contrib .auth .decorators import login_required
57from django .core .files .base import ContentFile
68from django .shortcuts import redirect , render
9+ from django .utils .timezone import now
710from home .decorators import profile_required
8- from playground .tasks import doodle_classifier_task , sentiment_analysis_task
11+ from PIL import Image
12+ from transformers import AutoModelForSequenceClassification , AutoTokenizer , pipeline
913
1014from .models import PlaygroundTask
1115
@@ -28,17 +32,47 @@ def sentiment_analysis(request):
2832 if request .method == "POST" :
2933 input_data = request .POST .get ("input_data" )
3034
31- # Create a task entry in the database
32- task = PlaygroundTask .objects .create (
33- user = user ,
34- input_data = input_data ,
35- model_name = "sentiment_analysis" ,
36- status = "PENDING" ,
37- )
38-
3935 # Call Celery and attach the Celery task ID to the database entry
40- celery_task = sentiment_analysis_task .apply_async (args = [task .id , input_data ])
41- task .celery_task_id = celery_task .id
36+ try :
37+ MODEL_DIR = os .path .join (
38+ settings .BASE_DIR ,
39+ "playground" ,
40+ "aiml_models" ,
41+ "finiteautomata_bertweet-base-sentiment-analysis" ,
42+ )
43+
44+ # Load model from saved directory
45+ tokenizer = AutoTokenizer .from_pretrained (MODEL_DIR )
46+ model = AutoModelForSequenceClassification .from_pretrained (MODEL_DIR )
47+ sentiment_pipeline = pipeline (
48+ "sentiment-analysis" , model = model , tokenizer = tokenizer
49+ )
50+
51+ if not model :
52+ raise ValueError (
53+ "Model 'finiteautomata_bertweet-base-sentiment-analysis' not found."
54+ )
55+
56+ # Process the input with the model
57+ result = sentiment_pipeline (input_data )[0 ]
58+
59+ # Create a task entry in the database
60+ task = PlaygroundTask .objects .create (
61+ user = user ,
62+ input_data = input_data ,
63+ model_name = "sentiment_analysis" ,
64+ result = str (result ),
65+ completed_at = now (),
66+ status = "COMPLETED" ,
67+ )
68+
69+ task .save ()
70+
71+ except Exception as e :
72+ task .status = "FAILED"
73+ task .result = str (e )
74+ task .save ()
75+ # raise e
4276 task .save ()
4377
4478 return redirect ("sentiment_analysis" )
@@ -51,19 +85,22 @@ def sentiment_analysis(request):
5185 ).order_by ("-created_at" )
5286
5387 for task in previous_results :
54- if task .result :
55- try :
56- # Replace single quotes with double quotes to make it valid JSON
57- formatted_result = task .result .replace ("'" , '"' )
58- task .result = json .loads (formatted_result )
59- except json .JSONDecodeError :
60- task .result = (
61- {}
62- ) # If JSON is invalid, set it as an empty dictionary
88+ try :
89+ # Replace single quotes with double quotes to make it valid JSON
90+ formatted_result = task .result .replace ("'" , '"' )
91+ task .result = json .loads (formatted_result )
92+ except json .JSONDecodeError :
93+ task .result = {} # If JSON is invalid, set it as an empty dictionary
6394 context = {"previous_results" : previous_results }
6495 return render (request , "playground/sentiment_analysis.html" , context = context )
6596
6697
98+ # Load the pre-trained MNIST model from Hugging Face
99+ mnist_classifier = pipeline (
100+ "image-classification" , model = "farleyknight/mnist-digit-classification-2022-09-04"
101+ )
102+
103+
67104@login_required
68105def doodle_classifier (request ):
69106 user = request .user
@@ -82,16 +119,34 @@ def doodle_classifier(request):
82119 user = user ,
83120 input_data = image_data , # Store the base64 data for reference
84121 model_name = "doodle_classifier" ,
85- status = "PENDING" ,
86122 )
87123
88124 # Save the image file to the task's input_image field
89125 task .input_image .save (f"doodle_{ task .id } .png" , image_file )
90126 task .save ()
91127
92128 # Call Celery task
93- celery_task = doodle_classifier_task .apply_async (args = [task .id ])
94- task .celery_task_id = celery_task .id
129+ try :
130+ # Open the saved PNG image from the input_image field
131+ image = Image .open (task .input_image .path )
132+ print ("image being loaded: " , image .filename )
133+
134+ # Run inference using the pre-trained model
135+ result = mnist_classifier (image )
136+ print (str (result ))
137+ best_prediction = max (result , key = lambda x : x ["score" ])
138+ best_label = best_prediction ["label" ]
139+ # print("Label: ", best_label, "Score: ", best_score)
140+
141+ # Update the task with the result
142+ task .result = best_label # Convert the result to a string for storage
143+ task .status = "COMPLETED"
144+ task .save ()
145+
146+ except Exception as e :
147+ # Handle any errors that occur during processing
148+ task .result = str (e ) # Store the error message
149+ task .status = "FAILED"
95150 task .save ()
96151
97152 return redirect ("doodle_classifier" )
0 commit comments