Skip to content

Commit

Permalink
v2.20.6
Browse files Browse the repository at this point in the history
  • Loading branch information
Dooy committed Sep 3, 2024
1 parent dc5de6e commit 75f1d4f
Show file tree
Hide file tree
Showing 24 changed files with 640 additions and 180 deletions.
3 changes: 3 additions & 0 deletions changlog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# 功能升级日志

# 计划
# 2.20.6
- 😄 新增: 画图 ideogram 相关模块

# 2.20.5
- 😄 新增: flux 相关模型的dall.e格式
- 🐞 修复:claude-3-5,maxtoken问题 #495
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "chatgpt-web-midjourney-proxy",
"version": "2.20.5",
"version": "2.20.6",
"private": false,
"description": "ChatGPT Web Midjourney Proxy",
"author": "Dooy <[email protected]>",
Expand Down
5 changes: 4 additions & 1 deletion service/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import FormData from 'form-data'
import axios from 'axios';
import AWS from 'aws-sdk';
import { v4 as uuidv4} from 'uuid';
import { viggleProxyFileDo,viggleProxy, lumaProxy, runwayProxy } from './myfun'
import { viggleProxyFileDo,viggleProxy, lumaProxy, runwayProxy, ideoProxy, ideoProxyFileDo } from './myfun'


const app = express()
Expand Down Expand Up @@ -349,6 +349,9 @@ app.use('/pro/viggle' ,authV2, viggleProxy);

app.use('/runway' ,authV2, runwayProxy );

app.use('/ideogram/remix' ,authV2, upload2.single('image_file'), ideoProxyFileDo );
app.use('/ideogram' ,authV2, ideoProxy );




Expand Down
47 changes: 47 additions & 0 deletions service/src/myfun.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,54 @@ export const viggleProxy=proxy(process.env.VIGGLE_SERVER?? API_BASE_URL, {
},

})


export const ideoProxy=proxy(process.env.IDEO_SERVER?? API_BASE_URL, {
https: false, limit: '10mb',
proxyReqPathResolver: function (req) {
return req.originalUrl //req.originalUrl.replace('/sunoapi', '') // 将URL中的 `/openapi` 替换为空字符串
},
proxyReqOptDecorator: function (proxyReqOpts, srcReq) {
if ( process.env.VIGGLE_KEY ) proxyReqOpts.headers['Authorization'] ='Bearer '+process.env.IDEO_KEY;
else proxyReqOpts.headers['Authorization'] ='Bearer '+process.env.OPENAI_API_KEY;
proxyReqOpts.headers['Content-Type'] = 'application/json';
proxyReqOpts.headers['Mj-Version'] = pkg.version;
return proxyReqOpts;
},

})

//req, res, next
export const ideoProxyFileDo=async( req:Request, res:Response, next?:NextFunction)=>{
console.log('req.originalUrl', req.originalUrl );
let API_BASE_URL = isNotEmptyString(process.env.OPENAI_API_BASE_URL)
? process.env.OPENAI_API_BASE_URL
: 'https://api.openai.com'
API_BASE_URL= process.env.IDEO_SERVER?? API_BASE_URL
if(req.file.buffer) {
const fileBuffer = req.file.buffer;
const formData = new FormData();
formData.append('image_file', fileBuffer, { filename: req.file.originalname } );
formData.append('image_request', req.body.image_request );
try{
let url = `${API_BASE_URL}${req.originalUrl}` ;
let responseBody = await axios.post( url , formData, {
headers: {
Authorization: 'Bearer '+ (process.env.IDEO_KEY??process.env.OPENAI_API_KEY) ,
'Content-Type': 'multipart/form-data',
//'Mj-Version': pkg.version
}
}) ;
res.json(responseBody.data );
}catch(e){
res.status( 400 ).json( {error: e } );
}

}else{
res.status(400).json({'error':'uploader fail'});
}

}

