Skip to content

Commit

Permalink
Initial working adventure mode.
Browse files Browse the repository at this point in the history
  • Loading branch information
Vali-98 committed Nov 5, 2023
1 parent f68bfe0 commit d6f6f49
Show file tree
Hide file tree
Showing 6 changed files with 211 additions and 25 deletions.
22 changes: 22 additions & 0 deletions app/CharInfo.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,23 @@ const CharInfo = () => {
numberOfLines={8}
/>
</ScrollView>

<Text style={styles.boxText}>Adventure Options</Text>
<Text style={styles.boxTextGray}>eg. option1 || option2 || option3</Text>
<ScrollView style={styles.inputContainer}>
<TextInput
style={styles.input}
multiline
onChangeText={(mes) => {
if(characterCard.spec !== undefined && characterCard.spec === 'chara_card_v2')
setCharacterCard({...characterCard, adventure_options: mes, data: {...characterCard.data, adventure_options: mes} })
else
setCharacterCard({...characterCard, adventure_options: mes })
}}
value={characterCard?.data?.adventure_options ?? characterCard?.adventure_options}
numberOfLines={8}
/>
</ScrollView>
</ScrollView>
</SafeAreaView>
)
Expand Down Expand Up @@ -199,6 +216,11 @@ const styles = StyleSheet.create({
paddingBottom: 8,
},

boxTextGray:{
color:Color.Offwhite,
paddingBottom: 8,
},

input: {
color: Color.Text,
textAlignVertical: 'top',
Expand Down
25 changes: 23 additions & 2 deletions app/Settings.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { SafeAreaView, View, Text, Image, StyleSheet } from 'react-native'
import { Global, Color, API, getUserImageDirectory } from '@globals'
import React from 'react'
import { useMMKVString } from 'react-native-mmkv'
import { TouchableOpacity } from 'react-native-gesture-handler'
import { useMMKVBoolean, useMMKVString } from 'react-native-mmkv'
import { Switch, TouchableOpacity } from 'react-native-gesture-handler'
import { FontAwesome } from '@expo/vector-icons'
import { useRouter } from 'expo-router'

const Settings = () => {
const [userName, setUserName] = useMMKVString(Global.CurrentUser)
const [apiType, setAPIType] = useMMKVString(Global.APIType)
const [adventureMode, setAdventureMode] = useMMKVBoolean(Global.AdventureEnabled)
const router = useRouter()

return (
Expand Down Expand Up @@ -48,6 +49,19 @@ const Settings = () => {
</TouchableOpacity>
</View>


{ (apiType === API.KAI) && (
<View style={styles.switchContainer}>
<Switch style={styles.largeButton}
value={adventureMode}
onValueChange={setAdventureMode}
thumbColor={adventureMode ? Color.White : Color.Offwhite}
trackColor={{false: Color.DarkContainer, true: Color.Offwhite}}
/>
<Text style={{color:adventureMode ? Color.Text : Color.Offwhite, fontSize: 18, marginLeft: 12}}>Adventure Mode</Text>
</View>
)}


</SafeAreaView>
)
Expand Down Expand Up @@ -123,4 +137,11 @@ const styles = StyleSheet.create({
borderColor: Color.Offwhite,
},

switchContainer : {
marginTop: 20,
alignItems: 'center',
flexDirection: 'row',
marginHorizontal: 16,
}

})
98 changes: 91 additions & 7 deletions app/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import {
View, Text, TextInput,
SafeAreaView, TouchableOpacity,
StyleSheet
StyleSheet,
ToastAndroid,
ActivityIndicator
} from 'react-native'
import { useState, useEffect} from 'react'
import {ChatWindow }from '@components/ChatMenu/ChatWindow/ChatWindow'
Expand All @@ -23,12 +25,17 @@ const Home = () => {
const [nowGenerating, setNowGenerating] = useMMKVBoolean(Global.NowGenerating)
// Instruct
const [currentInstruct, setCurrentInstruct] = useMMKVObject(Global.CurrentInstruct)

// api / adventure
const [apiType, setApiType] = useMMKVString(Global.APIType)
const [adventureMode, setAdventureMode] = useMMKVBoolean(Global.AdventureEnabled)
// Local
const [messages, setMessages] = useState([]);
const [newMessage, setNewMessage] = useState('');
const [targetLength, setTargetLength] = useState(0)
const [abortFunction, setAbortFunction] = useState(undefined)


// load character chat upon character change
useEffect(() => {
if (charName === 'Welcome' || charName === undefined) return
Expand All @@ -42,6 +49,10 @@ const Home = () => {

}, [charName])

useEffect(() => {
//setAdventureMode(false)
}, [apiType])

// triggers generation when set true
// TODO : Use this to save instead
useEffect(() => {
Expand All @@ -68,7 +79,7 @@ const Home = () => {
generateResponse(setAbortFunction, insertGeneratedMessage, messages)
}

const handleSend = () => {
const handleSend = (newMessage) => {
if (newMessage.trim() !== ''){
const newMessageItem = createChatEntry(userName, true, newMessage)
setMessages(messages => [...messages, newMessageItem])
Expand All @@ -78,18 +89,32 @@ const Home = () => {
setNowGenerating(true)
}

const insertGeneratedMessage = (data) => {
const insertGeneratedMessage = (input_data) => {
let data = ""
let adventure_data = ""
if(adventureMode) {
const filtered = input_data.split("```")
data = filtered[0]
if(filtered.length > 1)
adventure_data = filtered[1].split('\n').filter(item => {return item.startsWith(`[`)}).map(text => {return text.split(`] `)[1]}).join('||')
}
else data = input_data

setMessages(messages => {
try {
const createnew = (messages.length < targetLength)
const mescontent = ((createnew ) ? data : messages.at(-1).mes + data)
.replaceAll(currentInstruct.input_sequence, ``)
.replaceAll(currentInstruct.output_sequence, ``)
const newmessage = (createnew) ? createChatEntry(charName, false, "") : messages.at(-1)
newmessage.mes = mescontent
let newmessage = {
...((createnew) ? createChatEntry(charName, false, "") : messages.at(-1)),
mes : mescontent,
gen_finished:Date() ,
adventure_options : adventure_data
}
newmessage.swipes[newmessage.swipe_id] = mescontent
newmessage.gen_finished = Date()
newmessage.swipe_info[newmessage.swipe_id].gen_finished = Date()
newmessage.swipe_info[newmessage.swipe_id].adventure_options = adventure_data
const finalized_messages = createnew ? [...messages , newmessage] : [...messages.slice(0,-1), newmessage]
return finalized_messages
} catch (error) {
Expand All @@ -99,6 +124,16 @@ const Home = () => {
})
}

const getAdventureOptions = () => {
if(messages.length === 0|| messages.at(-1).name !== charName || messages.at(-1)?.adventure_options === undefined) return []
try {
return messages.at(-1)?.adventure_options.split("||") ?? messages.at(-1)?.data?.adventure_options.split("||")
} catch {
ToastAndroid.show(`Something is wrong with Options formatting`, 2000)
return []
}
}

const abortResponse = () => {
console.log(`Aborting Generation`)
if(abortFunction !== undefined)
Expand Down Expand Up @@ -144,6 +179,41 @@ const Home = () => {

<ChatWindow messages={messages} />

{(adventureMode) ?
(nowGenerating ?
<View style={styles.adventureInput}>
<ActivityIndicator size="large" />
</View>
:
(messages.at(-1).name === charName &&
<View style={styles.adventureInput}>
{(messages.at(-1)?.adventure_options !== undefined && messages.at(-1)?.adventure_options !== '') ?
getAdventureOptions().map((text, index) => (
<View key={index}>
<TouchableOpacity style={styles.adventureOptionContainer}
onPress={() => {
setNewMessage(text)
setTargetLength(messages.length + 1)
handleSend(text)
}}
>
<Text style={{color: Color.Text}}>{text}</Text>
</TouchableOpacity>
</View>))
:
<View>
<TouchableOpacity style={styles.adventureOptionContainer}
onPress={() => {
setTargetLength(messages.length)
setNowGenerating(true)
}}
>
<Text style={{color: Color.Text}}>Generate Responses</Text>
</TouchableOpacity>
</View>
}
</View>))
:
<View style={styles.inputContainer}>

<Menu>
Expand Down Expand Up @@ -176,12 +246,13 @@ const Home = () => {
<MaterialIcons name='stop' color={Color.Button} size={30}/>
</TouchableOpacity>
:
<TouchableOpacity style={styles.sendButton} onPress={handleSend}>
<TouchableOpacity style={styles.sendButton} onPress={() => handleSend(newMessage)}>
<MaterialIcons name='send' color={Color.Button} size={30}/>
</TouchableOpacity>
}

</View>
}
</View>
</MessageContext.Provider>
}
Expand Down Expand Up @@ -257,6 +328,19 @@ const styles = StyleSheet.create({
color: Color.Text,
marginLeft: 16,
},

adventureInput: {
marginBottom: 8,
},

adventureOptionContainer: {
marginHorizontal: 16,
marginVertical: 2,
padding: 12,
borderRadius: 16,
backgroundColor: Color.DarkContainer,
justifyContent: 'center',
},
});

export default Home;
Expand Down
3 changes: 2 additions & 1 deletion components/ChatMenu/ChatWindow/ChatItem.js
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ const ChatItem = ({ message, id, scroll}) => {
newmessages.at(id + 1).send_date = messages.at(id + 1).swipe_info.at(swipeid).send_date
newmessages.at(id + 1).gen_started = messages.at(id + 1).swipe_info.at(swipeid).gen_started
newmessages.at(id + 1).gen_finished = messages.at(id + 1).swipe_info.at(swipeid).gen_finished
newmessages.at(id + 1).adventure_options = messages.at(id + 1).swipe_info.at(swipeid).adventure_options

newmessages.at(id + 1).swipe_id = swipeid
saveChatFile(newmessages)
Expand Down Expand Up @@ -220,10 +221,10 @@ const ChatItem = ({ message, id, scroll}) => {
newmessages.at(id + 1).send_date = messages.at(id + 1).swipe_info.at(swipeid).send_date
newmessages.at(id + 1).gen_started = messages.at(id + 1).swipe_info.at(swipeid).gen_started
newmessages.at(id + 1).gen_finished = messages.at(id + 1).swipe_info.at(swipeid).gen_finished
newmessages.at(id + 1).adventure_options = messages.at(id + 1).swipe_info.at(swipeid).adventure_options

newmessages.at(id + 1).swipe_id = swipeid


saveChatFile(newmessages)
return newmessages
})
Expand Down
12 changes: 10 additions & 2 deletions constants/global.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ export const enum Global {
NovelModel='novelmodel', // novelai model

AphroditeKey = 'aphroditekey', // api key for aphrodite, default is `EMPTY`

// ADVENTURE

AdventureEnabled = `adventureEnabled`,
AdventureSettings = 'adventuresettings',
}

export const enum API {
Expand Down Expand Up @@ -393,7 +398,7 @@ const createNewChat = (userName : any, characterName : any, initmessage : any) =
{"name":characterName,"is_user":false,"send_date":humanizedISO8601DateTime(),
"mes":initmessage
.replaceAll(`{{char}}`, mmkv.getString(Global.CurrentCharacter))
.replaceAll(`{{user}}`, mmkv.getString(Global.CurrentUser))
.replaceAll(`{{user}}`, mmkv.getString(Global.CurrentUser))
},
]
}
Expand All @@ -411,7 +416,8 @@ export const createNewDefaultChat = (
{encoding: FS.EncodingType.UTF8})
.then( response => {
let card = JSON.parse(response)
const newmessage = createNewChat(userName, charName, ( card?.data?.first_mes ?? card.first_mes ))
let newmessage : any = createNewChat(userName, charName, ( card?.data?.first_mes ?? card.first_mes ))
newmessage[1].adventure_options = card?.adventure_options ?? card?.data?.adventure_options ?? ""
return FS.writeAsStringAsync(
`${FS.documentDirectory}characters/${charName}/chats/${newmessage[0].create_date}.jsonl`,
newmessage.map((item: any)=> JSON.stringify(item)).join('\u000d\u000a'),
Expand Down Expand Up @@ -510,13 +516,15 @@ export const createChatEntry = (name : string, is_user : string, message : strin
"extra":{"api":api,"model":model},
"swipe_id":0,
"swipes":[message],
"adventure_options" : "",
"swipe_info":[
// metadata
{
"send_date": humanizedISO8601DateTime(),
"extra":{"api":api,"model":model},
"gen_started" : new Date(),
"gen_finished" : new Date(),
"adventure_options" : "",
},
],
}
Expand Down
Loading

0 comments on commit d6f6f49

Please sign in to comment.