File size: 15,355 Bytes
10cde02
71a2c91
10cde02
e2d2e30
 
 
7c9530c
28f5d18
59488ed
7c9530c
 
 
10cde02
db7b744
 
21999ba
 
 
397dfe3
db7b744
10cde02
 
 
36bcbee
7c9530c
 
 
 
 
 
 
10cde02
c1f566c
7c9530c
 
 
 
 
 
 
 
 
 
fa1a863
7c9530c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ab3334d
f23957c
c1f566c
ab3334d
 
10cde02
28f5d18
e2d2e30
0629fcf
 
e2d2e30
 
f97efd9
0629fcf
f97efd9
 
71a2c91
0629fcf
59488ed
 
c1f566c
0629fcf
b40d264
 
 
7c9530c
 
c1f566c
0629fcf
e2d2e30
c1f566c
0629fcf
7c9530c
 
c1f566c
0629fcf
7c9530c
e2d2e30
 
59488ed
 
 
 
 
 
 
7c9530c
1675db5
a94a1dc
 
c1f566c
a94a1dc
fa1a863
 
e67763b
 
 
a94a1dc
e67763b
c1f566c
e67763b
a94a1dc
 
fa1a863
 
 
 
 
 
 
94053ec
 
 
 
 
5bec612
94053ec
 
5bec612
 
94053ec
a94a1dc
5bec612
7c9530c
 
 
5d5d235
a94a1dc
 
7c9530c
e2d2e30
 
7c9530c
 
 
 
0b392f8
7c9530c
 
c1f566c
7c9530c
 
 
 
 
 
 
 
0b392f8
e67763b
0b392f8
 
 
 
 
 
7c9530c
 
 
 
 
852eeec
7c9530c
c1f566c
7c9530c
 
bfb639d
7c9530c
 
 
 
 
 
 
 
 
 
 
 
e2d2e30
c1f566c
e2d2e30
7c9530c
e2d2e30
 
bfb639d
a94a1dc
c1f566c
 
a94a1dc
 
 
c1f566c
bfb639d
a94a1dc
bfb639d
a94a1dc
 
7c9530c
 
c1f566c
 
10cde02
 
db7b744
7c9530c
10cde02
7c9530c
 
 
 
 
 
 
 
c1f566c
fa1a863
7c9530c
 
 
 
 
 
c1f566c
7c9530c
 
 
 
 
 
 
5bec612
7c9530c
 
 
 
 
 
c1f566c
7c9530c
 
 
 
 
c1f566c
b40d264
7c9530c
 
 
21999ba
 
 
 
a94a1dc
59488ed
 
 
a94a1dc
 
59488ed
 
 
c1f566c
59488ed
 
 
71a2c91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21999ba
 
 
 
 
 
 
 
 
 
 
 
 
 
7c9530c
 
 
 
21999ba
 
 
 
7c9530c
c1f566c
7c9530c
 
 
 
 
 
e03c26e
 
 
7c9530c
 
 
 
 
 
 
 
 
 
c1f566c
7c9530c
71a2c91
 
 
e67763b
 
7c9530c
21999ba
 
 
 
 
 
 
 
 
 
4f94b44
 
 
 
397dfe3
4f94b44
 
e2d2e30
db7b744
 
 
 
 
21999ba
db7b744
 
 
21999ba
db7b744
 
 
e8511c9
db7b744
21999ba
 
 
db7b744
 
 
 
 
 
 
 
 
 
 
 
21999ba
db7b744
 
 
 
10cde02
db7b744
 
 
 
 
e2d2e30
db7b744
 
e2d2e30
db7b744
 
 
 
e2d2e30
db7b744
 
 
 
 
e2d2e30
db7b744
 
e2d2e30
db7b744
e2d2e30
db7b744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36bcbee
 
db7b744
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21999ba
 
db7b744
 
 
 
 
 
 
 
 
21999ba
 
db7b744
21999ba
db7b744
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import streamlit as st
from streamlit.delta_generator import DeltaGenerator
import os
import time
import json
import re
from typing import List, Literal, TypedDict, Tuple
from transformers import AutoTokenizer
from gradio_client import Client
from openai import OpenAI
import anthropic
from groq import Groq

import constants as C
import utils as U
from helpers.auth import runWithAuth
from helpers.sidebar import showSidebar
from helpers.activities import saveLatestActivity
from helpers.imageCdn import initCloudinary, getCdnUrl

from dotenv import load_dotenv
load_dotenv()


ModelType = Literal["GPT4", "CLAUDE", "LLAMA"]
ModelConfig = TypedDict("ModelConfig", {
    "client": OpenAI | Groq | anthropic.Anthropic,
    "model": str,
    "max_context": int,
    "tokenizer": AutoTokenizer
})