export const viggleProxyFileDo= async( req:Request, res:Response, next?:NextFunction)=>{
// if ( process.env.VIGGLE_KEY ) proxyReqOpts.headers['Authorization'] ='Bearer '+process.env.VIGGLE_KEY;
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
},
"package": {
"productName": "ChatGPT-MJ",
"version": "2.20.5"
"version": "2.20.6"
},
"tauri": {
"allowlist": {
Expand Down
139 changes: 139 additions & 0 deletions src/api/ideo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
import { gptServerStore, homeStore, useAuthStore } from "@/store";
import { mlog } from "./mjapi";
import { sleep } from "./suno";


export interface IdeoImageData {
is_image_safe: boolean;
prompt: string;
resolution: string;
seed: number;
url: string;
}
function getHeaderAuthorization(){
let headers={}
if( homeStore.myData.vtoken ){
const vtokenh={ 'x-vtoken': homeStore.myData.vtoken ,'x-ctoken': homeStore.myData.ctoken};
headers= {...headers, ...vtokenh}
}
if(!gptServerStore.myData.IDEO_KEY){
const authStore = useAuthStore()
if( authStore.token ) {
const bmi= { 'x-ptoken': authStore.token };
headers= {...headers, ...bmi }
return headers;
}
return headers
}
const bmi={
'Authorization': 'Bearer ' +gptServerStore.myData.IDEO_KEY
}
headers= {...headers, ...bmi }
return headers
}

export const getUrl=(url:string)=>{
if(url.indexOf('http')==0) return url;

const pro_prefix= '';//homeStore.myData.is_luma_pro?'/pro':''
url= url.replaceAll('/pro','')
if(gptServerStore.myData.IDEO_SERVER){

return `${ gptServerStore.myData.IDEO_SERVER}${pro_prefix}/ideogram${url}`;
}
return `${pro_prefix}/ideogram${url}`;
}


export const ideoSubmit= async( data:any ):Promise<IdeoImageData[]>=>{
let rz:IdeoImageData[]
let rzdata:any={image_request:data.image_request}
if(data.file) {
//mlog('文件上传', data.file );
const formData = new FormData();
formData.append('image_file', data.file )
formData.append('image_request', JSON.stringify(data.image_request) )

let d:any = await ideoFetch( '/remix', formData,{upFile:true})
//mlog(' 文件上传 back', d );
rz= d.data as IdeoImageData[]
}else{
let d:any = await ideoFetch('/generate ' ,rzdata )
//mlog('back', d );
rz= d.data as IdeoImageData[]
}
return rz;

}
export const ideoFetch=(url:string,data?:any,opt2?:any )=>{
mlog('ideoFetch', url );
let headers= opt2?.upFile?{}: {'Content-Type':'application/json'}

if(opt2 && opt2.headers ) headers= opt2.headers;

headers={...headers,...getHeaderAuthorization()}

return new Promise<any>((resolve, reject) => {
let opt:RequestInit ={method:'GET'};

opt.headers= headers ;
if(opt2?.upFile ){
opt.method='POST';
opt.body=data as FormData ;
}
else if(data) {
opt.body= JSON.stringify(data) ;
opt.method='POST';
}
fetch(getUrl(url), opt )
.then( async (d) =>{
if (!d.ok) {
let msg = '发生错误: '+ d.status
try{
let bjson:any = await d.json();
msg = '('+ d.status+')发生错误: '+(bjson?.error?.message??'' )
}catch( e ){
}
homeStore.myData.ms && homeStore.myData.ms.error(msg )
throw new Error( msg );
}

d.json().then(d=> resolve(d)).catch(e=>{

homeStore.myData.ms && homeStore.myData.ms.error('发生错误'+ e )
reject(e)
}
)})
.catch(e=>{
if (e.name === 'TypeError' && e.message === 'Failed to fetch') {
homeStore.myData.ms && homeStore.myData.ms.error('跨域|CORS error' )
}
else homeStore.myData.ms && homeStore.myData.ms.error('发生错误:'+e )
mlog('e', e.stat )
reject(e)
})
})

}

// export async function FeedViggleTask(id:string){
// const ss = new viggleStore()
// const hk= new lumaHkStore();
// const hkObj= hk.getOneById(id)
// for(let i=0; i<500;i++){
// let url= '/video-task/by-ids';
// if(hkObj && hkObj.isHK ) url= '/pro/video-task/by-ids';
// const d= await viggleFetch(url,{ids:[id]})
// mlog('FeedViggleTask', d )

// if(d.data && d.data.length>0){
// let task= d.data[0] as ViggleTask;
// task.last_feed=new Date().getTime()
// ss.save( task )
// homeStore.setMyData({act:'FeedViggleTask'})
// if ( d.data[0].status==0) return
// }
// await sleep(2000)
// }

// }
1 change: 1 addition & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,5 @@ export * from "./chat"
export * from "./sse/fetchsse"
export * from "./Recognition"
export * from "./luma"
export * from "./ideo"

32 changes: 30 additions & 2 deletions src/api/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import { t } from "@/locales";
import { ChatMessage } from "gpt-tokenizer/esm/GptEncoding";
import { chatSetting } from "./chat";
import { MessageApiInjection } from "naive-ui/es/message/src/MessageProvider";
import { ideoSubmit } from "./ideo";
import { error } from "console";
//import {encode, encodeChat} from "gpt-tokenizer"
//import {encode, encodeChat} from "gpt-tokenizer/cjs/encoding/cl100k_base.js";
//import { get_encoding } from '@dqbd/tiktoken'
Expand Down Expand Up @@ -214,8 +216,26 @@ export const subGPT= async (data:any, chat:Chat.Chat )=>{
let d:any;
let action= data.action;
//chat.myid= `${Date.now()}`;
if( action=='gpt.dall-e-3' ){ //执行变化
if( action=='gpt.dall-e-3' && data.data && data.data.model && data.data.model =='ideogram'){ //ideogram
mlog("ddlog 数据 ", data.data )
try{
let d= await ideoSubmit(data.data );
mlog("ddlog 数据返回 ", d )
const rz = d[0];
chat.text= rz.prompt//rz.p??`图片已完成`;
chat.opt={imageUrl:rz.url } ;
chat.loading = false;
homeStore.setMyData({act:'updateChat', actData:chat });

}catch(e){
//chat.text='失败!'+"\n```json\n"+JSON.stringify(d, null, 2)+"\n```\n";
chat.text='失败!'+"\n```json\n"+ e +"\n```\n";
chat.loading=false;
homeStore.setMyData({act:'updateChat', actData:chat });
}
}else if( action=='gpt.dall-e-3' ){ //执行变化
// chat.model= 'dall-e-3';


let d= await gptFetch('/v1/images/generations', data.data);
try{
Expand All @@ -225,7 +245,8 @@ export const subGPT= async (data:any, chat:Chat.Chat )=>{
chat.loading = false;
homeStore.setMyData({act:'updateChat', actData:chat });
}catch(e){
chat.text='失败!'+"\n```json\n"+JSON.stringify(d, null, 2)+"\n```\n";
//chat.text='失败!'+"\n```json\n"+JSON.stringify(d, null, 2)+"\n```\n";
chat.text='失败!'+"\n```json\n"+ (d?JSON.stringify(d, null, 2):e) +"\n```\n";
chat.loading=false;
homeStore.setMyData({act:'updateChat', actData:chat });
}
Expand All @@ -234,6 +255,13 @@ export const subGPT= async (data:any, chat:Chat.Chat )=>{

}

export const isDallImageModel =(model:string|undefined)=>{
if(!model) return false;
if( model.indexOf('flux')>-1 ) return true;
return ['dall-e-2' ,'dall-e-3','ideogram' ].indexOf(model)>-1

}

interface subModelType{
message:any[]
onMessage:(d:{text:string,isFinish:boolean})=>void
Expand Down
8 changes: 7 additions & 1 deletion src/locales/en-US.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,13 @@ export default {

,subtle: 'High definition 2x'
,creative: 'High definition 2x. Creative'
,gpt_gx: 'GPTs use g-*'
,gpt_gx: 'GPTs use g-*',

"ideoabout": "About Ideogram",
"ideoserver": "Ideogram Server",
"ideokeyPlaceholder": "API Key for Ideogram (optional)",
"ideopls": "Image description prompts",
"nohead": "Excludes"

},
"mjset": {
Expand Down
8 changes: 7 additions & 1 deletion src/locales/fr-FR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,13 @@ export default {

subtle: 'Haute définition 2x'
,creative: 'Haute définition 2x. Créatif'
,gpt_gx: 'Les GPT utilisent g-*'
,gpt_gx: 'Les GPT utilisent g-*',

"ideoabout": "À propos d'Ideogram",
"ideoserver": "Serveur Ideogram",
"ideokeyPlaceholder": "Clé API pour Ideogram (optionnelle)",
"ideopls": "Invites de description d'image",
"nohead": "Exclut"

},
"mjset": {
Expand Down
8 changes: 7 additions & 1 deletion src/locales/ko-KR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,13 @@ export default {

subtle: '고화질 2배'
,creative: '고화질 2배. 창의적'
,gpt_gx: 'GPTs는 g-*를 사용합니다'
,gpt_gx: 'GPTs는 g-*를 사용합니다',

"ideoabout": "아이디어그램에 대하여",
"ideoserver": "아이디어그램 서버",
"ideokeyPlaceholder": "아이디어그램의 API 키 (선택 사항)",
"ideopls": "이미지 설명 프롬프트",
"nohead": "포함하지 않음"

},
"mjset": {
Expand Down
10 changes: 9 additions & 1 deletion src/locales/ru-RU.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,15 @@ export default {
"micRecEnd": "Запись завершена",
subtle: 'Высокое разрешение 2x'
,creative: 'Высокое разрешение 2x. Творческий'
,gpt_gx: 'GPT использует g-*'
,gpt_gx: 'GPT использует g-*',


"ideoabout": "О Идеограмме",
"ideoserver": "Сервер Идеограммы",
"ideokeyPlaceholder": "API-ключ для Идеограммы (необязательно)",
"ideopls": "Подсказки для описания изображения",
"nohead": "Не включает"


},
"mjset": {
Expand Down
8 changes: 7 additions & 1 deletion src/locales/tr-TR.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,13 @@ export default {

subtle: 'Haute définition 2x'
,creative: 'Haute définition 2x. Créatif'
,gpt_gx: 'Les GPT utilisent g-*'
,gpt_gx: 'Les GPT utilisent g-*',

"ideoabout": "Ideogram Hakkında",
"ideoserver": "Ideogram Sunucusu",
"ideokeyPlaceholder": "Ideogram için API Anahtarı (isteğe bağlı)",
"ideopls": "Görüntü açıklama ipuçları",
"nohead": "Dahil değil"
},
"mjset": {
"server": "Sunucu",
Expand Down
Loading

0 comments on commit 75f1d4f

Please sign in to comment.