Spaces:
Running
Running
File size: 7,488 Bytes
907b200 | 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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | <?php
namespace App\Http\Controllers\Api;
use App\Http\Requests\Docking\SubmitDockingRequest;
use App\Jobs\ConvertSmilesJob;
use App\Jobs\RunDockingJob;
use App\Models\DockingJob;
use App\Traits\ApiResponseTrait;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Str;
use Laravel\Sanctum\PersonalAccessToken;
use Symfony\Component\HttpFoundation\StreamedResponse;
class DockingController
{
use ApiResponseTrait;
public function submit(SubmitDockingRequest $request)
{
$isSmiles = $request->filled('ligand_smiles');
if ($isSmiles) {
$ligandPath = null;
} else {
$ligandPath = $this->storeAsPdbqt($request->file('ligand_file'), true);
}
$proteinPath = $this->storeAsPdbqt($request->file('protein_file'), false);
$job = DockingJob::create([
'user_id' => $request->user()->id,
'input_type' => $isSmiles ? 'smiles' : 'file',
'smiles' => $isSmiles ? $request->ligand_smiles : null,
'protein_name' => $request->protein_name,
'ligand_name' => $request->ligand_name,
'protein_path' => $proteinPath,
'ligand_path' => $ligandPath,
'status' => 'pending',
]);
$params = [
'center_x' => $request->center_x,
'center_y' => $request->center_y,
'center_z' => $request->center_z,
'box_size_x' => $request->box_size_x,
'box_size_y' => $request->box_size_y,
'box_size_z' => $request->box_size_z,
'exhaustiveness' => $request->exhaustiveness ?? 8,
'n_poses' => $request->n_poses ?? 5,
];
if ($isSmiles) {
ConvertSmilesJob::dispatch($job, $request->ligand_smiles, $params);
} else {
RunDockingJob::dispatch($job, $params);
}
return $this->successResponse('Docking Job Successfully Queued', [
'job_id' => $job->id,
'status' => $job->status,
]);
}
public function history(Request $request)
{
$perPage = min((int) $request->query('per_page', 15), 100);
$paginator = DockingJob::dockingOnly()
->where('user_id', $request->user()->id)
->orderBy('created_at', 'desc')
->paginate($perPage)
->through(function ($job) {
return [
'id' => $job->id,
'status' => $job->status,
'protein' => $job->protein_name,
'ligand' => $job->ligand_name,
'created_at' => $job->created_at->toIso8601String(),
'download_url' => url('/api/docking/download/'.$job->id),
'scores' => $job->vina_scores ?? [],
'error' => $job->status === 'failed' ? ($job->result_data['error'] ?? null) : null,
];
});
return $this->paginatedResponse('Docking history retrieved successfully', $paginator);
}
public function status(Request $request, $id)
{
$job = DockingJob::dockingOnly()
->where('id', $id)
->where('user_id', $request->user()->id)
->first();
if (! $job) {
return $this->errorResponse('Docking job not found or unauthorized', 404);
}
return $this->successResponse('Job details retrieved successfully', [
'id' => $job->id,
'status' => $job->status,
'protein' => $job->protein_name,
'ligand' => $job->ligand_name,
'created_at' => $job->created_at->toIso8601String(),
'download_url' => url('/api/docking/download/'.$job->id),
'scores' => $job->vina_scores ?? [],
'error' => $job->status === 'failed' ? ($job->result_data['error'] ?? null) : null,
]);
}
public function download(Request $request, $id)
{
$token = $request->bearerToken() ?? $request->query('token');
if (! $token) {
return $this->errorResponse('Unauthenticated', 401);
}
$accessToken = PersonalAccessToken::findToken($token);
if (! $accessToken || ! $accessToken->tokenable) {
return $this->errorResponse('Invalid token', 401);
}
$job = DockingJob::dockingOnly()
->where('id', $id)
->where('user_id', $accessToken->tokenable->id)
->first();
if (! $job || $job->status !== 'completed') {
return $this->errorResponse('Docking file not available or unauthorized', 404);
}
$filePath = $job->result_data['output_file'] ?? null;
if (! $filePath || ! file_exists($filePath)) {
return $this->errorResponse('File not found on server', 404);
}
return new StreamedResponse(function () use ($filePath) {
$stream = fopen($filePath, 'rb');
if ($stream) {
fpassthru($stream);
fclose($stream);
}
}, 200, [
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename="docking_result_'.$job->id.'.pdbqt"',
'Content-Length' => filesize($filePath),
]);
}
private function storeAsPdbqt(UploadedFile $file, bool $isLigand): string
{
$ext = strtolower($file->getClientOriginalExtension());
$filename = Str::random(40).'.pdbqt';
$destPath = storage_path('app/private/docking/'.$filename);
if ($ext === 'pdbqt') {
$file->storeAs('docking', $filename);
} elseif ($ext === 'pdb') {
$this->convertPdbToPdbqt($file->getRealPath(), $destPath, $isLigand);
} else {
throw new HttpResponseException(
$this->errorResponse('Unsupported file format: .'.$ext.'. Only .pdb and .pdbqt files are accepted.', 422)
);
}
return $destPath;
}
private function convertPdbToPdbqt(string $source, string $dest, bool $isLigand): void
{
$pythonPath = env('DOCKING_PYTHON_PATH');
$obabel = $pythonPath ? dirname($pythonPath).'/obabel' : 'obabel';
if (! file_exists($obabel)) {
$obabel = 'obabel';
}
$result = Process::timeout(60)->run([
$obabel,
'-ipdb', $source,
'-opdbqt',
'-O', $dest,
]);
if (! $result->successful()) {
Log::error('PDB-to-PDBQT conversion failed', [
'source' => $source,
'dest' => $dest,
'error' => $result->errorOutput(),
]);
throw new HttpResponseException(
$this->errorResponse('Failed to convert PDB file to PDBQT format.', 500)
);
}
$content = file_get_contents($dest);
$lines = explode("\n", $content);
if ($isLigand) {
$lines = array_map(fn ($line) => str_starts_with($line, 'ATOM') ? 'HETATM'.substr($line, 6) : $line, $lines);
} else {
$lines = array_filter($lines, fn ($line) => preg_match('/^(ATOM|HETATM)/', $line));
$lines = array_values($lines);
}
file_put_contents($dest, implode("\n", $lines));
}
}
|