modelType: ModelType = os.environ.get("MODEL_TYPE") or "CLAUDE"

MODEL_CONFIG: dict[ModelType, ModelConfig] = {
    "GPT4": {
        "client": OpenAI(api_key=os.environ.get("OPENAI_API_KEY")),
        "model": "gpt-4o-mini",
        "max_context": 128000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/gpt-4o")
    },
    "CLAUDE": {
        "client": anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")),
        "model": "claude-3-5-sonnet-20240620",
        "max_context": 128000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/claude-tokenizer")
    },
    "LLAMA": {
        "client": Groq(api_key=os.environ.get("GROQ_API_KEY")),
        "model": "llama-3.1-70b-versatile",
        "max_context": 128000,
        "tokenizer": AutoTokenizer.from_pretrained("Xenova/Meta-Llama-3.1-Tokenizer")
    }
}

client = MODEL_CONFIG[modelType]["client"]
MODEL = MODEL_CONFIG[modelType]["model"]
MAX_CONTEXT = MODEL_CONFIG[modelType]["max_context"]
tokenizer = MODEL_CONFIG[modelType]["tokenizer"]

isClaudeModel = modelType == "CLAUDE"


def __countTokens(text):
    text = str(text)
    tokens = tokenizer.encode(text, add_special_tokens=False)
    return len(tokens)


st.set_page_config(
    page_title="Kommuneity Story Creator",
    page_icon=C.AI_ICON,
    # menu_items={"About": None}
)


def __isInvalidResponse(response: str):
    if len(re.findall(r'\n((?!http)[a-z])', response)) > 3 and "```" not in response:
        U.pprint("new line followed by small case char")
        return True

    if len(re.findall(r'\b(\w+)(\s+\1){2,}\b', response)) > 1:
        U.pprint("lot of consecutive repeating words")
        return True

    if len(re.findall(r'\n\n', response)) > 30:
        U.pprint("lots of paragraphs")
        return True

    if C.EXCEPTION_KEYWORD in response:
        U.pprint("LLM API threw exception")
        if 'roles must alternate between "user" and "assistant"' in str(response):
            U.pprint("Removing last msg from context...")
            st.session_state.messages.pop(-2)
        return True

    if ('{\n    "options"' in response) and (C.JSON_SEPARATOR not in response):
        U.pprint("JSON response without json separator")
        return True
    if ('{\n    "action"' in response) and (C.JSON_SEPARATOR not in response):
        U.pprint("JSON response without json separator")
        return True

    if response.startswith(C.JSON_SEPARATOR):
        U.pprint("only options with no text")
        return True


def __matchingKeywordsCount(keywords: List[str], text: str):
    return sum([
        1 if keyword in text else 0
        for keyword in keywords
    ])


def __getRawImagePromptDetails(prompt: str, response: str) -> Tuple[str, str, str]:
    regex = r'[^a-z0-9 \n\.\-\:\/]|((the) +)'

    cleanedResponse = re.sub(regex, '', response.lower())
    U.pprint(f"{cleanedResponse=}")

    cleanedPrompt = re.sub(regex, '', prompt.lower())

    if (st.session_state.selectedStory):
        imageText = st.session_state.selectedStory

        return (
            f"Extract the story from this text and add few more details about this story:\n{imageText}",
            "Effect: dramatic, bokeh",
            "Painting your story character ...",
        )

    if (
        __matchingKeywordsCount(
            [C.BOOKING_LINK],
            cleanedResponse
        ) > 0
        and "storytelling coach" not in cleanedPrompt
    ):
        aiResponses = [
            chat.get("content")
            for chat in st.session_state.chatHistory
            if chat.get("role") == "assistant"
        ]

        relevantResponse = f"""
        {aiResponses[-1]}
        {response}
        """

        return (
            f"Extract the story from this text:\n{relevantResponse}",
            """
            Style: In a storybook, surreal
            """,
            "Imagining your story scene ...",
        )

    return (None, None, None)


