123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692 |
- <?php
- //decode by http://www.yunlu99.com/
- namespace app\controller\api;
- use laytp\controller\Api;
- use laytp\library\Random;
- use think\facade\Db;
- use ins\Words;
- use app\service\api\UserServiceFacade;
- use app\service\ChatgptServiceFacade;
- use app\service\api\MiniappServiceFacade;
- use app\service\BillServiceFacade;
- use app\service\ConfServiceFacade;
- use app\service\MemberServiceFacade;
- use app\service\api\YijianServiceFacade;
- use app\service\api\SdapiServiceFacade;
- use app\service\api\InsServiceFacade;
- use app\service\api\ImageCensorServiceFacade;
- use app\service\api\SpeechServiceFacade;
- use openai\OpenAi;
- use laytp\library\UploadDomain;
- use think\facade\Filesystem;
- class Ai extends Api
- {
- protected function _initialize()
- {
- }
- public $noNeedLogin = array("chat", "chat4event", "chat4", "test", "test2", "recognizer", "chatgpt");
- public function chat()
- {
- global $_GPC;
- $modelVipinfo = new \app\model\Vipinfo();
- $loginUserInfo = UserServiceFacade::getUserInfo();
- $modelQuestion = new \app\model\Question();
- $prompt = $this->request->post("prompt", '');
- $guide = $this->request->post("guide", '');
- $answer = $this->request->post("answer", '');
- $platform = $this->request->header("platform", "H5");
- $conf = ConfServiceFacade::groupGet("system.config", 0);
- $type = $this->request->post("type", "gpt35");
- $numberAlias = !empty($conf["number_alias"]) ? $conf["number_alias"] : "点数";
- if (!$prompt) {
- return $this->error("请填写问题");
- }
- $clearPrompt = $this->wordFilter($prompt);
- $proxy = $this->getUrl($type, $conf);
- if ($type == "gpt35") {
- $coin = ConfServiceFacade::get("system.plan.unlock_gpt3", 1);
- } else {
- $coin = ConfServiceFacade::get("system.plan.lock_gpt4", 0);
- }
- $checkMember = MemberServiceFacade::check($loginUserInfo, $type, $coin, $conf);
- if (isset($checkMember["status"]) && !$checkMember["status"]) {
- return $this->error($checkMember["msg"], 2);
- }
- $res = ChatgptServiceFacade::chat($prompt, $guide, $answer, $platform);
- if (!$res) {
- return $this->error("服务器出现未知错误,请稍后重试或联系客服.", 3);
- }
- if ($platform == "wxMiniProgram") {
- $check = MiniappServiceFacade::msgSecCheck($res, $loginUserInfo["openid_miniapp"]);
- if (!$check) {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- } else {
- if ($platform == "wxOfficialAccount" || $platform == "H5") {
- if (!empty($conf) && !empty($conf["is_h5_filter"]) && $conf["is_h5_filter"] == 1) {
- $check = ImageCensorServiceFacade::textCensorUserDefined($res);
- if (!empty($check["conclusion"]) && $check["conclusion"] == "不合规") {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- }
- }
- }
- if ($coin > 0) {
- $checkMember = MemberServiceFacade::cash($loginUserInfo, $type, $coin, $conf);
- if (isset($checkMember["status"]) && !$checkMember["status"]) {
- return $this->error($checkMember["msg"], 2);
- }
- }
- $question = $modelQuestion->save(["type" => $type,"uid" => $loginUserInfo["id"], "question" => $prompt, "answer" => $res, "uniacid" => $_GPC["uniacid"]]);
- return $this->success("操作成功", $res);
- }
- public function chatgpt()
- {
- header("Content-Type: text/event-stream");
- header("Cache-Control: no-cache");
- header("Connection: keep-alive");
- header("X-Accel-Buffering: no");
- global $_GPC;
- $loginUserInfo = UserServiceFacade::getUserInfo();
- $modelVipinfo = new \app\model\Vipinfo();
- $modelQuestion = new \app\model\Question();
- $type = $this->request->post("type", "gpt35");
- $prompt = $this->request->post("prompt", '');
- $guide = $this->request->post("guide", '');
- $guideId = $this->request->post("guide_id", 0);
- $guideType = $this->request->post("guide_type", 0);
- $answer = $this->request->post("answer", '');
- $messages = $this->request->post("messages", []);
- $platform = $this->request->header("platform", "H5");
- $conf = ConfServiceFacade::groupGet("system.config", 0);
- $numberAlias = !empty($conf["number_alias"]) ? $conf["number_alias"] : "点数";
- if ($type == "gpt35") {
- $coin = ConfServiceFacade::get("system.plan.unlock_gpt3", 1);
- } else {
- $coin = ConfServiceFacade::get("system.plan.lock_gpt4", 0);
- }
- $proxy = $this->getUrl($type, $conf);
- $checkMember = MemberServiceFacade::check($loginUserInfo, $type, $coin, $conf);
- if (isset($checkMember["status"]) && !$checkMember["status"]) {
- return $checkMember["msg"];
- }
- $temperature = 0.8;
- $presencePenalty = 0;
- $frequencyPenalty = 0;
- if (isset($conf["temperature"])) {
- $temperature = floatval($conf["temperature"]) ?? 0.8;
- }
- if (isset($conf["presence_penalty"])) {
- $presencePenalty = floatval($conf["presence_penalty"]) ?? 0;
- }
- if (isset($conf["frequency_penalty"])) {
- $frequencyPenalty = floatval($conf["frequency_penalty"]) ?? 0;
- }
- $OPENAI_API_KEY = '';
- $clearPrompt = $this->wordFilter($prompt);
- $headers = ["Accept: application/json", "Content-Type: application/json", "Authorization: Bearer " . $proxy["sk"]];
- $messages = [];
- if (mb_strlen($answer) + mb_strlen($guide) + mb_strlen($prompt) < 4000) {
- if ($answer) {
- $messages[] = ["role" => "assistant", "content" => $answer];
- }
- if ($guide) {
- $messages[] = ["role" => "system", "content" => $guide];
- }
- }
- $messages[] = ["role" => "user", "content" => $prompt];
- $opts = ["model" => $proxy["model"], "messages" => $messages, "temperature" => $temperature, "presence_penalty" => $presencePenalty, "frequency_penalty" => $frequencyPenalty, "stream" => true];
- if ($type == "gpt4") {
- $ins = ConfServiceFacade::groupGet("system.ai");
- $opts["key"] = $ins["ins_api_key"];
- if (!$opts["key"]) {
- return error("后台未正确配置参数");
- }
- $get_post_data = http_build_query($opts);
- $API_URL = "https://api.wike.cc/api/gpt4/set" . "?" . $get_post_data;
-
- } else {
- $API_URL = $proxy["url"];
- }
- $response = '';
- $section = '';
- $callback = function ($ch, $data) use($messages, $loginUserInfo, $modelQuestion, $modelVipinfo, $_GPC, $platform, $conf, $numberAlias, $coin, $clearPrompt, $type, $proxy, $section) {
- global $response, $section;
- $dataLength = strlen($data);
- $complete = @json_decode($data, true);
- if ($type == "gpt4" && isset($complete["code"]) && $complete["code"] != 200) {
- echo $data;
- exit;
- }
- if (isset($complete->error)) {
- file_put_contents(__DIR__ . "/ds.json", json_encode($complete->error));
- file_put_contents(__DIR__ . "/ds2.json", json_encode($proxy));
- echo "服务器出现未知错误,请稍后重试或联系客服。";
- exit;
- } else {
- if (!empty($section)) {
- $data = $section . $data;
- $section = '';
- } else {
- if (substr($data, -1) !== "\n") {
- $section = $data;
- return $dataLength;
- }
- }
- $wordArr = $this->parseData($data);
- foreach ($wordArr as $word) {
- if ($word == "data: [DONE]" || $word == "data: [CONTINUE]") {
- if (empty($response)) {
- goto Vqj1C;
- }
- if ($platform == "wxOfficialAccount" || $platform == "H5") {
- if (!empty($conf) && !empty($conf["is_h5_filter"]) && $conf["is_h5_filter"] == 1) {
- $check = ImageCensorServiceFacade::textCensorUserDefined($response);
- if (!empty($check["conclusion"]) && $check["conclusion"] == "不合规") {
- echo "内容包含敏感信息,不予展示。";
- exit;
- }
- }
- }
- $end = end($messages);
- $clearResponse = $this->wordFilter($response);
- $question = $modelQuestion->save(["type" => $type,"uid" => $loginUserInfo["id"], "question" => $clearPrompt, "answer" => $clearResponse, "uniacid" => $_GPC["uniacid"]]);
- if ($type == "gpt4") {
- $post["answer"] = $clearResponse;
- }
- $checkMember = MemberServiceFacade::cash($loginUserInfo, $type, $coin, $conf);
- if (isset($checkMember["status"]) && !$checkMember["status"]) {
- return $this->error($checkMember["msg"], 2);
- }
- $response = '';
- break;
- }
- $response .= $word;
- echo $word;
- Vqj1C:
- ob_flush();
- flush();
- }
- return $dataLength;
- }
- };
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_URL, $API_URL);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($opts, 320));
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
- curl_exec($ch);
- }
- private function getUrl($type, $conf)
- {
- global $_GPC;
- if ($type == "gpt35") {
- $data = [];
- if (empty($conf["connect_lines"]) || $conf["connect_lines"] == 1) {
- $res = InsServiceFacade::getproxy($type);
- $res2 = json_decode($res, true);
- if (empty($res2) || !empty($res2["code"]) && $res2["code"] == 403 || !empty($res2["code"]) && $res2["code"] == 400) {
- $data["model"] = "gpt-3.5-turbo-0301";
- $data["sk"] = '';
- $data["url"] = "https://proxy3.wike.cc/v1/chat/completions";
- return $data;
- }
- return $res2["data"];
- } else {
- if ($conf["connect_lines"] == 2) {
- $info = \app\model\Sk::order("id desc")->where(["uniacid" => $_GPC["uniacid"], "status" => 1])->limit(1)->select();
- if (!$info) {
- return $this->error("未配置key,或无可用的key");
- }
- $data["model"] = "gpt-3.5-turbo-0301";
- $data["sk"] = $info[0]["sk"];
- $data["url"] = $conf["private_proxy"];
- }
- }
- return $data;
- } elseif ($type == "gpt4") {
- $res = InsServiceFacade::getproxy($type);
- $res2 = json_decode($res, true);
- if (empty($res2) || !empty($res2["code"]) && $res2["code"] == 403 || !empty($res2["code"]) && $res2["code"] == 400) {
- return $this->error("4.0数据获取失败,请稍后再试");
- }
- $res2["data"]["sk"] = InsServiceFacade::decrypt($res2["data"]["sk"], WIKE);
- return $res2["data"];
- }
- }
- public function chat4()
- {
- global $_GPC;
- $post = $this->request->post();
- $prompt = $this->request->post("prompt", '');
- $guide = $this->request->post("guide", '');
- $answer = $this->request->post("answer", '');
- $platform = $this->request->header("platform", "H5");
- $conf = ConfServiceFacade::groupGet("system.config", 0);
- $coin = ConfServiceFacade::get("system.plan.lock_gpt4", 0);
- if (!$prompt) {
- return $this->error("请填写文本");
- }
- $loginUserInfo = UserServiceFacade::getUserInfo();
- $numberAlias = !empty($conf["number_alias"]) ? $conf["number_alias"] : "点数";
- $modelQuestion = new \app\model\Question();
- if (empty($conf["is_gpt4"]) || $conf["is_gpt4"] == 2) {
- return $this->error("后台未启用gpt4.0", 2);
- }
- if ($loginUserInfo["coin"] < $coin) {
- return $this->error($numberAlias . "不足", 2);
- } else {
- \app\model\User::where(["id" => $loginUserInfo["id"]])->dec("coin", $coin)->update();
- BillServiceFacade::record(0, $coin, "chatgpt", "问答消耗" . $numberAlias, $loginUserInfo["id"], $_GPC["uniacid"]);
- }
- $res = InsServiceFacade::gpt4($post);
- $res2 = json_decode($res, true);
- if (empty($res2)) {
- return $this->error("请求错误");
- }
- if (!empty($res2["code"]) && $res2["code"] == 403) {
- return $this->error($res2["msg"]);
- }
- if (!empty($res2["code"]) && $res2["code"] == 400) {
- return $this->error($res2["msg"]);
- }
- if ($platform == "wxMiniProgram") {
- $check = MiniappServiceFacade::msgSecCheck($res2["data"], $loginUserInfo["openid_miniapp"]);
- if (!$check) {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- } else {
- if ($platform == "wxOfficialAccount" || $platform == "H5") {
- if (!empty($conf) && !empty($conf["is_h5_filter"]) && $conf["is_h5_filter"] == 1) {
- $check = ImageCensorServiceFacade::textCensorUserDefined($res2["data"]);
- if (!empty($check["conclusion"]) && $check["conclusion"] == "不合规") {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- }
- }
- }
- $question = $modelQuestion->save(["uid" => $loginUserInfo["id"], "question" => $prompt, "answer" => $res2["data"], "uniacid" => $_GPC["uniacid"]]);
- return $this->success("操作成功", $res2["data"]);
- }
- public function tts()
- {
- global $_GPC;
- $text = $this->request->post("text", '');
- if (!$text) {
- return $this->error("请填写文本");
- }
- $res = SpeechServiceFacade::synthesis2($text);
- if (isset($res->{"error_code"})) {
- return $this->error($res["error_msg"]);
- }
- return $this->success("操作成功", $res);
- }
- public function ttsJob()
- {
- global $_GPC;
- $taskIds = $this->request->param("task_ids", '');
- if (!$taskIds) {
- return $this->error("请上传任务id");
- }
- $res = SpeechServiceFacade::query($taskIds);
- if (isset($res->{"error_code"})) {
- return $this->error($res["error_msg"]);
- }
- return $this->success("操作成功", $res->{"tasks_info"}[0]);
- }
- public function recognizer()
- {
- global $_GPC;
- $platform = $this->request->header("platform", "H5");
- $speech = $this->request->file("speech");
- if ($platform == "wxMiniProgram") {
- $format = "m4a";
- } else {
- $format = "wav";
- }
- $audio = file_get_contents($speech);
- $res = SpeechServiceFacade::asr($audio, $format, "16000");
- if (isset($res["err_no"]) && $res["err_no"] != 0) {
- return $this->error($res["err_msg"]);
- }
- return $this->success("操作成功", $res);
- }
- public function getAddress()
- {
- global $_GPC;
- $data = [];
- $conf = ConfServiceFacade::groupGet("system.config");
- if (empty($conf["connect_lines"]) || $conf["connect_lines"] == 1) {
- $data["sk"] = "sk-wfjrfffffffffffffffhufrhuwdyqgygbwdyft";
- $data["url"] = "https://ok.justduit.com";
- } else {
- if ($conf["connect_lines"] == 2) {
- $info = \app\model\Sk::order("id desc")->where(["uniacid" => $_GPC["uniacid"], "status" => 1])->limit(1)->select();
- if (!$info) {
- return $this->error("未配置key,或无可用的key");
- }
- $data["sk"] = "sk-wfjrfffffffffffffffhufrhuwdyqgygbwdyft";
- $data["url"] = "https://ok.justduit.com";
- }
- }
- return $this->success("操作成功", $data);
- }
- public function painting()
- {
- global $_GPC;
- $modelGallery = new \app\model\Gallery();
- $platform = $this->request->header("platform", "H5");
- $prompt = $this->request->post("prompt", '');
- $negativePrompt = $this->request->post("negative_prompt", '');
- $conf = ConfServiceFacade::groupGet("system.config");
- $coin = ConfServiceFacade::get("system.plan.unlock_aipainting", 0);
- if (!$prompt) {
- return $this->error("请填写文本");
- }
- $res = SdapiServiceFacade::getMj($prompt, $negativePrompt);
- print_r($res);
- return;
- $loginUserInfo = UserServiceFacade::getUserInfo();
- if ($platform == "wxMiniProgram") {
- $check = MiniappServiceFacade::msgSecCheck($prompt, $loginUserInfo["openid_miniapp"]);
- if (!$check) {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- } else {
- if ($platform == "wxOfficialAccount" || $platform == "H5") {
- if (!empty($conf) && !empty($conf["is_h5_filter"]) && $conf["is_h5_filter"] == 1) {
- $check = ImageCensorServiceFacade::textCensorUserDefined($prompt);
- if (!empty($check["conclusion"]) && $check["conclusion"] == "不合规") {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- }
- }
- }
- $numberAlias = !empty($conf["number_alias"]) ? $conf["number_alias"] : "点数";
- if ($coin > 0) {
- if ($loginUserInfo["coin"] < $coin) {
- return $this->error("您的点数不足");
- }
- }
- $res = YijianServiceFacade::put_task($prompt);
- if (!empty($res["status"]) && $res["status"] != 0) {
- return $this->error($res["reason"]);
- }
- if ($coin > 0) {
- \app\model\User::where(["id" => $loginUserInfo["id"]])->dec("coin", $coin)->update();
- }
- if (!empty($res["data"]["Uuid"])) {
- $data["job_id"] = $res["data"]["Uuid"];
- $data["prompt"] = $prompt;
- $data["paid_coin"] = $coin;
- $data["uid"] = $loginUserInfo["id"];
- $data["uniacid"] = $_GPC["uniacid"];
- $modelGallery->save($data);
- BillServiceFacade::record(0, $coin, "chatgpt", "绘画消耗" . $numberAlias, $loginUserInfo["id"], $_GPC["uniacid"]);
- }
- return $this->success("操作成功", $res["data"]);
- }
- public function showTask()
- {
- global $_GPC;
- $uuid = $this->request->param("uuid", '');
- $loginUserInfo = UserServiceFacade::getUserInfo();
- if (!$uuid) {
- return $this->error("请上传uuid");
- }
- $res = YijianServiceFacade::show_task($uuid);
- if (!empty($res["status"]) && $res["status"] != 0) {
- $coin = ConfServiceFacade::get("system.plan.unlock_aipainting", 0);
- if ($coin > 0) {
- \app\model\User::where(["id" => $data["uid"]])->inc("coin", $coin)->update();
- }
- return $this->error($res["reason"]);
- }
- if (empty($res["data"]["ImagePath"])) {
- return $this->success("继续等待", "wait");
- }
- $filePath = $this->_put_file_from_url_content($res["data"]["ImagePath"]);
- $galleryInfo = \app\model\Gallery::where(["job_id" => $uuid])->findOrEmpty();
- if ($galleryInfo && empty($galleryInfo["img"])) {
- $filesModel = new \app\model\Files();
- $fileId = $filesModel->insertGetId(["category_id" => 0, "name" => $uuid . time(), "file_type" => "image", "path" => $filePath["saveName"], "upload_type" => "local", "size" => 1, "create_admin_user_id" => 0, "update_admin_user_id" => 0, "create_time" => date("Y-m-d H:i:s"), "update_time" => date("Y-m-d H:i:s"), "uniacid" => $_GPC["uniacid"], "ext" => "png"]);
- $galleryInfo->save(["img" => $fileId]);
- }
- return $this->success("操作成功", $res["data"]["ImagePath"]);
- }
- public function checkText()
- {
- global $_GPC;
- $loginUserInfo = UserServiceFacade::getUserInfo();
- $prompt = $this->request->param("prompt", '');
- $platform = $this->request->header("platform", "H5");
- $conf = ConfServiceFacade::groupGet("system.config", 0);
- if (!$prompt) {
- return $this->error("请填写问题");
- }
- $str = strstr($prompt, "收割台湾");
- if ($str != false) {
- return $this->error("您的提问涉及敏感信息");
- }
- if ($platform == "wxMiniProgram") {
- $check = MiniappServiceFacade::msgSecCheck($prompt, $loginUserInfo["openid_miniapp"]);
- if (!$check) {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- } else {
- if ($platform == "wxOfficialAccount" || $platform == "H5") {
- if (!empty($conf) && !empty($conf["is_h5_filter"]) && $conf["is_h5_filter"] == 1) {
- $check = ImageCensorServiceFacade::textCensorUserDefined($prompt);
- if (!empty($check["conclusion"]) && $check["conclusion"] == "不合规") {
- if (!empty($check["data"]) && ($check["data"][0]["subType"] == 1 || $check["data"][0]["subType"] == 2 || $check["data"][0]["subType"] == 3 || $check["data"][0]["subType"] == 5)) {
- return $this->error("失败,文字内容安全检测不通过!");
- }
- }
- }
- }
- }
- return $this->success("操作成功");
- }
- public function chat4event()
- {
- header("Content-Type: text/event-stream");
- header("Cache-Control: no-cache");
- header("Connection: keep-alive");
- header("X-Accel-Buffering: no");
- $OPENAI_API_KEY = "sk-";
- $headers = ["Accept: application/json", "Content-Type: application/json", "Authorization: Bearer " . $OPENAI_API_KEY];
- $prompt = $this->request->post("prompt", "写一篇文章");
- $messages = [["role" => "user", "content" => $prompt]];
- $opts = ["model" => "gpt-4", "messages" => $messages, "temperature" => 1.0, "max_tokens" => 2000, "frequency_penalty" => 0, "presence_penalty" => 0.6, "stream" => true];
- $callback = function ($ch, $data) {
- $complete = json_decode($data);
- if (isset($complete->error)) {
- print_r($complete->error);
- } else {
- $word = $this->parseData($data);
- if ($word == "data: [DONE]" || $word == "data: [CONTINUE]") {
- ob_flush();
- flush();
- } else {
- echo $word;
- ob_flush();
- flush();
- }
- }
- return strlen($data);
- };
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_URL, "https://proxy4.iduomi.cc/v1/chat/completions");
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($opts));
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callback);
- curl_exec($ch);
- }
- public function wordFilter($message)
- {
- $Filter = new \ins\Words("*");
- $clearMessage = $Filter->filter($message);
- return $clearMessage;
- }
- private function parseData($content)
- {
- $content = trim($content);
- $rows = explode("\n", $content);
- $result = [];
- foreach ($rows as $data) {
- if (strpos($data, "data: [DONE]") !== false) {
- $char = "data: [DONE]";
- } else {
- $data = str_replace("data: {", "{", $data);
- $data = rtrim($data, "\n\n");
- if (strpos($data, "}\n\n{") !== false) {
- $arr = explode("}\n\n{", $data);
- $data = "{" . $arr[1];
- }
- $data = @json_decode($data, true);
- if (!is_array($data)) {
- continue;
- }
- if ($data["choices"]["0"]["finish_reason"] == "stop") {
- $char = "data: [DONE]";
- } elseif ($data["choices"]["0"]["finish_reason"] == "length") {
- $char = "data: [CONTINUE]";
- } else {
- $char = $data["choices"]["0"]["delta"]["content"] ?? '';
- }
- }
- $result[] = $char;
- }
- return $result;
- }
- public function test()
- {
- header("Content-Type: text/event-stream");
- header("Cache-Control: no-cache");
- header("Connection: keep-alive");
- header("X-Accel-Buffering: no");
- global $_GPC;
- $ins = ConfServiceFacade::groupGet("system.ai");
- $API_URL = "https://api.wike.cc/api/senseai/chatgpt4";
- $data["key"] = $ins["ins_api_key"];
- $get_post_data = http_build_query($data);
- $callbacks = function ($ch, $data) use($_GPC) {
- $complete = @json_decode($data, true);
- echo $data;
- ob_flush();
- flush();
- return strlen($data);
- };
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_URL, $API_URL . "?" . $get_post_data);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
- curl_setopt($ch, CURLOPT_WRITEFUNCTION, $callbacks);
- curl_exec($ch);
- }
- public static function send($API_URL, $get_post_data, $type, $ifsign, $sk)
- {
- $get_post_data = http_build_query($get_post_data);
- if ($ifsign) {
- $sign = md5($get_post_data . $sk);
- $res = self::send_curl($API_URL, $type, $get_post_data, $sign);
- } else {
- $res = self::send_curl($API_URL, $type, $get_post_data, null);
- }
- return $res;
- }
- public static function send_curl($API_URL, $type, $get_post_data, $sign)
- {
- $ch = curl_init();
- if ($type == "POST") {
- curl_setopt($ch, CURLOPT_URL, $API_URL);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $get_post_data);
- } elseif ($type == "GET") {
- curl_setopt($ch, CURLOPT_URL, $API_URL . "?" . $get_post_data);
- }
- if ($sign) {
- curl_setopt($ch, CURLOPT_HTTPHEADER, ["sign:" . $sign]);
- }
- curl_setopt($ch, CURLOPT_REFERER, $API_URL);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- $resdata = curl_exec($ch);
- curl_close($ch);
- return $resdata;
- }
- protected function uploadImage($file, $post = array())
- {
- if (empty($post["upload_type"])) {
- $uploadType = "local";
- } else {
- $uploadType = $post["upload_type"];
- }
- if (!in_array($uploadType, ["local", "ali-oss", "qiniu-kodo"])) {
- return $this->error($uploadType . "上传方式未定义");
- }
- $fileExt = strtolower($file->getOriginalExtension());
- $uploadDomain = new UploadDomain();
- if (!$uploadDomain->check($file->getOriginalName(), $file->getSize(), $fileExt, $file->getMime())) {
- }
- $saveName = date("Ymd") . "/" . md5(uniqid(mt_rand())) . ".{$fileExt}";
- $uploadDir = $this->request->post("dir");
- $object = $uploadDir ? $uploadDir . "/" . $saveName : $saveName;
- $data = [];
- $filePath = $object;
- $uploadDir = ltrim("/", $uploadDir);
- $saveName = Filesystem::putFileAs("/" . $uploadDir, $file, "/" . $object);
- $filePath = $saveName;
- $data["image"] = request()->domain() . STATIC_PATH . "/storage/" . $saveName;
- $data["name"] = $saveName;
- return $data;
- }
- private function _put_file_from_url_content($url)
- {
- $name = md5(uniqid(mt_rand())) . ".png";
- $saveName = date("Ymd") . "/" . $name;
- $path = IA_ROOT_WK . "/public/static/storage/";
- set_time_limit(0);
- $url = trim($url);
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_HEADER, 0);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- $file = curl_exec($curl);
- curl_close($curl);
- $filename = $path . $saveName;
- if (!file_exists($path . date("Ymd"))) {
- mkdir($path . date("Ymd"), 0755, true);
- }
- $write = @fopen($filename, "w");
- if ($write == false) {
- return false;
- }
- if (fwrite($write, $file) == false) {
- return false;
- }
- if (fclose($write) == false) {
- return false;
- }
- $data["filename"] = $filename;
- $data["url"] = request()->domain() . STATIC_PATH . "/storage/" . $saveName;
- $data["saveName"] = $saveName;
- $data["name"] = $name;
- return $data;
- }
- }
|