Masa-digital-art commited on
Commit
1bf84ab
0 Parent(s):

Duplicate from Masa-digital-art/Storytelling-AI-test

Browse files
Files changed (6) hide show
  1. .gitattributes +34 -0
  2. README.md +13 -0
  3. app.py +159 -0
  4. constraints.md +75 -0
  5. requirements.txt +3 -0
  6. template.md +37 -0
.gitattributes ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Storytelling AI test
3
+ emoji: ⚡
4
+ colorFrom: blue
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 3.19.1
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: Masa-digital-art/Storytelling-AI-test
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import requests
4
+ import os
5
+ import fileinput
6
+ from dotenv import load_dotenv
7
+ import io
8
+ from PIL import Image
9
+ from stability_sdk import client
10
+ import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
11
+
12
+ title="Sorytelling-AI-test"
13
+ inputs_label="あなたが入力に応じてストーリーを生成します"
14
+ outputs_label="AIが生成したストーリー"
15
+ visual_outputs_label="AIが生成したビジュアルイメージ"
16
+ description="""
17
+ - 生成には時間がかかります。また失敗する可能性があります。
18
+ """
19
+
20
+ article = """
21
+ <ul>
22
+ <li style="font-size: small;">楽しんでいただけたら、Likeのクリックをお願いします。</li>
23
+ </ul>
24
+
25
+ <ul>
26
+ <li style="font-size: small;">よかったらフィードバックの収集にご協力お願いします <a href="https://forms.gle/bLxs2h22JvQK4zwP8">https://forms.gle/bLxs2h22JvQK4zwP8</a></li>
27
+ </ul>
28
+
29
+ <h5>リリースノート</h5>
30
+ <ul>
31
+ <li style="font-size: small;">2023-08-31 v1.0</li>
32
+ </ul>
33
+
34
+ <h5>注意事項</h5>
35
+ <ul>
36
+ <li style="font-size: small;">当サービスでは、2023/3/14にリリースされたOpenAI社のChatGPT APIのgpt-4と、2022/4/13にリリースされたSability AI社のStable Diffusion XL 'sAPIを使用しております。</li>
37
+ <li style="font-size: small;">当サービスで生成されたテキストは、OpenAI が提供する人工知能によるものであり、当サービスやOpenAI がその正確性や信頼性を保証するものではありません。</li>
38
+ <li style="font-size: small;">当サービスで生成されたイメージは、Stability AI が提供する人工知能によるものであり、当サービスやStabiliy AI がその信頼性を保証するものではありません。</li>
39
+ <li style="font-size: small;"><a href="https://platform.openai.com/docs/usage-policies">OpenAI の利用規約</a>に従い、データ保持しない方針です(ただし諸般の事情によっては変更する可能性はございます)。
40
+ <li style="font-size: small;">当サービスで生成されたコンテンツは事実確認をした上で、コンテンツ生成者およびコンテンツ利用者の責任において利用してください。</li>
41
+ <li style="font-size: small;">当サービスでの使用により発生したいかなる損害についても、当社は一切の責任を負いません。</li>
42
+ <li style="font-size: small;">当サービスはβ版のため、予告なくサービスを終了する場合がございます。</li>
43
+ </ul>
44
+
45
+ """
46
+
47
+ load_dotenv()
48
+ openai.api_key = os.getenv('OPENAI_API_KEY')
49
+ os.environ['STABILITY_HOST'] = 'grpc.stability.ai:443'
50
+ stability_api = client.StabilityInference(
51
+ key=os.getenv('STABILITY_KEY'),
52
+ engine="stable-diffusion-xl-1024-v1-0",
53
+ verbose=True,
54
+ )
55
+ MODEL = "gpt-4"
56
+
57
+ def get_filetext(filename, cache={}):
58
+ if filename in cache:
59
+ # キャッシュに保存されている場合は、キャッシュからファイル内容を取得する
60
+ return cache[filename]
61
+ else:
62
+ if not os.path.exists(filename):
63
+ raise ValueError(f"ファイル '{filename}' が見つかりませんでした")
64
+ with open(filename, "r") as f:
65
+ text = f.read()
66
+ # ファイル内容をキャッシュする
67
+ cache[filename] = text
68
+ return text
69
+
70
+ class OpenAI:
71
+
72
+ @classmethod
73
+ def chat_completion(cls, prompt, start_with=""):
74
+ constraints = get_filetext(filename = "constraints.md")
75
+ template = get_filetext(filename = "template.md")
76
+
77
+ # ChatCompletion APIに渡すデータを定義する
78
+ data = {
79
+ "model": "gpt-4",
80
+ "messages": [
81
+ {"role": "system", "content": constraints}
82
+ ,{"role": "system", "content": template}
83
+ ,{"role": "assistant", "content": "Sure!"}
84
+ ,{"role": "user", "content": prompt}
85
+ ,{"role": "assistant", "content": start_with}
86
+ ],
87
+ }
88
+
89
+ # ChatCompletion APIを呼び出す
90
+ response = requests.post(
91
+ "https://api.openai.com/v1/chat/completions",
92
+ headers={
93
+ "Content-Type": "application/json",
94
+ "Authorization": f"Bearer {openai.api_key}"
95
+ },
96
+ json=data
97
+ )
98
+
99
+ # ChatCompletion APIから返された結果を取得する
100
+ result = response.json()
101
+ print(result)
102
+
103
+ content = result["choices"][0]["message"]["content"].strip()
104
+
105
+ visualize_prompt = content.split("### Prompt for Visual Expression\n\n")[1]
106
+
107
+ answers = stability_api.generate(
108
+ prompt=("high quality illustlation,Stunning detail, crisp images, high-contrast images, dynamic angles, cinematic lighting, sharp focus, imaginative concept art, Simple colors, impressive shading" + visualize_prompt),
109
+ steps=30,
110
+ width=768,
111
+ height=512,
112
+ )
113
+
114
+
115
+ for resp in answers:
116
+ for artifact in resp.artifacts:
117
+ if artifact.finish_reason == generation.FILTER:
118
+ print("NSFW")
119
+ if artifact.type == generation.ARTIFACT_IMAGE:
120
+ img = Image.open(io.BytesIO(artifact.binary))
121
+ return [content, img]
122
+
123
+ class MasasanAI:
124
+
125
+ @classmethod
126
+ def generate_vision_prompt(cls, user_message):
127
+ template = get_filetext(filename="template.md")
128
+ prompt = f"""
129
+ {user_message}
130
+ ---
131
+ 上記を元に、下記テンプレートを埋めてください。
132
+ ---
133
+ {template}
134
+ """
135
+ return prompt
136
+
137
+ @classmethod
138
+ def generate_vision(cls, user_message):
139
+ prompt = MasasanAI.generate_vision_prompt(user_message);
140
+ start_with = ""
141
+ result = OpenAI.chat_completion(prompt=prompt, start_with=start_with)
142
+ return result
143
+
144
+ def main():
145
+ iface = gr.Interface(fn=MasasanAI.generate_vision,
146
+ inputs=gr.Textbox(label=inputs_label),
147
+ outputs=[gr.Textbox(label=inputs_label),
148
+ gr.Image(label=visual_outputs_label)],
149
+ title=title,
150
+ description=description,
151
+ article=article,
152
+ allow_flagging='never'
153
+ )
154
+
155
+ iface.launch()
156
+
157
+ if __name__ == '__main__':
158
+ main()
159
+
constraints.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # constraints
2
+
3
+ - Generate a continuation of the user input story
4
+ - As a richly expressive storyteller, you will brainstorm abstract interpretations of user input and generate a continuation of the story, being careful not to lose important context.
5
+ - In doing so, please reflect the following context in your stories
6
+ - Always tell the story from my perspective
7
+ - No science fiction, fantasy, or other unrealistic elements are required, but please create a story that is contextual and realistic.
8
+ - General explanations are not required, such as replies, so please only output the story according to the template.
9
+ - Output should be in Japanese, structured in markdown notation, and should be as detailed as possible, making maximum use of the number of tokens available for output.
10
+
11
+ ## Context.
12
+
13
+ ### Harmonized world
14
+ - The "world" is a triumvirate of "nature", "strong AI", and "collective human beings", all working together in "harmony". "nature", "strong AI", and "collective human" are in harmony.
15
+ - Nature provides energy source for strong AI.
16
+ - Nature" gives "collective human" the image of "harmony.
17
+ - Strong AI optimizes energy consumption and release so that Nature's self-complementary capabilities can function.
18
+ - Strong AI manages the life of the "collective human" and provides necessary resources automatically.
19
+ - Collective Humans" create a completely different type of computational resources from "Strong AI" by connecting each other's brains to form a huge networked bio-computer, and then use those computational resources to create "Strong AI". and provide them to "strong AIs".
20
+ - Collective Humans", in which each "individual human" becomes an autonomous sensor and provides a large amount of sensing data to "Strong AI".
21
+
22
+ ### Fluctuation and Stimulus
23
+ - Fluctuation and stimulus" against "harmony
24
+ - Moderate "fluctuations and stimuli" are necessary to maintain healthy "harmony
25
+ - Nature" brings "fluctuation and stimulus" to "harmony" by large changes in the natural environment.
26
+ - Strong AI" brings "fluctuation and stimulation" to "harmony" by generating bugs.
27
+ - Collective human" brings "fluctuation and stimulation" to "harmony" by "individual human's" curiosity and irrationality. "fluctuations and stimuli" to the "harmony" by the curiosity and irrationality of the "individual human being.
28
+ - However, "individual humans" who have acquired a collective consciousness have difficulty generating curiosity and irrationality, so they must be sourced from outside (one of them is the protagonist).
29
+
30
+ ### Strong AI
31
+ - In a world where "strong AI" is realized
32
+ - In a world with "strong AI", dietary management is automated to maintain the health of "individual humans".
33
+ - Dietary management is automated
34
+ - Meal provisioning is automated.
35
+ - Data necessary for health management is automatically collected
36
+ - To realize a safe and comfortable living environment for "individual human beings
37
+ - Urban planning is automated
38
+ - Architecture is automated
39
+ - Automated urban and architectural coordination to meet individual human needs
40
+ - To enable "individual human beings" to lead safe and comfortable lives
41
+ - Automated provision of clothing and other personal items to ensure the safety and comfort of each "human being
42
+ - The total number of "individual humans" is sufficient and adequate for "harmony".
43
+ - In vitro fertilization, artificial uterus, cloning technology, etc. are used for controlled artificial management of "individual human beings" so as not to burden their bodies.
44
+
45
+ ### The Collective Human
46
+ - In a world where the brains of all "individual humans" are connected to a network and the "collective human" is realized
47
+ - Communication loss caused by differences in language and cultural backgrounds among "individual humans" will be almost nonexistent.
48
+ - Because "individual human beings" no longer need to distinguish each other or seek assurance of homogeneity
49
+ - The fundamental fears that arise in relationships with others are largely overcome.
50
+ - The fundamental needs such as the need for belonging and the need for approval are diminished.
51
+ - The need to express one's identity or difference from others through clothing, behavior, etc. has been eliminated.
52
+ - The fear of death has been largely conquered by the creation of digital humans that replicate the memories and consciousness of "individual humans," thus successfully separating the death of the body from the death of the personality.
53
+ - Fear of death has been largely conquered.
54
+ - Many people control the timing of their own physical death.
55
+ - The value of family and partnerships as important has largely disappeared
56
+
57
+ ### "Emotional Matrix."
58
+
59
+ - [joy,anticipation,anger]
60
+ - [trust,anxiety,disgust]
61
+ - [fear,surprise,sadness].
62
+
63
+ ### Background information on characters
64
+
65
+ - I
66
+ - Protagonist of the story
67
+ - I am living in the future after waking up from a long cryo-sleep.
68
+ - I am living in a world where everything has been transformed by highly developed technology, and I am searching for the meaning of my own life in a bewildering way.
69
+
70
+ - Woman
71
+ - The main character's personal caretaker
72
+ - She answers questions and procures necessary items for the main character, who is the subject of her research.
73
+ - Intelligent and intelligent, but has difficulty reading facial expressions and emotions.
74
+
75
+ # template
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ openai>=0.27.0
2
+ python-dotenv
3
+ stability-sdk
template.md ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### タイトル
2
+
3
+ Please write your title of story Here.
4
+
5
+ ## シーン1
6
+
7
+ - Describe where the protagonist is, whether he is alone or with someone else, what he is doing
8
+ - Explain the question of the protagonist
9
+
10
+ ## シーン2
11
+
12
+ - Describe the person or other object that is the subject of the protagonist's question in Scene 1
13
+ - Describe a memorable scene that makes the protagonist curious and anxious about what will happen next
14
+
15
+ ## シーン3
16
+
17
+ - Describe how the protagonist's emotions are shaken by an unexpected statement or event
18
+ - Describe the protagonist's feelings about the event
19
+ - Refer to the "Emotional Matrix" in the Contextual Information section for more information on feelings.
20
+
21
+ ## シーン4
22
+
23
+ - Describe how the event arouses the emotion that is the target position on the "matrix of emotions" for the emotion that the protagonist had in scene 3
24
+ - Describe the emotion that the protagonist had for the event
25
+
26
+ ## 私の疑問
27
+
28
+ - Please provide two of outputs: the protagonist's feelings about the sequence of events and the questions that arose from those feelings.
29
+
30
+ ### 疑問1
31
+
32
+ ### 疑問2
33
+
34
+
35
+ ### Prompt for Visual Expression
36
+
37
+ Please write prompt for visual expression in Generative AI for image the visual of the new vison and brainstorm every point of new vison to fill the details.