Skip to content

Commit 6fdbaaf

Browse files
removed the async tasks to reduce complexity
1 parent c44e5c7 commit 6fdbaaf

File tree

11 files changed

+108
-101
lines changed

11 files changed

+108
-101
lines changed

Algolyzer/Algolyzer/__init__.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +0,0 @@
1-
from .celery_app import celery_app
2-
3-
__all__ = ("celery_app",)

Algolyzer/Algolyzer/celery_app.py

Lines changed: 0 additions & 17 deletions
This file was deleted.

Algolyzer/Algolyzer/settings/base.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -97,15 +97,5 @@
9797
STATICFILES_DIRS = [BASE_DIR / "static"]
9898
STATIC_ROOT = BASE_DIR / "staticfiles"
9999

100-
# Celery Configurations
101-
# settings.py
102-
103-
# Celery Settings
104-
CELERY_BROKER_URL = os.getenv(
105-
"CELERY_BROKER_URL", "redis://localhost:6379/0"
106-
) # URL for Redis
107-
CELERY_ACCEPT_CONTENT = ["json"] # Accept JSON formatted tasks
108-
CELERY_TASK_SERIALIZER = "json" # Use JSON serialization
109-
110100
# AIML downloaded models directory
111101
MODEL_DIR = "/aiml_models"

Algolyzer/playground/admin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,5 @@
77
class PlaygroundTaskAdmin(admin.ModelAdmin):
88
list_display = ("id", "user", "model_name", "status", "created_at", "completed_at")
99
list_filter = ("status", "model_name", "created_at")
10-
search_fields = ("user__username", "celery_task_id", "model_name", "input_data")
11-
readonly_fields = ("created_at", "completed_at", "celery_task_id")
10+
search_fields = ("user__username", "model_name", "input_data")
11+
readonly_fields = ("created_at", "completed_at")
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Generated by Django 5.1.4 on 2025-04-03 11:06
2+
3+
from django.db import migrations, models
4+
5+
6+
class Migration(migrations.Migration):
7+
dependencies = [
8+
("playground", "0002_playgroundtask_input_image"),
9+
]
10+
11+
operations = [
12+
migrations.RemoveField(
13+
model_name="playgroundtask",
14+
name="celery_task_id",
15+
),
16+
migrations.AlterField(
17+
model_name="playgroundtask",
18+
name="status",
19+
field=models.CharField(
20+
choices=[("COMPLETED", "Completed"), ("FAILED", "Failed")],
21+
default="PENDING",
22+
max_length=20,
23+
),
24+
),
25+
]

Algolyzer/playground/models.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,10 @@
44

55
class PlaygroundTask(models.Model):
66
STATUS_CHOICES = [
7-
("PENDING", "Pending"),
8-
("PROCESSING", "Processing"),
97
("COMPLETED", "Completed"),
108
("FAILED", "Failed"),
119
]
12-
1310
user = models.ForeignKey(User, on_delete=models.CASCADE)
14-
celery_task_id = models.CharField(max_length=255, unique=True) # Celery's Task ID
1511
model_name = models.CharField(max_length=100) # Selected ML model
1612
input_data = models.TextField() # Store user input (can be JSON)
1713
input_image = models.ImageField(upload_to="doodles/", blank=True, null=True)
@@ -21,4 +17,4 @@ class PlaygroundTask(models.Model):
2117
completed_at = models.DateTimeField(blank=True, null=True)
2218

2319
def __str__(self):
24-
return f"Task {self.celery_task_id} - {self.status}"
20+
return f"Task {self.model_name} - {self.status}"

Algolyzer/playground/templates/playground/doodle_classifier.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ <h2 class="text-xl font-semibold mb-3 px-4">Previous Results</h2>
3838
<div class="stat place-items-center">
3939
<div class="stat-title">Status</div>
4040
<div class="stat-value text-primary">{{ result.status }}</div>
41-
<div class="stat-desc">Pending | Processing | Completed</div>
41+
<div class="stat-desc">Failed | Completed</div>
4242
</div>
4343

4444
<div class="stat place-items-center">

Algolyzer/playground/templates/playground/sentiment_analysis.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ <h2 class="text-xl font-semibold mb-3 px-4">Previous Results</h2>
3232
<div class="stat place-items-center">
3333
<div class="stat-title">Status</div>
3434
<div class="stat-value text-primary">{{ result.status }}</div>
35-
<div class="stat-desc">Pending | Processing | Completed</div>
35+
<div class="stat-desc">Failed | Completed</div>
3636
</div>
3737

3838
<div class="stat place-items-center">

Algolyzer/playground/templates/playground/task_status.html

Lines changed: 0 additions & 20 deletions
This file was deleted.

Algolyzer/playground/views.py

Lines changed: 78 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
import base64
22
import json
3+
import os
34

5+
from django.conf import settings
46
from django.contrib.auth.decorators import login_required
57
from django.core.files.base import ContentFile
68
from django.shortcuts import redirect, render
9+
from django.utils.timezone import now
710
from 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

1014
from .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
68105
def 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

Comments
 (0)