Merge remote-tracking branch 'origin/master'

This commit is contained in:
Андрей Сумин
2025-03-02 23:33:20 +03:00
16 changed files with 171 additions and 50 deletions
+3 -3
View File
@@ -19,6 +19,7 @@ from apps.task.models import (
CompetitionTaskAttachment,
CompetitionTaskSubmission,
)
from apps.task.tasks import analyze_data_task
router = Router(tags=["competition"])
@@ -124,6 +125,7 @@ def submit_task(
status=CompetitionTaskSubmission.StatusChoices.CHECKING,
content=content,
)
analyze_data_task.delay(submission_id=submission.id)
return TaskSubmissionOut(submission_id=submission.id)
@@ -155,6 +157,4 @@ def get_submissions_history(request, competition_id: UUID, task_id: UUID):
)
def get_task_attachments(request, competition_id: UUID, task_id: UUID):
task = get_object_or_404(CompetitionTask, id=task_id)
return status.OK, CompetitionTaskAttachment.objects.filter(
task=task
).all()
return status.OK, CompetitionTaskAttachment.objects.filter(task=task).all()
+5
View File
@@ -23,3 +23,8 @@ class UserSchema(ModelSchema):
class Meta:
model = User
fields = ["id", "email", "username", "created_at", "achievements"]
class StatSchema(Schema):
total_attempts: int
solved_tasks: int
+31 -1
View File
@@ -11,15 +11,17 @@ from api.v1.schemas import (
BadRequestError,
ConflictError,
ForbiddenError,
NotFoundError,
NotFoundError, UnauthorizedError,
)
from api.v1.user.schemas import (
LoginSchema,
RegisterSchema,
TokenSchema,
UserSchema,
StatSchema
)
from apps.user.models import User
from apps.task.models import CompetitionTaskSubmission, ReviewStatusChoices
router = Router(tags=["user"])
@@ -85,3 +87,31 @@ def get_me(request):
def get_user(request, user_id: str):
user = get_object_or_404(User, id=user_id)
return status.OK, user
@router.get(
"/me/stat",
response={
status.OK: StatSchema,
status.UNAUTHORIZED: UnauthorizedError
},
)
def get_my_stat(request):
user_submissions = CompetitionTaskSubmission.objects.filter(
user=request.auth
)
checked_attempts = user_submissions.filter(status=CompetitionTaskSubmission.StatusChoices.CHECKED).all()
success_attempts_cnt = 0
for attempt in checked_attempts:
is_correct = attempt.result.get("correct", None)
if is_correct is None:
is_correct = attempt.result.get("total_points", 0) > 0
if is_correct:
success_attempts_cnt += 1
return StatSchema(
total_attempts=len(user_submissions),
solved_tasks=success_attempts_cnt
)
+1 -1
View File
@@ -35,7 +35,7 @@ class CompetitionEndpointTests(TestCase):
self.valid_headers = {"HTTP_AUTHORIZATION": f"Bearer {token}"}
def get_url(self, competition_id):
return f"/api/v1/competition/{competition_id}"
return f"/api/v1/competitions/{competition_id}"
def test_get_competition_success(self):
response = self.client.get(
+1 -1
View File
@@ -31,7 +31,7 @@ class CompetitionTaskSubmissionAdmin(admin.ModelAdmin):
"user__username",
"user__email",
)
filter = ("plagiarism_checked",)
list_filter = ("plagiarism_checked", "status",)
ordering = ["-timestamp"]
def has_add_permission(self, request, obj=None):
+3 -3
View File
@@ -92,9 +92,9 @@ class CompetitionTaskAttachment(BaseModel):
class CompetitionTaskSubmission(BaseModel):
class StatusChoices(models.TextChoices):
SENT = "sent"
CHECKING = "checking"
CHECKED = "checked"
SENT = "sent", "Отправлено на проверку"
CHECKING = "checking", "Проверка"
CHECKED = "checked", "Проверено"
def submission_content_upload_to(instance, filename) -> str:
return f"submissions/{instance.id}/content/{filename}"
+4 -4
View File
@@ -1,4 +1,4 @@
import requests
import httpx
from celery import shared_task
from django.core.files.base import ContentFile
@@ -17,7 +17,7 @@ def analyze_data_task(self, submission_id):
for f in submission.task.attachments.filter(public=True)
]
response = requests.post(
response = httpx.post(
f"{settings.CHECKER_API_ENDPOINT}/execute",
files=[("files", (f.name, f)) for f in files]
+ [
@@ -40,10 +40,10 @@ def analyze_data_task(self, submission_id):
)
submission.status = CompetitionTaskSubmission.StatusChoices.CHECKED
except requests.exceptions.RequestException as e:
except httpx.RequestError as e:
self.retry(countdown=2**self.request.retries)
except Exception as e:
submission.result = {"error": str(e)}
submission.result = {"error": str(e), "success": False}
submission.status = CompetitionTaskSubmission.StatusChoices.CHECKED
submission.earned_points = 0
finally:
+18
View File
@@ -0,0 +1,18 @@
import os
from pathlib import Path
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / ".env")
REGISTRY_LOGIN = os.getenv("REGISTRY_USERNAME", None)
REGISTRY_PASSWORD = os.getenv("REGISTRY_USERNAME", None)
REGISTRY_URL = os.getenv("REGISTRY_URL", "gitlab.prodcontest.ru:5050")
DOCKER_IMAGE = os.getenv(
"IMAGE", default="gitlab.prodcontest.ru:5050/team-15/project/custom-python"
)
+21 -15
View File
@@ -10,19 +10,25 @@ import tempfile
import logging
from urllib.parse import urlparse
import re
app = FastAPI()
docker_client = docker.from_env()
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
import config
DOCKER_IMAGE = "gitlab.python:3-slim"
CONTAINER_TIMEOUT = 60
MAX_FILE_SIZE = 4 * 1024 * 1024
ALLOWED_FILENAME_CHARS = r"[^a-zA-Z0-9_\-.]"
app = FastAPI()
docker_client = docker.from_env()
logger = logging.getLoggerQ(__name__)
logging.basicConfig(level=logging.INFO)
docker_client.login(
username=config.REGISTRY_LOGIN,
password=config.REGISTRY_PASSWORD,
registry=config.REGISTRY_URL,
)
class FileDetails(BaseModel):
url: HttpUrl = Field(
..., description="URL to download the file from (supports HTTP/HTTPS)"
@@ -130,7 +136,7 @@ def run_container_safely(
volumes[host_path] = {"bind": container_path, "mode": "ro"}
container = docker_client.containers.run(
image=DOCKER_IMAGE,
image=config.DOCKER_IMAGE,
command=command,
volumes=volumes,
working_dir="/execution",
@@ -166,6 +172,14 @@ def run_container_safely(
pass
def validate_file_path(path: str) -> bool:
return (
not os.path.isabs(path)
and os.path.basename(path) == path
and all(c.isalnum() or c in {"_", "-", "."} for c in path)
)
@app.post("/execute", response_model=ExecutionResponse)
async def execute_code(request: ExecutionRequest) -> ExecutionResponse:
try:
@@ -279,11 +293,3 @@ async def health_check() -> HealthCheckResponse:
return HealthCheckResponse(status="healthy", docker="connected")
except docker.errors.DockerException:
return HealthCheckResponse(status="degraded", docker="unavailable")
def validate_file_path(path: str) -> bool:
return (
not os.path.isabs(path)
and os.path.basename(path) == path
and all(c.isalnum() or c in {"_", "-", "."} for c in path)
)
+1
View File
@@ -7,6 +7,7 @@ dependencies = [
"aiohttp>=3.11.13",
"docker>=7.1.0",
"fastapi>=0.115.11",
"python-dotenv>=1.0.1",
"python-multipart>=0.0.20",
"regex>=2024.11.6",
"uvicorn>=0.34.0",
@@ -1,17 +1,19 @@
import React from 'react';
import { FileIcon } from 'lucide-react';
import { FileIcon, Download } from 'lucide-react';
import { Button } from "@/components/ui/button";
interface FileSolutionProps {
selectedFile: File | null;
setSelectedFile: (file: File | null) => void;
fileInputRef: React.RefObject<HTMLInputElement>;
existingFileUrl?: string | null;
}
const FileSolution: React.FC<FileSolutionProps> = ({
selectedFile,
setSelectedFile,
fileInputRef
fileInputRef,
existingFileUrl = null
}) => {
const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files[0]) {
@@ -42,6 +44,14 @@ const FileSolution: React.FC<FileSolutionProps> = ({
}
};
const fileName = selectedFile
? selectedFile.name
: existingFileUrl
? existingFileUrl.split('/').pop() || 'file'
: '';
const hasFile = !!selectedFile || !!existingFileUrl;
return (
<>
<input
@@ -52,19 +62,31 @@ const FileSolution: React.FC<FileSolutionProps> = ({
accept=".jpg,.jpeg,.png,.pptx,.docx,.pdf,.xlsx,.txt"
/>
{selectedFile ? (
{hasFile ? (
<div className="bg-white rounded-lg p-6 flex flex-col items-center justify-center min-h-[180px]">
<div className="flex flex-col items-center">
<FileIcon size={28} className="text-black mb-2" />
<span className="text-sm text-gray-700 font-medium mb-1 font-hse-sans">{selectedFile.name}</span>
<span className="text-xs text-gray-500 font-hse-sans">{(selectedFile.size / 1024).toFixed(1)} KB</span>
<Button
variant="ghost"
className="text-blue-500 text-sm mt-2 p-0 h-auto hover:bg-transparent hover:text-blue-600 font-hse-sans"
onClick={() => setSelectedFile(null)}
>
Выбрать другой файл
</Button>
<span className="text-sm text-gray-700 font-medium mb-1 font-hse-sans">{fileName}</span>
<div className="flex items-center mt-2">
{existingFileUrl && !selectedFile && (
<a
href={existingFileUrl}
download
className="flex items-center text-blue-500 text-sm mr-3 hover:text-blue-600"
>
<Download size={16} className="mr-1" />
Скачать
</a>
)}
<Button
variant="ghost"
className="text-blue-500 text-sm p-0 h-auto hover:bg-transparent hover:text-blue-600 font-hse-sans"
onClick={() => setSelectedFile(null)}
>
{!selectedFile && existingFileUrl ? "Выбрать другой файл" : "Очистить"}
</Button>
</div>
</div>
</div>
) : (
@@ -82,7 +104,7 @@ const FileSolution: React.FC<FileSolutionProps> = ({
Загрузить файл
</span>
<p className="text-xs text-gray-500 text-center font-hse-sans">
Доступные форматы: jpg, jpeg, png
Доступные форматы: jpg, jpeg, png, pptx, docx, pdf, xlsx, txt
</p>
</div>
)}
@@ -3,20 +3,22 @@ import { Sheet, SheetClose, SheetContent, SheetHeader, SheetTitle } from "@/comp
import { Button } from "@/components/ui/button";
import { X } from "lucide-react";
import SolutionStatus from '../SolutionStatus';
import { Solution } from '@/shared/types/task';
import { Solution, TaskType } from '@/shared/types/task';
interface SolutionHistorySheetProps {
isOpen: boolean;
onOpenChange: (open: boolean) => void;
solutions: Solution[];
maxPoints: number
maxPoints: number;
onSolutionSelect: (solution: Solution) => void;
}
const SolutionHistorySheet: React.FC<SolutionHistorySheetProps> = ({
isOpen,
onOpenChange,
solutions,
maxPoints
maxPoints,
onSolutionSelect
}) => {
return (
<Sheet open={isOpen} onOpenChange={onOpenChange}>
@@ -32,10 +34,17 @@ const SolutionHistorySheet: React.FC<SolutionHistorySheetProps> = ({
</div>
</SheetHeader>
<div className="flex flex-col mt-3 space-y-2.5 overflow-y-auto max-h-[calc(100vh-80px)] px-4">
<div className="flex flex-col mt-3 space-y-2.5 overflow-y-auto max-h-[calc(100vh-80px)] px-4 pb-4">
{solutions.length > 0 ? (
solutions.map((solution, index) => (
<div key={index} className="w-full">
<div
key={solution.id || index}
className="w-full cursor-pointer transition-transform hover:scale-[1.01]"
onClick={() => {
onSolutionSelect(solution);
onOpenChange(false);
}}
>
<SolutionStatus solution={solution} maxPoints={maxPoints} />
</div>
))
@@ -29,6 +29,7 @@ const TaskSolution: React.FC<TaskSolutionProps> = ({
}) => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [isHistoryOpen, setIsHistoryOpen] = useState(false);
const [selectedSolutionUrl, setSelectedSolutionUrl] = useState<string | null>(null);
const { id: competitionId } = useParams<{ id: string }>();
const solutionsQuery = useQuery({
@@ -45,6 +46,25 @@ const TaskSolution: React.FC<TaskSolutionProps> = ({
const latestSolution = solutionHistory && solutionHistory.length > 0 ? solutionHistory[solutionHistory.length - 1] : null;
const handleSolutionSelect = async (solution: Solution) => {
if (!solution.content) return;
setSelectedSolutionUrl(solution.content);
try {
if (task.type !== TaskType.FILE) {
const response = await fetch(solution.content);
if (!response.ok) {
throw new Error(`Failed to fetch solution content: ${response.status}`);
}
const text = await response.text();
setAnswer(text);
}
} catch (error) {
console.error('Error loading solution content:', error);
}
};
return (
<div className="md:w-[500px] flex flex-col gap-4">
{latestSolution ? (
@@ -64,6 +84,7 @@ const TaskSolution: React.FC<TaskSolutionProps> = ({
selectedFile={selectedFile}
setSelectedFile={setSelectedFile}
fileInputRef={fileInputRef}
existingFileUrl={selectedSolutionUrl}
/>
)}
@@ -81,6 +102,7 @@ const TaskSolution: React.FC<TaskSolutionProps> = ({
onOpenChange={setIsHistoryOpen}
solutions={solutionHistory}
maxPoints={task.points}
onSolutionSelect={handleSolutionSelect}
/>
</div>
);
+4 -3
View File
@@ -15,8 +15,8 @@ export interface TaskAttachment {
enum TaskType {
INPUT = "input",
FILE = "checker",
CODE = "review",
FILE = "review",
CODE = "checker",
}
enum SolutionStatus {
@@ -29,7 +29,8 @@ interface Solution {
id: string,
status: SolutionStatus,
timestamp: string,
earned_points: number
earned_points: number,
content: string
}
export type {Task, Solution}