def __getImagePromptDetails(prompt: str, response: str):
    (enhancePrompt, imagePrompt, loaderText) = __getRawImagePromptDetails(prompt, response)

    if imagePrompt or enhancePrompt:
        # U.pprint(f"[Raw] {enhancePrompt=} | {imagePrompt=}")

        promptEnhanceModelType: ModelType = "LLAMA"
        U.pprint(f"{promptEnhanceModelType=}")

        modelConfig = MODEL_CONFIG[promptEnhanceModelType]
        client = modelConfig["client"]
        model = modelConfig["model"]
        isClaudeModel = promptEnhanceModelType == "CLAUDE"

        systemPrompt = "You help in creating prompts for image generation"
        promptPrefix = f"{enhancePrompt}\nAnd then use the above to" if enhancePrompt else "Use the text below to"
        enhancePrompt = f"""
        {promptPrefix} create a prompt for image generation.

        {imagePrompt}

        Return only the final Image Generation Prompt, and nothing else
        """
        U.pprint(f"[Raw] {enhancePrompt=}")

        llmArgs = {
            "model": model,
            "messages": [{
                "role": "user",
                "content": enhancePrompt
            }],
            "temperature": 1,
            "max_tokens": 2000
        }

        if isClaudeModel:
            llmArgs["system"] = systemPrompt
            response = client.messages.create(**llmArgs)
            imagePrompt = response.content[0].text
        else:
            llmArgs["messages"] = [
                {"role": "system", "content": systemPrompt},
                *llmArgs["messages"]
            ]
            response = client.chat.completions.create(**llmArgs)
            responseMessage = response.choices[0].message
            imagePrompt = responseMessage.content

        U.pprint(f"[Enhanced] {imagePrompt=}")

    return (imagePrompt, loaderText)


def __getMessages():
    def getContextSize():
        currContextSize = __countTokens(C.SYSTEM_MSG) + __countTokens(st.session_state.messages) + 100
        U.pprint(f"{currContextSize=}")
        return currContextSize

    while getContextSize() > MAX_CONTEXT:
        U.pprint("Context size exceeded, removing first message")
        st.session_state.messages.pop(0)

    return st.session_state.messages


def __logLlmRequest(messagesFormatted: list):
    contextSize = __countTokens(messagesFormatted)
    U.pprint(f"{contextSize=} | {MODEL}")
    # U.pprint(f"{messagesFormatted=}")


def __predict():
    messagesFormatted = []

    try:
        if isClaudeModel:
            messagesFormatted.extend(__getMessages())
            __logLlmRequest(messagesFormatted)

            with client.messages.stream(
                model=MODEL,
                messages=messagesFormatted,
                system=C.SYSTEM_MSG,
                temperature=0.9,
                max_tokens=4000,
            ) as stream:
                for text in stream.text_stream:
                    yield text
        else:
            messagesFormatted.append(
                {"role": "system", "content": C.SYSTEM_MSG}
            )
            messagesFormatted.extend(__getMessages())
            __logLlmRequest(messagesFormatted)

            response = client.chat.completions.create(
                model=MODEL,
                messages=messagesFormatted,
                temperature=1,
                max_tokens=4000,
                stream=True
            )
            for chunk in response:
                choices = chunk.choices
                if not choices:
                    U.pprint("Empty chunk")
                    continue
                chunkContent = chunk.choices[0].delta.content
                if chunkContent:
                    yield chunkContent
    except Exception as e:
        U.pprint(f"LLM API Error: {e}")
        yield f"{C.EXCEPTION_KEYWORD} | {e}"


def __generateImage(prompt: str):
    fluxClient = Client(
        "black-forest-labs/FLUX.1-schnell",
        os.environ.get("HF_FLUX_CLIENT_TOKEN")
    )
    result = fluxClient.predict(
            prompt=prompt,
            seed=0,
            randomize_seed=True,
            width=1024,
            height=768,
            num_inference_steps=4,
            api_name="/infer"
    )
    U.pprint(f"imageResult={result}")
    return result


def __paintImageIfApplicable(
    imageContainer: DeltaGenerator,
    prompt: str,
    response: str,
):
    imagePath = None
    try:
        (imagePrompt, loaderText) = __getImagePromptDetails(prompt, response)
        if imagePrompt:
            imgContainer = imageContainer.container()
            imgContainer.write(
                f"""
                <div class='blinking code'>
                {loaderText}
                </div>
                """,
                unsafe_allow_html=True
            )
            imgContainer.image(C.IMAGE_LOADER)
            (imagePath, seed) = __generateImage(imagePrompt)
            imageContainer.image(imagePath)
    except Exception as e:
        U.pprint(e)
        imageContainer.empty()

    return imagePath


def __selectButton(optionLabel: str):
    st.session_state["buttonValue"] = optionLabel
    U.pprint(f"Selected: {optionLabel}")


def __showButtons(options: list):
    for option in options:
        st.button(
            option["label"],
            key=option["id"],
            on_click=lambda label=option["label"]: __selectButton(label)
        )


def __resetButtonState():
    st.session_state.buttonValue = ""


def __resetButtons():
    st.session_state.buttons = []


