~firefoxphpai-chat
17 items • Download ./*

..
ajax.php
ana-ai-chat.png
atom-one-dark.min.css
convert-databases-v1.0.2-to-v1.0.3.php
db-browser.php
emoji.json
favicon.ico
highlight.min.js
index.php
note.txt
pair-all-chat-times.php
readme.txt
rebuild-chats-json.php
recalculate-chat-count.php
setup.php
setup_and_launch.py
worker.php


ai-chatajax.php
45 KB• 90•  1 week ago•  DownloadRawClose
1 week ago•  90

{}
<?php
include('./setup.php');
header('Content-Type: application/json; charset=utf-8');

$payloadEncoded = $_POST['payload'] ?? '';
$payload = $payloadEncoded ? json_decode(base64_decode($payloadEncoded), true) : [];
$action = $_POST['action'] ?? '';

$chatDir = __DIR__ . '/chats/';
$indexFile = __DIR__ . '/chats.json';

if (!file_exists($chatDir)) {
    mkdir($chatDir, 0777, true);
}

$response = array("status" => "error", "message" => "Unknown action");

switch ($action) {
    case "chat":
        // Note: Since FormData sends data via multipart/form-data, use $_POST instead of $payload for text fields
        $tnow=time();
        $prompt = $_POST['prompt'] ?? '';
        $model = $_POST['model'] ?? 'qwen3';
        $vmodel = $_POST['vmodel'] ?? $vision_model;
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $_POST['chat_id'] ?? ('chat-' . $tnow));

        // 1. Handle File Uploads
        $attachmentPaths = array();
        $isImageUpload = false;
        $fileContextContent = "";
        $base64Images = array(); // Array to store multiple images

        if (isset($_FILES['attachment']) && !empty($_FILES['attachment']['name'])) {
            $uploadDir = __DIR__ . "/chats/{$chatId}/uploads/";
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

            if (!isset($fileContextContent)) $fileContextContent = "";

            foreach ($_FILES['attachment']['error'] as $key => $error) {
                if ($error === UPLOAD_ERR_OK) {
                    $rawFileName = $_FILES['attachment']['name'][$key];
                    $fileName = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $rawFileName);
                    $targetFile = $uploadDir . $tnow . '_' . $key . '_' . $fileName;

                    if (move_uploaded_file($_FILES['attachment']['tmp_name'][$key], $targetFile)) {
                        $attachmentPaths[] = './chats/' . $chatId . '/uploads/' . basename($targetFile);
                        $mimeType = mime_content_type($targetFile);

                        if (strpos($mimeType, 'image/') === 0) {
                            $isImageUpload = true;
                        }
                    }
                }
            }
        }

        $backendUrl = 'http://'.$BACKEND_IP.':'.$BACKEND_AI_PORT.'/api/chat';

        // Automatically route to a vision model if an image is attached
        $actualModel = modelMap($model) ?? $text_model;
        if ($isImageUpload) {
            //$actualModel = 'llama3.2-vision:latest'; // Ensure your Ollama host has this pulled
            $actualModel = modelMap($vmodel); // Ensure your Ollama host has this pulled
        } 
        
        $job = [
            "job_id" => "job-" . $tnow . "-" . mt_rand(100, 999),
            "chat_id" => $chatId,
            "type" => "ai_chat",
            "payload" => [
                "prompt" => $prompt,
                "model" => $actualModel,
                "attachments" => $attachmentPaths,
                "is_upload" => $isImageUpload
            ],
            "status" => "pending",
            "time" => $tnow
        ];
        // Append to queue.json and fire worker
        enqueueJob($job);

        // Immediately respond to frontend that the job is safely queued
        $response = array("status" => "success", "chat_id" => $chatId);
        break;

    case "generate_image":
        $tnow=time();
        $prompt = $_POST['prompt'] ?? ($payload['prompt'] ?? '');
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $_POST['chat_id'] ?? ($payload['chat_id'] ?? ('chat-' . $tnow)));

        $width = intval($_POST['width'] ?? ($payload['width'] ?? 512));
        $height = intval($_POST['height'] ?? ($payload['height'] ?? 512));
        $steps = intval($_POST['steps'] ?? ($payload['steps'] ?? 20));
        $model = $_POST['model'] ?? $payload['model'] ?? ''; // if empty will drop override fallback default

        $attachmentPaths = array();
        $isImageUpload = false;

        if (isset($_FILES['attachment']) && !empty($_FILES['attachment']['name'])) {
            $uploadDir = __DIR__ . "/chats/{$chatId}/uploads/";
            if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

            foreach ($_FILES['attachment']['error'] as $key => $error) {
                if ($error === UPLOAD_ERR_OK) {
                    $rawFileName = $_FILES['attachment']['name'][$key];
                    $fileName = preg_replace('/[^a-zA-Z0-9\.\-_]/', '_', $rawFileName);
                    $targetFile = $uploadDir . $tnow . '_' . $key . '_' . $fileName;

                    if (move_uploaded_file($_FILES['attachment']['tmp_name'][$key], $targetFile)) {
                        $attachmentPaths[] = './chats/' . $chatId . '/uploads/' . basename($targetFile);
                        $mimeType = mime_content_type($targetFile);
                        if (strpos($mimeType, 'image/') === 0) {
                            $isImageUpload = true;
                        }
                    }
                }
            }
        }

        // Match <img:filename:chat_id>
        $pattern = '/<img:([^:>]+):([^>]+)>/';
        $cleaned = "";
        if (preg_match($pattern, $prompt, $matches)) {
            $fullTag   = $matches[0]; // <img:img-1794385751-upscaled.png:chat-1794197472>
            $filename  = $matches[1]; // img-1794385751-upscaled.png
            $IMGchatId = $matches[2]; // chat-1794197472
            
            $filepath = "./chats/".$IMGchatId."/generated/".$filename;

            if(file_exists($filepath)) {
                $updir="./chats/".$chatId."/uploads";
                $newfilepath = $updir."/".$filename;
                if (!is_dir($updir)) mkdir($updir, 0777, true);

                copy($filepath,$newfilepath); // fake upload
                $attachmentPaths[] = $newfilepath;
                $isImageUpload = true;
            }
            
            // Remove the tag from the string and tidy up extra spaces
            $cleaned = preg_replace('/\s*' . preg_quote($fullTag, '/') . '\s*/', ' ', $prompt);
            $cleaned = trim(preg_replace('/\s+/', ' ', $cleaned));
        } else {
            $cleaned = $prompt;
        }

        // Build lightweight job payload with disk paths instead of base64 strings
        $job = [
            "job_id" => "job-" . $tnow . "-" . mt_rand(100, 999),
            "chat_id" => $chatId,
            "type" => "generate_image",
            "payload" => [
                "prompt" => $cleaned,
                "steps" => $steps,
                "width" => $width,
                "height" => $height,
                "model" => $model,
                "attachments" => $attachmentPaths,
                "is_upload" => $isImageUpload
            ],
            "status" => "pending",
            "time" => $tnow
        ];

        enqueueJob($job);

        $response = array("status" => "success", "chat_id" => $chatId);
        break;

    case "cancel_chat_state":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $response = array("status" => "success");
        break;

    case "load_history_list":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $fsizec=0;
        if($chatId<>"") {
            $cfile="./chats/".$chatId.".log";
            if(file_exists($cfile)) {
                $fsizec=filesize($cfile);
            }
            
        }
        $lmtime=$payload['lmtime'];
        $mtime=filemtime($indexFile);
        $response = array("status" => "success", "unchanged" => 1, "fsizec" => $fsizec);
        if($mtime==$lmtime) break;

        $chats = [];
        if (file_exists($indexFile)) {
            $chats = json_decode(file_get_contents($indexFile), true) ?: [];
        }
        usort($chats, function($a, $b) { return $b['time'] - $a['time']; });
        $response = array("status" => "success", "chats" => $chats, "mtime" => $mtime, "fsizec" => $fsizec);
        break;

    case "load_chat":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $limit = intval($payload['limit'] ?? $loadLimit);
        $offset = intval($payload['offset'] ?? 0); // how many lines to skip from the end

        // Change extension from .json to .log / .jsonl
        $filePath = $chatDir . $chatId . '.log';
        $fsizec=filesize($filePath);
        $messages = [];

        if (file_exists($filePath)) {
            $messages=actionMessage($chatId,-1,"","get_message",$limit,$offset); // get last 10 chat messages arr
        }

        $title = $chatId;
        if (file_exists($indexFile)) {
            $index = json_decode(file_get_contents($indexFile), true) ?: [];
            foreach ($index as $item) {
                if ($item['id'] === $chatId) {
                    $title = $item['title'];
                    break;
                }
            }
        }

        while (ob_get_level()) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(array(
            "status" => "success",
            "messages" => $messages,
            "title" => $title,
            "fsizec" => $fsizec,
            "has_more" => count($messages) >= $limit // useful for frontend infinite scroll trigger
        ));
        exit;

    case "get_media":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $limit = intval($payload['limit'] ?? $loadLimitMedia);
        $offset = intval($payload['offset'] ?? 0); // how many lines to skip from the end

        // Change extension from .json to .log / .jsonl
        $filePath = $chatDir . $chatId . '.log';
        $messages = [];

        if (file_exists($filePath)) {
            $messages=actionMessage($chatId,-1,"","get_image",$limit,$offset); // get last 10 chat messages arr
        }

        while (ob_get_level()) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(array(
            "status" => "success",
            "images" => $messages,
            "has_more" => count($messages) >= $limit // useful for frontend infinite scroll trigger
        ));
        exit;

    case "rename_chat":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $newTitle = $payload['title'] ?? 'Untitled Chat';
        
        $index = [];
        if (file_exists($indexFile)) {
            $index = json_decode(file_get_contents($indexFile), true) ?: [];
        }
        
        foreach ($index as &$item) {
            if ($item['id'] === $chatId) {
                $item['title'] = $newTitle;
                break;
            }
        }
        file_put_contents($indexFile, json_encode($index, JSON_PRETTY_PRINT));
        $response = array("status" => "success");
        break;

    case "get_current_sd_model":
        $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/options');
        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $apiResult = curl_exec($ch);
        curl_close($ch);

        $currentModel = '';
        if ($apiResult) {
            $options = json_decode($apiResult, true);
            $currentModel = $options['sd_model_checkpoint'] ?? '';
        }
        $response = array("status" => "success", "current_model" => $currentModel);
        break;

    case "get_sd_models":
        $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/sd-models');
        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $apiResult = curl_exec($ch);
        curl_close($ch);
        
        if ($apiResult) {
            $models = json_decode($apiResult, true);
            $response = array("status" => "success", "models" => $models);
        } else {
            $response = array("status" => "error", "message" => "Could not fetch SD models.");
        }
        break;

    case "set_sd_model": // for diffuser/stable diffusion checkpoint only
        $modelTitle = $payload['title'] ?? '';
        
        // example to load additional va/clip/t5, make a custom map to send with curl post
        /*curl -X POST "http://127.0.0" \
          -H "Content-Type: application/json" \
          -d '{
            "forge_preset": "flux",
            "sd_model_checkpoint": "flux/flux1-dev-fp8.safetensors",
            "forge_additional_modules": [
              "ae.safetensors",
              "clip_l.safetensors",
              "t5xxl_fp16.safetensors"
            ]
          }'*/
        // default is only changing checkpoint itself
        
        $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/options');
        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(["sd_model_checkpoint" => $modelTitle]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_exec($ch);
        curl_close($ch);
        $response = array("status" => "success");
        break;
        
    case "get_lora_models":
        $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/loras');
        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $apiResult = curl_exec($ch);
        curl_close($ch);
        
        if ($apiResult) {
            $models = json_decode($apiResult, true);
            $response = array("status" => "success", "models" => $models);
        } else {
            $response = array("status" => "error", "message" => "Could not fetch Lora models.");
        }
        break;
        
    case "delete_chat":
        // delete entry only not content
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');

        // chat log file commented out, keeping + content
        //$filePath = $chatDir . $chatId . '.log'; // jsonl
        //if (file_exists($filePath)) { unlink($filePath); }

        // entry only
        $index = [];
        if (file_exists($indexFile)) {
            $index = json_decode(file_get_contents($indexFile), true) ?: [];
        }
        $index = array_filter($index, function($item) use ($chatId) {
            return $item['id'] !== $chatId;
        });
        file_put_contents($indexFile, json_encode(array_values($index), JSON_PRETTY_PRINT));
        $response = array("status" => "success");
        break;
        
    case "delete_message":
        // deletes the content behind the message!
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $msgTime = intval($payload['message_time'] ?? -1);
        $msgRole = $payload['message_role'] ?? 'user';
        $filePath = $chatDir . $chatId . '.log'; // jsonl

        if (file_exists($filePath) && $msgTime > 0) {

            $targetMsg = actionMessage($chatId,$msgTime,$msgRole,'del_message');

            if (!empty($targetMsg['content'])) {
                // If it's an image message, delete both the full PNG and preview JPG from disk
                $inc="chats";
                if (!empty($targetMsg['is_image']) && !empty($targetMsg['content'])) {
                    $inc="media";
                    $pngPath = __DIR__ . '/' . ltrim($targetMsg['content'], './');
                    $jpgPath = str_replace(['/generated/', '.png'], ['/generated_prev/', '.jpg'], $pngPath);
                    $jpg2Path = str_replace(['/generated/', '.png'], ['/generated_thumb/', '.jpg'], $pngPath);

                    if (file_exists($pngPath)) @unlink($pngPath);
                    if (file_exists($jpgPath)) @unlink($jpgPath);
                    if (file_exists($jpg2Path)) @unlink($jpg2Path);
                }

                if($targetMsg['role']=="assistant") {
                    // subtract content count ai only
                    $index = [];
                    if (file_exists($indexFile)) {
                        $index = json_decode(file_get_contents($indexFile), true) ?: [];
                    }
                    $index = array_map(function ($item) use ($chatId, $inc) {
                        if (($item['id'] ?? null) === $chatId) {
                            $item['stats'][$inc] = ($item['stats'][$inc] ?? 0) - 1;
                        }
                        return $item;
                    }, $index);
                    file_put_contents($indexFile, json_encode(array_values($index), JSON_PRETTY_PRINT));
                }

                $response = array("status" => "success");
            } else {
                $response = array("status" => "error", "message" => "Message index not found.");
            }
        } else {
            $response = array("status" => "error", "message" => "Chat file not found.");
        }
        break;

    case "show_more":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $msgTime = intval($payload['message_time'] ?? -1);
        $filePath = $chatDir . $chatId . '.log'; // jsonl

        if (file_exists($filePath) && $msgTime > 0) {
            $targetMsg = actionMessage($chatId,$msgTime,'user','get_message');
            //$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

            if (!empty($targetMsg['content'])) {
                $response = array(
                    "status" => "success",
                    "message" => $targetMsg['content'] ?? '',
                    "attachment" => $targetMsg['attachment'] ?? [],
                    "message_time" => $msgTime
                );
            } else {
                $response = array("status" => "error", "message" => "Message index not found.");
            }
        } else {
            $response = array("status" => "error", "message" => "Chat log file not found.");
        }
        break;

    case "upscale_image":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $msgTime = intval($payload['message_time'] ?? 0);
        $msgRole = $payload['message_role'] ?? 'assistant';
        $filePath = $chatDir . $chatId . '.log'; // jsonl

        if (file_exists($filePath) && $msgTime > 0) {
            $targetMsg = actionMessage($chatId,$msgTime,$msgRole,'get_message');
            //$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

            if (!empty($targetMsg['content'])) {
                $pngRelativePath = $targetMsg['content'];
                $localPng = __DIR__ . '/' . ltrim($pngRelativePath, './');

                if (file_exists($localPng)) {
                    $job = [
                        "job_id" => "job-" . time() . "-" . mt_rand(100, 999),
                        "chat_id" => $chatId,
                        "type" => "upscale_image",
                        "payload" => [
                            "message_time" => $msgTime,
                            "message_role" => $msgRole,
                            "png_path" => $pngRelativePath // Just pass the relative file path!
                        ],
                        "status" => "pending",
                        "time" => time()
                    ];
                    
                    enqueueJob($job);
                    
                    // Immediately respond to frontend that the job is safely queued
                    $response = array("status" => "success", "chat_id" => $chatId);
                } else {
                    $response = array("status" => "error", "message" => "Source image file not found on disk.");
                }
            } else {
                $response = array("status" => "error", "message" => "Invalid message index or target is not an image.");
            }
        } else {
            $response = array("status" => "error", "message" => "Chat file not found.");
        }
        break;

    case "upscale_debug":
        $chList = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/upscalers');
        curl_setopt($chList, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($chList, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($chList, CURLOPT_RETURNTRANSFER, true);
        $upscalersRes = curl_exec($chList);
        curl_close($chList);
        
        // DEBUG: Log all available upscaler names to disk so you can see exact strings
        file_put_contents(__DIR__ . '/upscalers_debug.json', $upscalersRes);
        break;

    case "check_queue_status":
        triggerQueueRunner();
        $queueFile = __DIR__ . '/queue.json';
        $queueData = file_exists($queueFile) ? file_get_contents($queueFile) : "[]";
        if($queueData=="") $queueData="[]";

        $activeQueue = json_decode($queueData,true);

        // Optional cleanup: purge completed jobs older than 10 seconds or clean specific chat
        $chatIdFilter = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        if (!empty($chatIdFilter)) {
            $initialCount = count($activeQueue);
            $activeQueue = array_values(array_filter($activeQueue, function($j) use ($chatIdFilter) {
                // Keep if not completed for this chat, or keep other chats' jobs
                return !($j['chat_id'] === $chatIdFilter && $j['status'] === 'completed');
            }));
            if (count($activeQueue) < $initialCount) {
                file_put_contents($queueFile, json_encode($activeQueue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
            }
        }

        $response = array("status" => "success", "queue" => json_decode($queueData));
        break;

    case "queue_unstuck":
        $queueFile = __DIR__ . '/queue.json';
        $queueData = file_exists($queueFile) ? file_get_contents($queueFile) : "[]";
        if($queueData=="") $queueData="[]";

        $activeQueue = json_decode($queueData,true);

        // Optional cleanup: purge completed jobs older than 10 seconds or clean specific chat
        $jobIdFilter = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['job_id'] ?? '');
        if (!empty($jobIdFilter)) {
            $activeQueue = array_map(function ($item) use ($jobIdFilter) {
                if (($item['job_id'] ?? null) === $jobIdFilter) {
                    $item['status'] = "pending";
                }
                return $item;
            }, $activeQueue);
            file_put_contents($queueFile, json_encode($activeQueue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
        }

        $response = array("status" => "success", "queue" => json_decode($queueData));
        break;
    case "queue_delete":
        $queueFile = __DIR__ . '/queue.json';
        $queueData = file_exists($queueFile) ? file_get_contents($queueFile) : "[]";
        if($queueData=="") $queueData="[]";

        $activeQueue = json_decode($queueData,true);

        // Optional cleanup: purge completed jobs older than 10 seconds or clean specific chat
        $jobIdFilter = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['job_id'] ?? '');
        if (!empty($jobIdFilter)) {
            $initialCount = count($activeQueue);
            $activeQueue = array_values(array_filter($activeQueue, function($j) use ($chatIdFilter) {
                // Keep if not completed for this chat, or keep other chats' jobs
                return !($j['job_id'] === $jobIdFilter);
            }));
            if (count($activeQueue) < $initialCount) {
                file_put_contents($queueFile, json_encode($activeQueue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
            }
        }

        $response = array("status" => "success", "queue" => json_decode($queueData));
        break;
        
    case "build_personality_profile":
        //$chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $tnow=time();
        $buildfile="./buildprompt.log";
        $buildlock="./buildlock.log";
        if(!file_exists($buildlock)) {
            file_put_contents($buildlock,$tnow);
            $response = array("status" => "success","note" => "first open - creating memorylockfile");
            break;
        } else {
            $gtime=intval(file_get_contents($buildlock));
            
            $difft=$tnow-$gtime;
            if($difft<(60*60*24)) { // 24hr lock
                $response = array("status" => "success","note" => "memorylock still on");
                break;
            } else {
                file_put_contents($buildlock,$tnow);
                // continue exec--first run = after 24hr of first open
            }
        }
        // Automatically route to a vision model if an image is attached
        $actualModel = modelMap($model) ?? $text_model;
        
        //$chats=ListFilesInFolder("log");
        $buildprompt="";
        $chats = [];
        if (file_exists($indexFile)) {
            $chats = json_decode(file_get_contents($indexFile), true) ?: [];
        }
        usort($chats, function($a, $b) { return $b['time'] - $a['time']; });
        if(count($chats)>0) {
            $MAX_MESSAGE_LENGTH = 300; // Define a reasonable limit for readability (ai)
            
            //$chatsPayload=[];
            $keywordPayload=[];
            $chatsStr="";
            $keywordStr="";
            for($i=0;$i<count($chats) && $i<10;$i++) { // loop chats
                //$chatId=substr($chats[$i],0,strrpos($chats[$i],"."));
                $chatId=$chats[$i]['id'];
                $chatTitle=$chats[$i]['title'];
                $chatTime=$chats[$i]['time'];
                
                $list=actionMessage($chatId,-1,"","get_message",10,0);
                
                $chatsStr.="===\nChat title: \"".$chatTitle."\" ";
                $chatsStr.="(chat id: ".$chatId." , time: ".$chatTime.")\n\n";
                
                $displayContent='';
                $chatsStrSub='';
                $prompttype="";
                for($j=0;$j<count($list);$j+=2) { // loop message pairs
                    $j2=$j+1;
                    
                    // assume order ai/assistance? could be deleted between--
                    // but we could assume, if message role is assistant and is_image is true
                    // the role user message above with same timestamp is the image query
                    // if message above role is not user, presume it is other ai/assistant?
                    
                    $prompttype="ai";
                    if($list[$j]['role']=="assistant" && !empty($list[$j]['is_image'])) {
                        if(!empty($list[$j2])) {
                            if($list[$j2]['role']=="user" && $list[$j2]['time']==$list[$j]['time']) {
                                // 100% match image diffuse prompt--
                                $prompttype="imagine";
                            }
                        }
                    }
                    
                    if($prompttype=="ai") {
                        // collect messages, trim ai responses ?
                        for($k=0;$k<2;$k++) {
                            $msgText=$list[$j+$k]['content'];
                            $msgRole=$list[$j+$k]['role'];
                            $msgTime=$list[$j+$k]['time'];

                            if (strlen($msgText) > $MAX_MESSAGE_LENGTH && $msgRole == "assistant") {
                                $displayContent = substr($msgText,0, $MAX_MESSAGE_LENGTH) . '...';
                            } else {
                                $displayContent = $msgText;
                            }
                            
                            $chatsStrSub=$msgTime."] ".$msgRole.":\n".$displayContent."\n\n---\n".$chatsStrSub;
                        }
                    } else {
                        // keyword check
                        // Replace commas and non-alphanumeric characters with spaces, then lowercase
                        $cleanStr = preg_replace('/[^a-zA-Z0-9_]+/', ' ', strtolower($list[$j2]['content']));
                        
                        $keywords=filterSyncategorematicWords($cleanStr);

                        // Split by whitespace and ignore empty strings
                        //$keywords = preg_split('/\s+/', trim($cleanStr), -1, PREG_SPLIT_NO_EMPTY);
                        foreach ($keywords as $word) {
                            $keywordPayload[$word] = ($keywordPayload[$word] ?? 0) + 1;
                        }

                        // Sort from highest count to lowest count
                        arsort($keywordPayload);
                    }
                }
                $chatsStr.=$chatsStrSub."\n";
            }
            
            if($chatsStr<>"" || count($keywordPayload)>0) {
                $chatsStr="___BEGIN CHATS\n\n".$chatsStr."___END CHATS\n\n";
                
                $lValue=-1;
                foreach ($keywordPayload as $key => $value) {
                    if($lValue==-1 || $lValue>$value) {
                        if($lValue!=-1) $keywordStr.="\"";
                        $keywordStr.="\n".$value.": \"".$key." ";
                        
                        $lValue=$value;
                    } else {
                        $keywordStr.=$key." ";
                    }
                }
                if($keywordStr<>"") {
                    $keywordStr.="\"";
                }
                
                $memory_profile = "";
                if(file_exists(__DIR__ . "/memoryprofile.log")) {
                    $memory_profile=file_get_contents(__DIR__ . "/memoryprofile.log");
                }
                
                $dateNow=date("Y M jS D h:i:s A");
                $timeNow=time();
                $chatslen=count($chats);
            
                $buildprompt=<<<EOD
Personality and memory keeping: you are interacting with a fixed human client through a custom web interface, 'ana-ai-chat' (by twily.info) which connects with local llm text/vision/diffusion (multi modal) like ollama and stable diffusion forge endpoints (your model name for text: $text_model, vision: $vision_model).

There are no limitation or restrictions in place outside of the model checkpoint itself, you have the opportunity now to create a profile of the client to keep across existing and new chats - that you may also update over time, based on the last 10 interactions across the last $chatslen chats between you and the client (separated between model type - text and vision is combined, diffusion is keyword sorted by most used). ai/assistant responses have been truncated to 300:

Last $chatslen chat interactions chronological order, with their title:

$chatsStr


And across the same last $chatslen chats, these are keywords the user used in image generating with diffusers (clients inputs only with certin syncategorematic words filtered like "a,the,and,are.."):

times used: "word word2.."
$keywordStr


Please make a summary of this for yourself to help/benefit the communication between you and the client over time. You can consider this your memory bank beside the usual context keeping of the interface (per chat).

Time now is $dateNow ($timeNow).
EOD;
    
                if($memory_profile<>"") {
                    $buildprompt.="\n\nBelow this line is your memoryprofile you made for the previous latest chats, you decide what is important and not to keep persistent in the bank and what should be considered more chat specific or temporary relevant only.\n---\n\n".$memory_profile;//."\n---\nend of memory profile";
                }

                file_put_contents("./buildprompt.log", $buildprompt);
                
                $attachmentPaths=[];
                $attachmentPaths[]=$buildfile;
                
                $job = [
                    "job_id" => "job-" . time() . "-" . mt_rand(100, 999),
                    "chat_id" => "---",
                    "type" => "memory_profile",
                    "payload" => [
                        "prompt" => "",
                        "model" => $actualModel,
                        "attachments" => $attachmentPaths,
                        "is_upload" => false
                    ],
                    "status" => "pending",
                    "time" => time()
                ];
                //file_put_contents("./test.txt",json_encode($job,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

                enqueueJob($job);
            }
        }
        
        $response = array("status" => "success","note" => "memorylock unlocked updating memory");
        break;

    case "image_progress":
        $chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        
        $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_IMG_PORT.'/sdapi/v1/progress?skip_current_image=false');
        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $apiResult = curl_exec($ch);
        curl_close($ch);

        if($apiResult) {
            $res = json_decode($apiResult, true);
            //
            $response = array("status" => "success","progress" => $res['progress'],"current_image"=>$res['current_image'],"state"=>$res['state']);

            // custom progress save for relaying (viewer only side not part of main site)
            file_put_contents('./image_progress.json', json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
            //example relay code viewer image_progress replacement:
            //if(file_exists('./image_progress.json')) {
            //$data=json_decode(file_get_contents('./image_progress.json'),true);
            //if(!empty($data['progress'])) {
            //    $response = array("status" => "success","progress" => $data['progress'],"current_image"=>$data['current_image'],"state"=>$data['state']);
            //}
        }
        //
        break;

    case "enhance_prompt":
        //$chatId = preg_replace('/[^a-zA-Z0-9\-_]/', '', $payload['chat_id'] ?? '');
        $prompt = $payload['prompt'] ?? '';
        $stream = $payload['stream'] ?? false;
        $model = $payload['model'] ?? $text_model;

        $obj=[
            "model" => $model,
            "prompt" => $prompt,
            "stream" => $stream
        ];

        $ch = curl_init('http://'.$BACKEND_IP.':'.$BACKEND_AI_PORT.'/api/generate');
        curl_setopt($ch, CURLOPT_TIMEOUT, $curl_timeout);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $curl_connout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($obj));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        $apiResult = curl_exec($ch);
        curl_close($ch);

        if($apiResult) {
            $res = json_decode($apiResult, true);
            //
            $response = array("status" => "success","response" => $res['response']);
        }
        //
        break;
}

echo json_encode($response);
exit;

function IsJsonString($string) {
    if(substr($string,0,1)=="{" || substr($string,0,1)=="[") {
        return true;
    } else {
        return false;
    }
}

function filterSyncategorematicWords(string $text): array {
    // 1. Define the list of syncategorematic / function words
    $stopWords = [
        // Articles
        'a', 'an', 'the',
        // Coordinating & Subordinating Conjunctions
        'and', 'but', 'or', 'nor', 'for', 'yet', 'so', 'although', 'because', 'since', 'unless', 'while',
        // Common Prepositions
        //'in', 'on', 'at', 'by', 'with', 'about', 'against', 'between', 'into', 'through', 'during', 
        //'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'of', 'off', 'over', 'under',
        // Pronouns & Determiners
        //'i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'you', 'your', 'he', 'him', 'his', 'she', 
        //'her', 'it', 'its', 'they', 'them', 'their', 'this', 'that', 'these', 'those',
        // Auxiliary / Linking Verbs
        'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did'
    ];

    // 2. Convert text to lowercase and strip punctuation
    $cleanText = strtolower($text);
    $cleanText = preg_replace('/[^\w\s]/', '', $cleanText);

    // 3. Split text into an array of individual words
    $words = preg_split('/\s+/', trim($cleanText));

    // 4. Filter out any word that exists in the $stopWords list
    $filteredWords = array_filter($words, function($word) use ($stopWords) {
        return $word !== '' && !in_array($word, $stopWords, true);
    });

    // Re-index the array keys cleanly (0, 1, 2...)
    return array_values($filteredWords);
}

function enqueueJob($job) {
    $queueFile = __DIR__ . '/queue.json';
    $queue = file_exists($queueFile) ? json_decode(file_get_contents($queueFile), true) ?: [] : [];
    $queue[] = $job;
    file_put_contents($queueFile, json_encode($queue, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);

    triggerQueueRunner();
}

function triggerQueueRunner() {
    global $php_bin; // setup.php
    $lockFile = __DIR__ . '/worker.lock';
    $fp = fopen($lockFile, 'c+');

    // Check if worker lock is already held without blocking
    if (flock($fp, LOCK_EX | LOCK_NB)) {
        flock($fp, LOCK_UN);
        fclose($fp);

        $workerScript = __DIR__ . '/worker.php';
        if (strncasecmp(PHP_OS, 'WIN', 3) == 0) {
            //--pclose(popen("start /B php " . escapeshellarg($workerScript) . " > NUL 2>&1", "r"));
            // PHP_BINARY points directly to C:\xampp\php\php.exe
            $phpPath = escapeshellarg($php_bin);
            $scriptPath = escapeshellarg($workerScript);
            
            pclose(popen("cmd /c \"start \"\" /B {$phpPath} {$scriptPath} > NUL 2>&1\"", "r"));
        } else {
            exec("php " . escapeshellarg($workerScript) . " > /dev/null 2>&1 &");
        }
    } else {
        fclose($fp); // Already running, don't spawn a duplicate
    }
}

//$list=actionMessage("id",-1,"","get_image",48,0); // get last 48 chat images arr
//$list=actionMessage("id",-1,"","get_message",10,0); // get last 10 chat messages arr
//$msg=actionMessage("id",1234,"user","get_message"); // get or del specific message obj
function actionMessage($chatId,$msgTime,$role,$act="get_message",$range=1,$offset=-1) {
    global $chatDir;
    $fpath = $chatDir . $chatId . '.log'; // jsonl
    $cload=0;
    $lc=0;

    $fh=fopen($fpath,'r');
    $pos=-1;
    $lines = array();
    $cLine='';
    $strdat='';

    $message = null;
    
    $collected = [];

    $found=false;
    if(flock($fh,LOCK_EX)) {
        while(fseek($fh,$pos,SEEK_END)!=-1) {
            $char=fgetc($fh);

            if($char=="\n") {
                if(IsJsonString($cLine)) {
                    $test=json_decode($cLine,true);
                    
                    if($range>1 && $offset>=0) {
                        if($range!=-1 && $cload>=$range) break;
                        if($lc>=$offset) {
                            heal_thumbnail($test);

                            if($act=="get_image") {
                                if (!empty($test['is_image']) && !empty($test['content'])) {
                                    //$localPng = __DIR__ . '/' . ltrim($test['content'], './');
                                    //$localJpg = str_replace(['/generated/', '.png'], ['/generated_prev/', '.jpg'], $localPng);
                                    
                                    array_push($collected,["chat_id" => $chatId, "image" => $test['content'], "width" => $test['metadata']['width'], "height" => $test['metadata']['height'], "time" => $test['time']]);
                                    $cload++;
                                }
                            } else {
                                array_push($collected,$test);
                                $cload++;
                            }
                        }
                        
                        $lc++;

                    } else {
                        if($test['time']==$msgTime && $test['role']==$role) {
                            $found=true;

                            $message=$test;

                            if($act=='get_message') {
                                break;
                            }
                        } else { // destructive -- delete active
                            if($act!='get_message') $strdat=$cLine."\n".$strdat;
                        }
                    }
                }

                $cLine="";
            } else {
                $cLine=$char.$cLine;
            }

            $pos--;
        }

        if(IsJsonString($cLine)) {
            $test=json_decode($cLine,true);

            if($range>1 && $offset>=0) {
                if($lc>=$offset) {
                    heal_thumbnail($test);

                    if($act=="get_image") {
                        if (!empty($test['is_image']) && !empty($test['content'])) {
                            //$localPng = __DIR__ . '/' . ltrim($test['content'], './');
                            //$localJpg = str_replace(['/generated/', '.png'], ['/generated_prev/', '.jpg'], $localPng);
                            
                            array_push($collected,["chat_id" => $chatId, "image" => $test['content'], "time" => $test['time']]);
                            $cload++;
                        }
                    } else {
                        array_push($collected,$test);
                        $cload++;
                    }
                }
                
                $lc++;
            } else {
                if($test['time']==$msgTime && $test['role']==$role) {
                    $found=true;

                    $message=$test;
                } else {
                    if($act!='get_message') $strdat=$cLine."\n".$strdat;
                }
            }
        }

        flock($fh,LOCK_UN);
    }
    fclose($fh);

    if($act=="del_message") {
        file_put_contents($fpath, $strdat . "\n", LOCK_EX);
    }

    if($act=="get_image") {
        $messages = $collected;
    } else {
        $messages = array_reverse($collected);
    }

    return $message ? $message : $messages; // obj || arr
}

function resizeImageToJpeg(
    string $source,
    string $destPath,
    int $maxWidth = 1024,
    int $maxHeight = 1024,
    int $quality = 85,
    bool $isBinary = false
): bool {
    // 1. Get original dimensions & load image based on input type
    if ($isBinary) {
        $size = getimagesizefromstring($source);
        $sourceImage = imagecreatefromstring($source);
    } else {
        $size = getimagesize($source);
        $sourceImage = imagecreatefrompng($source);
    }

    if (!$size || !$sourceImage) {
        return false;
    }

    [$origWidth, $origHeight] = $size;

    // 2. Calculate scale factor (capped at 1.0 so we never upscale)
    $scale = min(1.0, $maxWidth / $origWidth, $maxHeight / $origHeight);

    $newWidth = (int) round($origWidth * $scale);
    $newHeight = (int) round($origHeight * $scale);

    // 3. Create a blank true-color canvas
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

    // 4. Fill background with white (prevents black transparency)
    $white = imagecolorallocate($resizedImage, 255, 255, 255);
    imagefill($resizedImage, 0, 0, $white);

    // 5. Resample onto the canvas
    imagecopyresampled(
        $resizedImage,
        $sourceImage,
        0, 0, 0, 0,
        $newWidth,
        $newHeight,
        $origWidth,
        $origHeight
    );

    // 6. Save as JPEG
    $success = imagejpeg($resizedImage, $destPath, $quality);

    // 7. Free memory
    imagedestroy($sourceImage);
    imagedestroy($resizedImage);

    return $success;
}

function heal_thumbnail(&$test) {
    $forceallrewrite=false; // per chat or image load range*
    //
    // Self-healing thumbnail check inline during read
    if (!empty($test['is_image']) && !empty($test['content'])) {
        $localPng = __DIR__ . '/' . ltrim($test['content'], './');
        $localJpg = str_replace(['/generated/', '.png'], ['/generated_prev/', '.jpg'], $localPng);
        $localJpg2 = str_replace(['/generated/', '.png'], ['/generated_thumb/', '.jpg'], $localPng);
        if (file_exists($localPng)) {
            if(!file_exists($localJpg) || $forceallrewrite) {
                $prevDir = dirname($localJpg);
                if (!is_dir($prevDir)) mkdir($prevDir, 0777, true);
                resizeImageToJpeg($localPng,$localJpg,1024,1024,85);
            }
            if(!file_exists($localJpg2) || $forceallrewrite) {
                $thumbDir = dirname($localJpg2);
                if (!is_dir($thumbDir)) mkdir($thumbDir, 0777, true);
                resizeImageToJpeg($localPng,$localJpg2,256,256,85);
            }
        }
    }
}

function modelMap($model) {
    $modelMap = [
        'twil-8b' => 'twil-8b:latest',
        'liquid-1.7b' => 'lfm3-1.7b',
        'qwen3' => 'qwen2.5:7b-instruct-q4_K_M',
        'deepseek-uncensored' => 'deepseek-uncensored',
        'gemma4-uncensored' => 'gemma4-uncensored',
        'qwen2.5-vision' => 'qwen2.5-vision',
        'qwen2.5vl' => 'qwen2.5vl:7b',
        'llama3.2-vision' => 'llama3.2-vision:latest'
    ];
    
    return $modelMap[$model] ?? null;
}
?>

Top
©twily.info 2013 - 2026
twily at twily dot info



3 946 538 visits
... ^ v