def __resetSelectedStory():
    st.session_state.selectedStory = {}


def __setStartMsg(msg):
    st.session_state.startMsg = msg


if "ipAddress" not in st.session_state:
    st.session_state.ipAddress = st.context.headers.get("x-forwarded-for")

if "chatHistory" not in st.session_state:
    st.session_state.chatHistory = []

if "messages" not in st.session_state:
    st.session_state.messages = []

if "buttonValue" not in st.session_state:
    __resetButtonState()

if "selectedStory" not in st.session_state:
    __resetSelectedStory()

if "selectedStoryTitle" not in st.session_state:
    st.session_state.selectedStoryTitle = ""

if "isStoryChosen" not in st.session_state:
    st.session_state.isStoryChosen = False

if "buttons" not in st.session_state:
    st.session_state.buttons = []

if "activityId" not in st.session_state:
    st.session_state.activityId = None

if "userActivitiesLog" not in st.session_state:
    st.session_state.userActivitiesLog = []


U.pprint("\n")
U.pprint("\n")

U.applyCommonStyles()
initCloudinary()
st.title("Kommuneity Story Creator 🪄")


def mainApp():
    if "startMsg" not in st.session_state:
        __setStartMsg("")
        st.button(C.START_MSG, on_click=lambda: __setStartMsg(C.START_MSG))

    for (i, chat) in enumerate(st.session_state.chatHistory):
        role = chat["role"]
        content = chat["content"]
        imagePath = chat.get("image")
        buttons = chat.get("buttons")
        avatar = C.AI_ICON if role == "assistant" else C.USER_ICON
        with st.chat_message(role, avatar=avatar):
            st.markdown(content)
            if imagePath and U.isValidImageUrl(imagePath):
                st.image(imagePath)
            if buttons:
                __showButtons(buttons)
                chat["buttons"] = []

    # U.pprint(f"{st.session_state.buttonValue=}")
    # U.pprint(f"{st.session_state.selectedStoryTitle=}")
    # U.pprint(f"{st.session_state.startMsg=}")

    if prompt := (
        st.chat_input()
        or st.session_state["buttonValue"]
        or st.session_state["selectedStoryTitle"]
        or st.session_state["startMsg"]
    ):
        __resetButtonState()
        __resetButtons()
        __setStartMsg("")
        if st.session_state["selectedStoryTitle"] != prompt:
            __resetSelectedStory()
        st.session_state.selectedStoryTitle = ""

        with st.chat_message("user", avatar=C.USER_ICON):
            st.markdown(prompt)
        U.pprint(f"{prompt=}")
        st.session_state.chatHistory.append({"role": "user", "content": prompt })
        st.session_state.messages.append({"role": "user", "content": prompt})

        with st.chat_message("assistant", avatar=C.AI_ICON):
            responseContainer = st.empty()

            def __printAndGetResponse():
                response = ""
                responseContainer.image(C.TEXT_LOADER)
                responseGenerator = __predict()

                for chunk in responseGenerator:
                    response += chunk
                    if __isInvalidResponse(response):
                        U.pprint(f"InvalidResponse={response}")
                        return

                    if C.JSON_SEPARATOR not in response:
                        responseContainer.markdown(response)

                return response

            response = __printAndGetResponse()
            while not response:
                U.pprint("Empty response. Retrying..")
                time.sleep(0.7)
                response = __printAndGetResponse()

            U.pprint(f"{response=}")

            rawResponse = response
            responseParts = response.split(C.JSON_SEPARATOR)

            jsonStr = None
            if len(responseParts) > 1:
                [response, jsonStr] = responseParts

            imageContainer = st.empty()
            imagePath = __paintImageIfApplicable(imageContainer, prompt, response)
            if imagePath:
                imagePath = getCdnUrl(imagePath)

            st.session_state.chatHistory.append({
                "role": "assistant",
                "content": response,
                "image": imagePath,
            })
            st.session_state.messages.append({
                "role": "assistant",
                "content": rawResponse,
            })

            if jsonStr:
                try:
                    json.loads(jsonStr)
                    jsonObj = json.loads(jsonStr)
                    options = jsonObj.get("options")
                    action = jsonObj.get("action")

                    if options:
                        __showButtons(options)
                        st.session_state.buttons = options
                    elif action:
                        U.pprint(f"{action=}")
                        if action == "SHOW_STORY_DATABASE":
                            time.sleep(0.5)
                            st.switch_page("pages/popular-stories.py")
                        # st.code(jsonStr, language="json")
                except Exception as e:
                    U.pprint(e)

        saveLatestActivity()


runWithAuth(mainApp)
showSidebar()