jifangw
2024-10-10 f3594da53527b4c170b48875b044e6e038d5fa35
Add files via upload
40 files added
3145 ■■■■■ changed files
FilmAgent/GenerateAudio.py 111 ●●●●● patch | view | raw | blame | history
FilmAgent/LLMCaller.py 48 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Apartment kitchen/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Apartment living room/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Beverage Room/position.json 20 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Billiard room/position.json 26 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Dining Room/position.json 26 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Gaming room/position.json 26 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Large kitchen/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Meeting room/position.json 44 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Office/position.json 20 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Reception Room/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Relaxing Room/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Roadside/position.json 14 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Sofa Corner/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Storehouse/position.json 20 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/Work room/position.json 32 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/actions.json 22 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/actions.txt 23 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/rotateandtrack.json 77 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/shots.json 11 ●●●●● patch | view | raw | blame | history
FilmAgent/Locations/shots.txt 27 ●●●●● patch | view | raw | blame | history
FilmAgent/env.txt 38 ●●●●● patch | view | raw | blame | history
FilmAgent/main.py 710 ●●●●● patch | view | raw | blame | history
FilmAgent/test_cot.py 81 ●●●●● patch | view | raw | blame | history
FilmAgent/test_full.py 716 ●●●●● patch | view | raw | blame | history
FilmAgent/test_no_interation.py 487 ●●●●● patch | view | raw | blame | history
FilmAgent/util.py 163 ●●●●● patch | view | raw | blame | history
TTS/env_tts.txt 141 ●●●●● patch | view | raw | blame | history
TTS/spk/female/seed_1151_restored_emb.pt patch | view | raw | blame | history
TTS/spk/female/seed_1397_restored_emb.pt patch | view | raw | blame | history
TTS/spk/female/seed_2279_restored_emb.pt patch | view | raw | blame | history
TTS/spk/female/seed_492_restored_emb.pt patch | view | raw | blame | history
TTS/spk/female/seed_874_restored_emb.pt patch | view | raw | blame | history
TTS/spk/male/seed_1185_restored_emb.pt patch | view | raw | blame | history
TTS/spk/male/seed_11_restored_emb.pt patch | view | raw | blame | history
TTS/spk/male/seed_1259_restored_emb.pt patch | view | raw | blame | history
TTS/spk/male/seed_1431_restored_emb.pt patch | view | raw | blame | history
TTS/spk/male/seed_1453_restored_emb.pt patch | view | raw | blame | history
TTS/tts_main.py 70 ●●●●● patch | view | raw | blame | history
FilmAgent/GenerateAudio.py
New file
@@ -0,0 +1,111 @@
import re
import os
import requests
import random
from util import *
from tqdm import tqdm
from LLMCaller import GPTTTS
# TO DO
Script_path = f"/path/to/script.json"
actos_path = f"/path/to/actors_profile.json"
Audio_path = f"The path to the folder where the audio files are stored."
# TO DO
if not os.path.exists(Audio_path):
    os.makedirs(Audio_path)
# ChatTTS
url = "http://xxx.xxx.xxx.xxx:xxxx/" # The API path where the chattts service is deployed
Chat_Speaker_female = [0, 1, 2, 3, 4]
Chat_Speaker_male = [0, 1, 2, 3, 4]
random.shuffle(Chat_Speaker_female)
random.shuffle(Chat_Speaker_male)
invalid_characters_map = {
    "!": ".",
    "?": ".",
    "'": ",",
    ':': ',',
    ';': ',',
    '!': '.',
    '(': ',',
    ')': ',',
    '[': ',',
    ']': ',',
    '>': ',',
    '<': ',',
    '-': ','
}
# OpenAI TTS
GPT_Speaker_female = ["alloy", "fable", "nova", "shimmer"]
GPT_Speaker_male = ["echo","onyx" ]
random.shuffle(GPT_Speaker_female)
random.shuffle(GPT_Speaker_male)
# Clear all audio generated last time
for filename in os.listdir(Audio_path):
    file_path = os.path.join(Audio_path, filename)
    os.remove(file_path)
# GPT: Assign a voice to each character
# name2gptspeaker = {}
# roles = read_json(actos_path)
# for role in roles:
#     if role['gender'].lower() == "male":
#         name2gptspeaker[role['name']] = GPT_Speaker_male[0]
#         GPT_Speaker_male.pop(0)
#     else:
#         name2gptspeaker[role['name']] = GPT_Speaker_female[0]
#         GPT_Speaker_female.pop(0)
# ChatTTS: Assign a voice to each character
name2chatspeaker = {}
roles = read_json(actos_path)
for role in roles:
    name2chatspeaker[role['name']] = {}
    if role['gender'].lower() == "male":
        name2chatspeaker[role['name']]['id'] = Chat_Speaker_male[0]
        name2chatspeaker[role['name']]['gender'] = "male"
        Chat_Speaker_male.pop(0)
    else:
        name2chatspeaker[role['name']]['id'] = Chat_Speaker_female[0]
        name2chatspeaker[role['name']]['gender'] = "female"
        Chat_Speaker_female.pop(0)
script = read_json(Script_path)
lines = []
for scene in script:
    for event in scene['scene']:
        if "content" in event.keys():
            l = event["content"]
            if contains_digit(l):
                l = translate_digit(l)
            lines.append({"speaker": event["speaker"], "content": prompt_format(l, invalid_characters_map)+"[uv_break]"})
Flag = "ChatTTS" # GPT or ChatTTS
params_infer_code =  {'prompt':'[speed_3]', 'temperature':0.3,'top_P':0.9, 'top_K':1}
params_refine_text = {'prompt':'[oral_2][laugh_4][break_6]'}
print(name2chatspeaker)
for line in tqdm(lines):
    # if Flag == "GPT":
    #     response = GPTTTS(line['content'], name2gptspeaker[line['speaker']])
    #     response.stream_to_file(cretae_new_path(Audio_path, "mp3"))
    if Flag == "ChatTTS":
        response = requests.post(url, json={"gender": name2chatspeaker[line['speaker']]['gender'], "text": line['content'], "id": name2chatspeaker[line['speaker']]['id'], "params_infer_code": params_infer_code, "params_refine_text": params_refine_text})
        # response = requests.post(url, json={"gender": line['gender'], "text": line['text'], "id": line['id'], "params_infer_code": params_infer_code, "params_refine_text": params_refine_text})
        if response.status_code == 200:
            content_disposition = response.headers.get("Content-Disposition")
            filename = re.findall("filename=\"(.+)\"", content_disposition)
            filename = filename[0]
            with open(os.path.join(Audio_path, filename), "wb") as f:
                f.write(response.content)
        else:
            print(f"Failed to create item. Status code: {response.status_code}")
FilmAgent/LLMCaller.py
New file
@@ -0,0 +1,48 @@
import os
import openai
from openai import OpenAI
api_key = "xxxxxxxxxxxxxx"
organization = "xxxxxxxxxxxxxx"
def GPTCall(prompt):
    counter = 0
    result = "api调用失败"
    while counter < 3:
        try:
            openai.api_key = api_key
            openai.organization = organization
            client = OpenAI(api_key = api_key, organization = organization)
            completion = client.chat.completions.create(
                model = "gpt-4o",
                # model = "gpt-3.5-turbo",
                # model="gpt-4-1106-preview",
                messages=[
                    {"role": "user", "content": prompt},
                ]
            )
            result = completion.choices[0].message.content
            print(f"%%%%%%%%%%%%%%%%%%%%%%%%\n{result}\n%%%%%%%%%%%%%%%%%%%%%%%")
            break
        except Exception as e:
            print(e)
            counter += 1
    return result
def GPTTTS(text, role):
    openai.api_key = api_key
    openai.organization = organization
    client = OpenAI(api_key = api_key, organization = organization)
    response = client.audio.speech.create(
        model = "tts-1",
        voice = role,
        input = text,
        response_format = "mp3"
    )
    return response
FilmAgent/Locations/Apartment kitchen/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "This position is situated at the innermost part of the apartment kitchen, adjacent to position 2.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "This position is located in the middle of the apartment's kitchen, adjacent to position 1.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "This position is situated on the far right side of the apartment kitchen, against the wall.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "This location is situated in the open area of the apartment kitchen.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "This location is situated in the open area of the apartment kitchen.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Apartment living room/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "This position is located in front of the long sofa at the center of the apartment, between position 2 and 3. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "This position is located in front of the short sofa at the center of the apartment, close to position 1 and 3. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "This position is located in front of the long sofa at the center of the apartment, close to position 1 and 2.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "This position is situated in the hallway of an apartment, behind position 2.",
        "sittable": false,
        "fixed_angle": true
    },
    {
        "id": "Position 5",
        "description": "This position is located diagonally behind position 1, close to the window.",
        "sittable": false,
        "fixed_angle": true
    }
]
FilmAgent/Locations/Beverage Room/position.json
New file
@@ -0,0 +1,20 @@
[
    {
        "id": "Position 1",
        "description": "The position is in front of a chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is situated in an open area within the beverage room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is not far from the beverage room entrance.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Billiard room/position.json
New file
@@ -0,0 +1,26 @@
[
    {
        "id": "Position 1",
        "description": "The position is next to the pool table.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is next to the pool table.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is next to the pool table.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is next to the pool table.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Dining Room/position.json
New file
@@ -0,0 +1,26 @@
[
    {
        "id": "Position 1",
        "description": "The position is in front of a chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is in front of a chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is in front of a chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "This position is at the entrance of the dining room.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Gaming room/position.json
New file
@@ -0,0 +1,26 @@
[
    {
        "id": "Position 1",
        "description": "This position is located in front of the sofa in the gaming room, adjacent to position 2. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "This position is located in front of the sofa in the gaming room, adjacent to position 1. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "This position is located in front of the computer desk in the middle of the gaming room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "This position is located in front of the computer desk at the far end of the gaming room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Large kitchen/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "The position is situated in an open area within the large kitchen.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is situated in an open area within the large kitchen.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is situated in an open area within the large kitchen, close to position 4.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is situated in an open area within the large kitchen, close to position 3.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "The position is situated in an open area within the large kitchen.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Meeting room/position.json
New file
@@ -0,0 +1,44 @@
[
    {
        "id": "Position 1",
        "description": "This position is located in front of the middle seat in the meeting room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is located in front of a seat on the right side of the meeting room, close to position 1. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is located in front of a seat on the right side of the meeting room, between position 2 and 4. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is located in front of a seat on the right side of the meeting room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "The position is located in front of a seat on the left side of the meeting room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 6",
        "description": "The position is located in front of a seat on the left side of the meeting room, between position 5 and 7. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 7",
        "description": "The position is located in front of a seat on the left side of the meeting room, close to position 1. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Office/position.json
New file
@@ -0,0 +1,20 @@
[
    {
        "id": "Position 1",
        "description": "The position is in front of the guest chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is in front of the guest chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is in front of the main chair. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Reception Room/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "The position is in front of the sofa in the reception room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is in front of the sofa in the reception room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is situated in an open area within the reception room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is situated in an open area within the reception room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "The position is at the front desk in the reception room.",
        "sittable": false,
        "fixed_angle": true
    }
]
FilmAgent/Locations/Relaxing Room/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "The position is situated in an open area within the relaxing room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is situated in an open area within the relaxing room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is situated in an open area within the relaxing room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is in front of the sofa in the relaxing room, close to position 5. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "The position is in front of the sofa in the relaxing room, close to position 4. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Roadside/position.json
New file
@@ -0,0 +1,14 @@
[
    {
        "id": "Position 1",
        "description": "This position is in front of the bench on the left side of the road. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "This position is in front of the bench on the right side of the road. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Sofa Corner/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "The position is in front of a sofa. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is in front of a sofa. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is in front of a sofa. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is situated in an open area within the sofa corner.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "The position is situated in an open area within the sofa corner.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/Storehouse/position.json
New file
@@ -0,0 +1,20 @@
[
    {
        "id": "Position 1",
        "description": "This position is located in front of a chair at the very back of the storehouse. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "This position is in front of the cabinet in the middle of the storehouse.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is not far from the storehouse entrance.",
        "sittable": false,
        "fixed_angle": true
    }
]
FilmAgent/Locations/Work room/position.json
New file
@@ -0,0 +1,32 @@
[
    {
        "id": "Position 1",
        "description": "The position is in front of a desk in the middle of the work room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 2",
        "description": "The position is in front of a desk at the back of the work room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 3",
        "description": "The position is in front of a desk in the middle of the work room.",
        "sittable": false,
        "fixed_angle": false
    },
    {
        "id": "Position 4",
        "description": "The position is in front of a desk in the middle of the work room. A character can sit down at this position.",
        "sittable": true,
        "fixed_angle": false
    },
    {
        "id": "Position 5",
        "description": "The position is situated in an open area within the work room.",
        "sittable": false,
        "fixed_angle": false
    }
]
FilmAgent/Locations/actions.json
New file
@@ -0,0 +1,22 @@
{
    "Standing Talking": "simply show the character is talking.",
    "Standing Thinking": "show the character is thinking.",
    "Standing Depressed": "convey the character's depressed emotion.",
    "Standing Crying": "show the character is crying.",
    "Standing Angry": "convey the character's angry emotion.",
    "Standing Happy": "convey the character's happy emotion.",
    "Standing Surprise": "convey the character's surprise emotion.",
    "Standing Puzzled": "show the character's confusion.",
    "Standing Greeting": "only used for the character to greet others.",
    "Standing Bored": "show the character's boredom.",
    "Standing Normal": "merely depict the character standing.",
    "Standing Arguing": "show the character is arguing with others.",
    "Standing Agree": "convey the character's approval.",
    "Standing Deny": "convey the character's rejection or disapproval.",
    "Joyful Jump": "demonstrate the character is extremely happy.",
    "Sit Down": "When you need to change the character's state from standing to sitting, you can perform this action.",
    "Sitting Talking": "simply show the character is talking.",
    "Sitting Laughing": "convey the character's happy emotion.",
    "Sitting Claping": "indicate the character agrees or is happy.",
    "Stand Up": "When you need to change the character's state from sitting to standing, you can perform this action."
}
FilmAgent/Locations/actions.txt
New file
@@ -0,0 +1,23 @@
1. **Actions performed in standing state**:
   - Standing Talking: simply show the character is talking.
   - Standing Thinking: show the character is thinking.
   - Standing Depressed: convey the character's depressed emotion.
   - Standing Crying: show the character is crying.
   - Standing Angry: convey the character's angry emotion.
   - Standing Happy: convey the character's happy emotion.
   - Standing Surprise: convey the character's surprise emotion.
   - Standing Puzzled: show the character's confusion.
   - Standing Greeting: only used for the character to greet others.
   - Standing Bored: show the character's boredom.
   - Standing Normal: merely depict the character standing.
   - Standing Arguing: show the character is arguing with others.
   - Standing Agree: convey the character's approval.
   - Standing Deny: convey the character's rejection or disapproval.
   - Joyful Jump: demonstrate the character is extremely happy.
   - Sit Down: Only when you need to change the character's state from standing to sitting, you must perform this action.
2. **Actions performed in sitting state**:
   - Sitting Talking: simply show the character is talking.
   - Sitting Laughing: convey the character's happy emotion.
   - Sitting Claping: indicate the character agrees or is happy.
   - Stand Up: Only when you need to change the character's state from sitting to standing, you must perform this action.
FilmAgent/Locations/rotateandtrack.json
New file
@@ -0,0 +1,77 @@
{
    "Apartment living room": {
        "rotate": 1,
        "track": 4,
        "long": 4
    },
    "Apartment kitchen": {
        "rotate": 1,
        "track": 1,
        "long": 3
    },
    "Roadside": {
        "rotate": 1,
        "track": 1,
        "long": 1
    },
    "Gaming room": {
        "rotate": 1,
        "track": 2,
        "long": 1
    },
    "Meeting room": {
        "rotate": 1,
        "track": 3,
        "long": 3
    },
    "Storehouse": {
        "rotate": 1,
        "track": 2,
        "long": 1
    },
    "Relaxing Room": {
        "rotate": 3,
        "track": 2,
        "long": 3
    },
    "Reception Room": {
       "rotate": 3,
        "track": 3,
        "long": 3
    },
    "Sofa Corner": {
        "rotate": 3,
        "track": 3,
        "long": 3
    },
    "Large kitchen": {
        "rotate": 3,
        "track": 3,
        "long": 3
    },
    "Beverage Room": {
        "rotate": 2,
        "track": 2,
        "long": 1
    },
    "Office": {
        "rotate": 2,
        "track": 2,
        "long": 1
    },
    "Dining Room": {
        "rotate": 2,
        "track": 2,
        "long": 2
    },
    "Billiard room": {
        "rotate": 2,
        "track": 2,
        "long": 2
    },
    "Work room": {
        "rotate": 3,
        "track": 2,
        "long": 2
    }
}
FilmAgent/Locations/shots.json
New file
@@ -0,0 +1,11 @@
{
    "Close Shot": "Captures only the upper body of the speaker, ideal for creating a sense of tension, pressure, or intimacy and focus on the character.",
    "Mid Shot": "Captures only the speaker's full body, useful for showing body language and balances detail and context.",
    "Follow Shot": "The camera follows the character continuously as they move. This shot creates a sense of immersion and keeps the audience connected to the character’s journey.",
    "Pan Shot": "The camera remains focused on the character, even if the character moves. This maintains the audience's attention on the character, emphasizing their importance or reactions.",
    "360 Degrees Shot": "The camera rotates 360 degrees around the character (the character must be standing).",
    "Curve Surround Shot": "The camera moves from the character's feet to their head while sweeping from back to front (the character must be standing).",
    "Track Shot": "The camera will dynamically transition from one long shot to another long shot.",
    "Zoom Shot": "This shot allows for a smooth transition from one perspective to another.",
    "Long Shot": "This shot displays the entire scene."
}
FilmAgent/Locations/shots.txt
New file
@@ -0,0 +1,27 @@
- **Dynamic Shots**:
   - **Zoom Shot**: Appears to move closer to the subject, following a Long Shot.
     - **Usage Condition**:
       1. When the character is talking, gradually focus on the character.
       2. When the character is talking, highlight key comedic or dramatic moment.
   - **Pan Shot**: Pivots horizontally from a fixed position to track character movement.
     - **Usage Condition**:
       1. When the character is talking, use this shot multiple times in a row to create a tense atmosphere.
       2. When the character is moving, use this shot to display both the character and surroundings.
   - **Follow Shot**: Continuously follows a moving character.
     - **Usage Condition**: This shot can only be used when the character is moving. Immersing the audience in the character's perspective during movement.
   - **360 Degrees Shot**: Circles completely around a standing character.
     - **Usage Condition**:
       1. This shot can be used when the character first appears in the script.
       2. When the character is talking, create unease and heightening scene tension.
   - **Curve Surround Shot**: Moves from the character's feet to head, with the character standing.
     - **Usage Condition**: This shot can only be used when the character first appears in the script.
   - **Track Shot**: Switches dynamically between long shots.
     - **Usage Condition**: This shot can only be used in the opening shot of each scene to showcase characters and their environments.
- **Static Shots**:
   - **Long Shot**: Displays the entire scene.
     - **Usage Condition**: Providing background and showing interactions during dialogue.
   - **Close Shot**: Focuses on the upper body of a character.
     - **Usage Condition**: Captures the character's emotions during dialogue.
   - **Mid Shot**: Captures the full body of a character.
     - **Usage Condition**: Showcasing body language and interactions.
FilmAgent/env.txt
New file
@@ -0,0 +1,38 @@
annotated-types==0.7.0
anyio==4.4.0
attrs==23.2.0
certifi==2024.2.2
charset-normalizer==3.3.2
colorama==0.4.6
contourpy==1.3.0
cycler==0.12.1
distro==1.9.0
exceptiongroup==1.2.1
fonttools==4.53.1
h11==0.14.0
httpcore==1.0.5
httpx==0.27.0
idna==3.7
importlib_resources==6.4.4
jsonlines==4.0.0
kiwisolver==1.4.5
Levenshtein==0.25.1
matplotlib==3.9.2
numpy==2.0.1
openai==1.30.5
packaging==24.1
pillow==10.4.0
pydantic==2.7.2
pydantic_core==2.18.3
pyparsing==3.1.4
python-dateutil==2.9.0.post0
python-Levenshtein==0.25.1
rapidfuzz==3.9.3
requests==2.32.3
scipy==1.13.1
six==1.16.0
sniffio==1.3.1
tqdm==4.66.4
typing_extensions==4.12.0
urllib3==2.2.2
zipp==3.20.1
FilmAgent/main.py
New file
@@ -0,0 +1,710 @@
from util import *
from LLMCaller import *
from typing import Dict, List, Union
import random
import copy
# TO DO
ROOT_PATH = "/path/to/FilmAgent"
# TO DO
class FilmCrafter:
    def __init__(self, topic: str) -> None:
        self.topic = topic
        self.log_path = cretae_new_path(os.path.join(ROOT_PATH, "Logs"), "txt")
        self.profile_path = os.path.join(ROOT_PATH, "Script\\actors_profile.json")
        self.action_description_path = os.path.join(ROOT_PATH, "Locations\\actions.txt")
        self.shot_description_path = os.path.join(ROOT_PATH, "Locations\\shots.txt")
        # scenes
        self.scene_path = os.path.join(ROOT_PATH, "Script\scenes_1.json")
        # + lines
        self.scene_path_1 = os.path.join(ROOT_PATH, "Script\scenes_2.json")
        # + positions
        self.scene_path_2 = os.path.join(ROOT_PATH, "Script\scenes_3.json")
        # + actions
        self.scene_path_3 = os.path.join(ROOT_PATH, "Script\scenes_4.json")
        # stage1_verify
        self.scene_path_4 = os.path.join(ROOT_PATH, "Script\scenes_5.json")
        # stage2_verify
        self.scene_path_5 = os.path.join(ROOT_PATH, "Script\scenes_6.json")
        # + movement
        self.scene_path_6 = os.path.join(ROOT_PATH, "Script\scenes_7.json")
        # + shot (stage3_verify)
        self.scene_path_7 = os.path.join(ROOT_PATH, "Script\scenes_8.json")
        # The final script
        self.script_path = cretae_new_path(os.path.join(ROOT_PATH, "Script\script"), "json")
        # director's shot annotation
        self.director_shot_path = os.path.join(ROOT_PATH, "Script\director_shot.json")
        # cinematographer's shot annotation
        self.cinematographer_shot_path = os.path.join(ROOT_PATH, "Script\cinematographer_shot.json")
        # The maximum number of characters in a film
        self.character_limit = 4
        # The maximum number of scenes in a film
        self.scene_limit = 3
        # The maximum number of discussions between director and screenwriter
        self.stage1_verify_limit = 3
        # The maximum number of discussions between director, actor and screenwriter
        self.stage2_verify_limit = 3
        # The maximum number of discussions between director and cinematographer
        self.stage3_verify_limit = 4
    def call(self, identity: str, params: Dict, trans2json: bool = True) -> Union[str, dict, list]:
        prompt = read_prompt(os.path.join(ROOT_PATH, f"Prompt\{identity}.txt") )
        prompt = prompt_format(prompt, params)
        log_prompt(self.log_path, prompt)
        result = GPTCall(prompt)
        if trans2json:
            result = clean_text(result)
            result = GPTResponse2JSON(result)
        log_prompt(self.log_path, result)
        return result
    def casting(self):
        '''
            Role: Director
            Behavior: Create the main characters and their bios for the film script.
        '''
        params = {"{topic}": self.topic, "{character_limit}": self.character_limit}
        result = self.call("director_1", params)
        write_json(self.profile_path, result)
    def scenes_plan(self):
        '''
            Role: Director
            Behavior:
                Plan the outline of script, include:
                1. The number of scenes.
                2. The characters, location and main plot of each scene.
        '''
        profile = read_json(self.profile_path)
        male_characters = ", ".join(list(map(lambda x: x['name'],
                                             filter(lambda x: x['gender'].lower() == 'male', profile))))
        female_characters = ", ".join(list(map(lambda x: x['name'],
                                               filter(lambda x: x['gender'].lower() == 'female', profile))))
        params = {"{topic}": self.topic,
                  "{male_characters}": male_characters,
                  "{female_characters}": female_characters,
                  "{scene_limit}": self.scene_limit}
        result = self.call("director_2", params)
        write_json(self.scene_path, result)
    def lines_generate(self):
        '''
            Role: Screenwriter
            Behavior: Write lines for the script.
        '''
        scenes = read_json(self.scene_path)
        script_outline = ""
        who = []
        where = []
        what = []
        for id,scene in enumerate(scenes):
            selected_roles = scene[return_most_similar("selected-characters", list(scene.keys()))]
            selected_location = scene[return_most_similar("selected-location", list(scene.keys()))]
            story_plot = scene[return_most_similar("story-plot", list(scene.keys()))]
            who.append(selected_roles)
            where.append(selected_location)
            what.append(story_plot)
            topic = scene[return_most_similar("sub-topic", list(scene.keys()))]
            characters = ", ".join(selected_roles)
            plot = story_plot
            location = selected_location
            goal = scene[return_most_similar("dialogue-goal", list(scene.keys()))]
            script_outline = script_outline + f"{id + 1}. **Scene {id + 1}**:\n   - topic: {topic}\n   - involved characters: {characters}\n   - plot: {plot}\n   - location: {location}\n   - dialogue goal: {goal}\n\n"
        params = {"{script_outline}": script_outline.strip()}
        result = self.call("screenwriter_1", params)
        lines = []
        assert len(result) == len(scenes)
        for j in range(len(scenes)):
            line = {}
            line['scene_information'] = {}
            line['scene_information']['who'] = who[j]
            line['scene_information']['where'] = where[j]
            line['scene_information']['what'] = what[j]
            line['dialogues'] = result[j][return_most_similar("scene-dialogue", list(result[j].keys()))]
            lines.append(line)
        write_json(self.scene_path_1, lines)
    def position_mark(self):
        '''
            Role: Screenwriter
            Behavior: Choose an appropriate initial position for each character in each scene of the script.
        '''
        scenes = read_json(self.scene_path_1)
        script_information = ""
        optional_positions = ""
        for id,scene in enumerate(scenes):
            i = id + 1
            who = scene['scene_information']['who']
            where = scene['scene_information']['where']
            what = scene['scene_information']['what']
            script_information = script_information + f"{i}. **Scene {i}**:\n   - characters: {who}\n   - location: {where}\n   - plot: {what}\n\n"
            position_path = os.path.join(ROOT_PATH, f"Locations\{where}\position.json")
            positions = read_json(position_path)
            normal_position = [item for item in positions if item['fixed_angle'] == False]
            # This "if judgment" is related to the position, and camera settings in Unity.
            if len(who) >= len(positions) - len(normal_position) + 2:
                p = ""
                for it,position in enumerate(positions):
                    j = it + 1
                    p = p + f"   - Position {j}: " + position['description'] + '\n'
            else:
                p = ""
                for it,position in enumerate(normal_position):
                    j = it + 1
                    p = p + f"   - Position {j}: " + position['description'] + '\n'
            optional_positions = optional_positions + f"{i}. **Positions in {where}**:\n{p}\n"
        params = {"{script_information}": script_information.strip(),
                        "{optional_positions}": optional_positions.strip()}
        result = self.call("screenwriter_2", params)
        assert len(result) == len(scenes)
        for j in range(len(scenes)):
            scenes[j]["initial position"] = result[j][return_most_similar("scene-position", list(result[j].keys()))]
        write_json(self.scene_path_2, scenes)
    def action_mark(self):
        '''
            Role: Screenwriter
            Behavior: Choose appropriate actions for the characters engaged in the dialogue.
        '''
        scenes = read_json(self.scene_path_2)
        all_actions = read_prompt(self.action_description_path)
        data = []
        for scene in scenes:
            position_path = os.path.join(ROOT_PATH, f"Locations\{scene['scene_information']['where']}\position.json")
            positions = read_json(position_path)
            ini = ""
            for id,item in enumerate(scene['initial position']):
                if [it['sittable'] for it in positions if get_number(it['id']) == get_number(item['position'])][0]:
                    sit = "sittable"
                else:
                    sit = "unsittable"
                ini = ini + f"   - {item['character']}: " + f"{sit} Position {str(get_number(item['position']))}, standing\n"
            ini = "   " + ini.strip()
            params = {"{initial}": ini,
                        "{plot}": scene['scene_information']['what'],
                        "{dialogues}": scene['dialogues'],
                        "{all_actions}": all_actions}
            result = self.call("screenwriter_3", params)
            assert len(result) == len(scene['dialogues'])
            scene['dialogues'] = result
            data.append(scene)
        write_json(self.scene_path_3, data)
    def find_unknown_actions(self, scenes: List) -> List:
        '''
            Input: The complete script
            Output: The list of actions appearing in the script that are not set in Unity.
        '''
        unknown_actions = []
        all_actions = read_json(os.path.join(ROOT_PATH, "Locations\\actions.json"))
        for scene in scenes:
            for line in scene['dialogues']:
                for action in line['actions']:
                    if action['action'] not in all_actions.keys() and action['action'] not in unknown_actions:
                        unknown_actions.append(action['action'])
        return unknown_actions
    def stage1_verify(self):
        '''
            Role: Director and Screenwriter
            Behavior: The director and screenwriter have a comprehensive discussion about the script to improve it, focusing on the following three aspects: Action Reasonableness, Theme Consistency, Script Fluency.
        '''
        scenes = read_json(self.scene_path_3)
        current_script = []
        unknown_actions = self.find_unknown_actions(scenes)
        characters_position = ""
        for id,scene in enumerate(scenes):
            new_scene = {}
            new_scene['scene_information'] = scene['scene_information']
            new_scene['initial position'] = scene['initial position']
            new_scene['dialogues'] = []
            for line in scene['dialogues']:
                new_line = copy.deepcopy(line)
                for action in new_line['actions']:
                    action.pop("reasoning")
                new_scene['dialogues'].append(new_line)
            current_script.append(new_scene)
            position_path = os.path.join(ROOT_PATH, f"Locations\{scene['scene_information']['where']}\position.json")
            positions = read_json(position_path)
            p = []
            for position in scene['initial position']:
                position_id = get_number(position['position'])
                sittable = "sittable" if positions[position_id-1]['sittable'] else "unsittable"
                p.append(f"{position['character']}'s position: {sittable}")
            characters_position = characters_position + f"{id+1}. **Scene {id+1}**:\n{', '.join(p)}\n\n"
        all_actions = read_prompt(self.action_description_path)
        for i in range(self.stage1_verify_limit):
            params = {"{theme}": self.topic,
                        "{original_script}": current_script,
                        "{all_actions}": all_actions,
                        "{unknown_actions}": ', '.join(unknown_actions)}
            feedback = self.call("director_3", params, trans2json=False)
            params = {"{theme}": self.topic,
                      "{feedback}": feedback,
                        "{script}": current_script,
                        "{all_actions}": all_actions,
                        "{characters_position}": characters_position}
            revised_script = self.call("screenwriter_4", params)
            current_script = revised_script
            unknown_actions = self.find_unknown_actions(revised_script)
            # If there are still unknown actions, discuss again immediately.
            if len(unknown_actions)>0:
                continue
            params = {"{feedback}": feedback,
                        "{revised_script}": revised_script}
            verify = self.call("director_4", params, trans2json=False)
            if verify.find("finalize") == -1:
                continue
            verify = verify[verify.find("finalize"):]
            if "True" in verify or "true" in verify:
                break
        write_json(self.scene_path_4, revised_script)
    def stage2_verify(self):
        '''
            Role: Actor, Director and Screenwriter
            Behavior: The actors suggest minor adjustments to the script lines, and the director and screenwriter discuss the revisions.
        '''
        scenes = read_json(self.scene_path_4)
        profiles = read_json(self.profile_path)
        feedback = {}
        scenes_for_actor = []
        for scene in scenes:
            item = {}
            item['scene_information'] = scene[return_most_similar('scene_information', list(scene.keys()))]
            item["dialogues"] = []
            for line in scene['dialogues']:
                new_line = {}
                new_line['speaker'] = line['speaker']
                new_line['content'] = line['content']
                item["dialogues"].append(new_line)
            scenes_for_actor.append(item)
        for profile in profiles:
            params = {"{character}": profile['name'],
                        "{profile}": profile,
                        "{script}": scenes_for_actor}
            result = self.call("actor", params, trans2json=False)
            feedback[profile['name']] = result
        suggestions = ""
        for name, suggestion in feedback.items():
            suggestions = suggestions + f"   - **{name}**: {suggestion}\n"
        params = {"{suggestions}": suggestions}
        result = self.call("director_5", params)
        if result[return_most_similar("adopted-suggestions", list(result.keys()))] == "None":
            write_json(self.scene_path_5, scenes)
        else:
            current_script = scenes_for_actor
            adopted_suggestions = result[return_most_similar("adopted-suggestions", list(result.keys()))]
            for sugg in adopted_suggestions:
                sugg.pop("reason")
            for i in range(self.stage2_verify_limit):
                params = {"{feedback}": adopted_suggestions,
                            "{script}": current_script}
                revised_script = self.call("screenwriter_5", params)
                current_script = revised_script
                params = {"{feedback}": adopted_suggestions,
                            "{revised_script}": revised_script}
                verify = self.call("director_6", params, trans2json=False)
                verify = verify[verify.find("finalize"):]
                if "True" in verify or "true" in verify:
                    break
            assert len(revised_script) == len(scenes)
            for id,scene in enumerate(scenes):
                assert len(scene['dialogues']) == len(revised_script[id]['dialogues'])
                for it,line in enumerate(scene['dialogues']):
                    assert line['speaker'] == revised_script[id]['dialogues'][it]['speaker']
                    line['content'] = revised_script[id]['dialogues'][it]['content']
            write_json(self.scene_path_5, scenes)
    def is_keep_standing(self, lines, character):
        '''
            Description: Check if the character remains standing throughout the script.
            Input: The complete script, a character's name
            Output: True or False
        '''
        for line in lines:
            actions = line['actions']
            for action in actions:
                if action['character'] == character and action['state'] == 'sitting':
                    return False
        return True
    def moveable_options(self, scene):
        '''
            Input: The complete script
            Output:
                1. All movable characters (i.e., the characters that remain standing throughout the script)
                2. All positions that character can move to (i.e., the unoccupied positions)
        '''
        position_path = os.path.join(ROOT_PATH, f"Locations\{scene[return_most_similar('scene_information', list(scene.keys()))]['where']}\position.json")
        positions = read_json(position_path)
        occupied_positions = [get_number(item['position']) for item in scene[return_most_similar('initial position', list(scene.keys()))]]
        unoccupied_positions = [f"{item['id']}: {item['description']}" for item in positions if get_number(item['id']) not in occupied_positions]
        if len(unoccupied_positions) == 0:
            return None, None
        who = scene[return_most_similar('scene_information', list(scene.keys()))]['who']
        moveable_characters = []
        for character in who:
            if self.is_keep_standing(scene['dialogues'], character):
                moveable_characters.append(character)
        if len(moveable_characters) == 0:
            return None, None
        return moveable_characters, unoccupied_positions
    def move_mark(self):
        '''
            Role: Director
            Behavior: The director adds appropriate character movements into the script.
        '''
        scenes = read_json(self.scene_path_5)
        data = []
        for scene in scenes:
            moveable_characters, unoccupied_positions = self.moveable_options(scene)
            moved_charatcter, moveto_position = None, None
            if moveable_characters:
                move2destination = ""
                for pn in unoccupied_positions:
                    move2destination = move2destination + f"   - {pn}\n"
                move2destination = "   " + move2destination.strip()
                lines = []
                for id in range(len(scene['dialogues'])):
                    lines.append(f"<Insertion Position {id}>")
                    item = {}
                    item['speaker'] = scene['dialogues'][id]['speaker']
                    item['content'] = scene['dialogues'][id]['content']
                    lines.append(item)
                params = {"{moveable_characters}": moveable_characters,
                                "{story}": scene[return_most_similar('scene_information', list(scene.keys()))]['what'],
                                "{lines}": lines,
                                "{destinations}": move2destination,
                                "{current_positions}": scene[return_most_similar('initial position', list(scene.keys()))]}
                result = self.call("director_7", params)
                if 'insertion' in result.keys():
                    moved_charatcter = result['move']['character']
                    moveto_position = result['move']['destination']
                    scene['dialogues'].insert(get_number(result['insertion'][return_most_similar('insertion position', list(result['insertion'].keys()))]), result)
            # Update the characters' position in real time
            position_change = False
            for line in scene['dialogues']:
                if "move" not in line.keys():
                    line['current position'] = scene[return_most_similar('initial position', list(scene.keys()))]
                else:
                    position_change = True
                    line['current position'] = scene[return_most_similar('initial position', list(scene.keys()))]
                    continue
                if position_change:
                    line['current position'] = [item if item['character'] !=  moved_charatcter else {'character': moved_charatcter, 'position': moveto_position} for item in line['current position']]
            data.append(scene)
        write_json(self.scene_path_6, data)
    def shot_mark(self):
        '''
            Input: None
            Output:
                1. Director's shot annotations
                2. Cinematographer's shot annotations
                3. The complete script before adding shot annotations
                4. The script after inserting the shot annotation points.
        '''
        scenes = read_json(self.scene_path_6)
        script = {}
        for ID,scene in enumerate(scenes):
            I = ID + 1
            script[f'scene {I}'] = []
            for id,item in enumerate(scene['dialogues']):
                line = {}
                i = id + 1
                if "speaker" in item.keys():
                    line['dialogue'] = f"{item['speaker']}: {item['content']}"
                    line['actions'] = item['actions']
                    # line['plot'] = ' '.join([it['reason'] for it in item['actions']])
                    line[f'selected-shot-{i}'] = "..."
                else:
                    line['move'] = {}
                    line['move']['character'] = item['move']['character']
                    line['move']['destination'] = item['move']['destination']
                    line[f'selected-shot-{i}'] = "..."
                script[f'scene {I}'].append(line)
        all_shots = read_prompt(self.shot_description_path)
        params = {"{script}": script, "{all_shots}": all_shots}
        result1 = self.call("cinematographer", params)
        result2 = self.call("director_8", params)
        for scene_id, scene in result1.items():
            for shot_id, shot in scene.items():
                shot.pop("reasoning")
        for scene_id, scene in result2.items():
            for shot_id, shot in scene.items():
                shot.pop("reasoning")
        write_json(self.director_shot_path, result2)
        write_json(self.cinematographer_shot_path, result1)
        return script, result1, result2, scenes
    def revise_shot_annotation(self, src, feedback):
        '''
            Input: Original shot annotation, revision suggestion
            Output: Revised shot annotation
        '''
        new = src
        for scene_id, scene in new.items():
            for shot_id, shot in scene.items():
                if shot['shot'] != feedback[scene_id][shot_id]['shot']:
                    continue
                need_update = feedback[scene_id][shot_id][return_most_similar("need update", list(feedback[scene_id][shot_id].keys()))]
                if isinstance(need_update, str) and need_update.lower() == "false":
                    continue
                if isinstance(need_update, bool) and not need_update:
                    continue
                shot['shot'] = feedback[scene_id][shot_id][return_most_similar("updated shot", list(feedback[scene_id][shot_id].keys()))]
        return new
    def stage3_verify(self):
        '''
            Role: Director and Cinematographer
            Behavior: The director and the cinematographer provide their own shot annotations, then discuss and revise them together, and finally, the director selects the better one.
        '''
        script, shot_mark_cinematographer, shot_mark_director, scenes = self.shot_mark()
        current_shot_c, current_shot_d = shot_mark_cinematographer, shot_mark_director
        all_shots = read_prompt(self.shot_description_path)
        for i in range(self.stage3_verify_limit):
            params = {"{identity_1}": "Director",
                      "{identity_2}": "Cinematographer",
                      "{script}": script,
                      "{shot_annotation}": current_shot_c,
                      "{all_shots}": all_shots
                      }
            result1 = self.call("shot_review", params)
            current_shot_c = self.revise_shot_annotation(current_shot_c, result1)
            params = {"{identity_1}": "Cinematographer",
                      "{identity_2}": "Director",
                      "{script}": script,
                      "{shot_annotation}": current_shot_d,
                      "{all_shots}": all_shots
                      }
            result2 = self.call("shot_review", params)
            current_shot_d = self.revise_shot_annotation(current_shot_d, result2)
        params = {"{shot_annotation_1}": current_shot_d,
                    "{shot_annotation_2}": current_shot_c,
                    "{script}": script,
                    "{all_shots}": all_shots
                    }
        result = self.call("director_9", params)
        last_shots = current_shot_d if result['better'].lower()=="director" else current_shot_c
        assert len(list(last_shots.keys())) == len(scenes)
        for id in range(len(list(last_shots.keys()))):
            i = id + 1
            assert len(list(last_shots[f'scene {i}'].keys())) == len(scenes[id]['dialogues'])
            for key,value in last_shots[f'scene {i}'].items():
                scenes[id]['dialogues'][get_number(key)-1]['selected shot'] = value[return_most_similar('shot', list(value.keys()))]
        write_json(self.scene_path_7, scenes)
    # Used for clean_script()
    def process_action(self, actions, v_characters, v_actions):
        new_actions = []
        for item in actions:
            new_item = {}
            new_item['character'] = return_most_similar(item['character'], v_characters)
            new_item['state'] = return_most_similar(item['state'], ['standing', 'sitting'])
            new_item['action'] = return_most_similar(item['action'], v_actions)
            if new_item['state'] == "standing" and ("Standing" in new_item['action'] or new_item['action'] == "Joyful Jump" or new_item['action'] == "Sit Down"):
                if new_item['action'] == "Standing Talking":
                    new_item['action'] = "Standing Talking " + str(random.randint(1, 6))
                if new_item['action'] == "Standing Angry":
                    new_item['action'] = "Standing Angry " + str(random.randint(1, 4))
                if new_item['action'] == "Standing Arguing":
                    new_item['action'] = "Standing Arguing " + str(random.randint(1, 2))
                if new_item['action'] == "Standing Agree":
                    new_item['action'] = "Standing Agree " + str(random.randint(1, 2))
                new_actions.append(new_item)
            elif new_item['state'] == "sitting" and ("Sitting" in new_item['action'] or new_item['action'] == "Stand Up"):
                if new_item['action'] == "Sitting Talking":
                    new_item['action'] = "Sitting Talking " + str(random.randint(1, 2))
                new_actions.append(new_item)
            else:
                pass
        return new_actions
    # Used for clean_script()
    def process_shot(self, info, location, shot, v_shots):
        shot = return_most_similar(shot, v_shots)
        if shot == "Pan Shot":
            return "Pan Shot 1"
        elif shot == "Track Shot":
            return "Track Shot " + str(random.randint(1, int(info[location]['track'])))
        elif shot == "Long Shot":
            return "Long Shot " + str(random.randint(1, int(info[location]['long'])))
        else:
            return shot
    def clean_script(self):
        '''
            Description: Only keep the necessary information in the script and perform certain checks to avoid errors when executing the script in Unity.
        '''
        scenes = read_json(self.scene_path_7)
        profiles = read_json(self.profile_path)
        v_characters = [item['name'] for item in profiles]
        info = read_json(os.path.join(ROOT_PATH, "Locations\\rotateandtrack.json"))
        v_locations = [location for location in info.keys()]
        info_1 = read_json(os.path.join(ROOT_PATH, "Locations\\actions.json"))
        v_actions = [action for action in info_1.keys()]
        info_2 = read_json(os.path.join(ROOT_PATH, "Locations\\shots.json"))
        v_shots = [shot for shot in info_2.keys()]
        data = []
        for scene in scenes:
            new_scene = {}
            scene_information_key = return_most_similar('scene_information', list(scene.keys()))
            new_scene['scene information'] = scene[scene_information_key]
            # verify
            for role in new_scene['scene information']['who']:
                role = return_most_similar(role, v_characters)
            new_scene['scene information']['where'] = return_most_similar(new_scene['scene information']['where'], v_locations)
            # verify
            new_scene['scene'] = []
            for line in scene['dialogues']:
                new_line = {}
                selected_shot_key = return_most_similar('selected shot', list(line.keys()))
                current_position_key = return_most_similar('current position', list(line.keys()))
                # verify
                if 'speaker' in line.keys():
                    new_line['speaker'] = return_most_similar(line['speaker'], v_characters)
                    new_line['content'] = line['content']
                    new_line['actions'] = self.process_action(line['actions'], v_characters, v_actions)
                    new_line['shot'] = self.process_shot(info, scene[scene_information_key]['where'], line[selected_shot_key], v_shots)
                    new_line['current position'] = line[current_position_key]
                else:
                    new_line['move'] = {}
                    new_line['move']['character'] = return_most_similar(line['move']['character'], v_characters)
                    new_line['move']['destination'] = "Position " + str(get_number(line['move']['destination']))
                    new_line['shot'] = self.process_shot(info, scene[scene_information_key]['where'], line[selected_shot_key], v_shots)
                    new_line['current position'] = line[current_position_key]
                # verify
                # verify
                for item in new_line['current position']:
                    item['character'] = return_most_similar(item['character'], v_characters)
                    item['position'] = "Position " + str(get_number(item['position']))
                # verify
                new_scene['scene'].append(new_line)
            initial_position_key = return_most_similar('initial position', list(scene.keys()))
            new_scene['initial position'] = scene[initial_position_key]
            for ini in new_scene['initial position']:
                ini['character'] = return_most_similar(ini['character'], v_characters)
                ini['position'] = "Position " + str(get_number(ini['position']))
            data.append(new_scene)
        write_json(self.script_path, data)
if __name__ == '__main__':
    f = FilmCrafter(topic = "Reconcilation in a friend reunion")
    print("Characters selecting >>>")
    f.casting()
    print("Scenes planning >>>")
    f.scenes_plan()
    print("Lines generating >>>")
    f.lines_generate()
    print("Positions marking >>>")
    f.position_mark()
    print("Actions marking >>>")
    f.action_mark()
    print("Director discusses with screenwriter about the script >>>")
    f.stage1_verify()
    print("Actors give comments on the lines >>>")
    f.stage2_verify()
    print("Movement marking >>>")
    f.move_mark()
    print("Director discusses with cinematographer about the shots >>>")
    f.stage3_verify()
    print("Script cleaning >>>")
    f.clean_script()
FilmAgent/test_cot.py
New file
@@ -0,0 +1,81 @@
from util import *
from LLMCaller import *
from typing import Dict, List, Union
# TO DO
ROOT_PATH = "/path/to/FilmAgent"
# TO DO
topics=["Reconcilation in a friend reunion", "A quarrel and breakup scene", "Casual meet-up with an old friend", "Emergency meeting after a security breach", "Late night brainstorming for a startup", "Family argument during dinner", "Emotional farewell at the roadside", "Heated debate over investments in the office", "Heated family discussion ending in a heartfelt apology", "Office gossip turning into a major understanding", "Celebratory end of project cheers with team members", "Planning a secret escape from a mundane routine", "Unexpected guest crashes a small house party", "An employee's emotional breakdown after being terminated", "Confession of a long-held secret among close friends"]
class FilmCrafter:
    def __init__(self, topic: str, ID) -> None:
        self.topic = topic
        self.store_path = os.path.join(ROOT_PATH, f"store\cot\{ID}")
        self.log_path = os.path.join(self.store_path, "prompt.txt")
        self.profile_path = os.path.join(self.store_path, "actors_profile.json")
        self.action_description_path = os.path.join(ROOT_PATH, "Locations\\actions.txt")
        self.shot_description_path = os.path.join(ROOT_PATH, "Locations\\shots.txt")
        self.script_path = os.path.join(self.store_path, "script.json")
        # The maximum number of characters in a film
        self.character_limit = 4
        if not os.path.exists(self.store_path):
            os.makedirs(self.store_path)
    def call(self, identity: str, params: Dict, trans2json: bool = True) -> Union[str, dict, list]:
        prompt = read_prompt(os.path.join(ROOT_PATH, f"Prompt\COT_Prompt\{identity}.txt") )
        prompt = prompt_format(prompt, params)
        log_prompt(self.log_path, prompt)
        result = GPTCall(prompt)
        if trans2json:
            result = clean_text(result)
            result = GPTResponse2JSON(result)
        log_prompt(self.log_path, result)
        return result
    def casting(self):
        params = {"{topic}": self.topic, "{character_limit}": self.character_limit}
        result = self.call("director_1", params)
        write_json(self.profile_path, result)
    def script_(self):
        profile = read_json(self.profile_path)
        male_characters = ", ".join(list(map(lambda x: x['name'],
                                             filter(lambda x: x['gender'].lower() == 'male', profile))))
        female_characters = ", ".join(list(map(lambda x: x['name'],
                                               filter(lambda x: x['gender'].lower() == 'female', profile))))
        optional_positions = ""
        base_path = os.path.join(ROOT_PATH, "Locations")
        for entry in os.listdir(base_path):
            full_path = os.path.join(base_path, entry)
            if os.path.isdir(full_path):
                ps = json.dumps(read_json(os.path.join(full_path, "position.json")))
                optional_positions = optional_positions + f"**{entry}**: {ps}\n"
        all_actions = read_prompt(self.action_description_path)
        all_shots = read_prompt(self.shot_description_path)
        params = {"{topic}": self.topic,
                  "{male_characters}": male_characters,
                  "{female_characters}": female_characters,
                  "{profiles}": profile,
                  "{optional_positions}": optional_positions,
                  "{all_actions}": all_actions,
                  "{all_shots}": all_shots
                  }
        result = self.call("script", params)
        write_json(self.script_path, result)
if __name__ == '__main__':
    id=14
    f = FilmCrafter(topic = topics[id-1], ID=id)
    f.casting()
    f.script_()
FilmAgent/test_full.py
New file
@@ -0,0 +1,716 @@
from util import *
from LLMCaller import *
from typing import Dict, List, Union
import random
import copy
# TO DO
ROOT_PATH = "/path/to/FilmAgent"
ID = 15
# TO DO
topics=["Reconcilation in a friend reunion", "A quarrel and breakup scene", "Casual meet-up with an old friend", "Emergency meeting after a security breach", "Late night brainstorming for a startup", "Family argument during dinner", "Emotional farewell at the roadside", "Heated debate over investments in the office", "Heated family discussion ending in a heartfelt apology", "Office gossip turning into a major understanding", "Celebratory end of project cheers with team members", "Planning a secret escape from a mundane routine", "Unexpected guest crashes a small house party", "An employee's emotional breakdown after being terminated", "Confession of a long-held secret among close friends"]
class FilmCrafter:
    def __init__(self, topic: str) -> None:
        self.topic = topic
        self.store_path = os.path.join(ROOT_PATH, f"store\\full\{ID}")
        self.log_path = os.path.join(self.store_path, "prompt.txt")
        self.profile_path = os.path.join(self.store_path, "actors_profile.json")
        self.action_description_path = os.path.join(ROOT_PATH, "Locations\\actions.txt")
        self.shot_description_path = os.path.join(ROOT_PATH, "Locations\\shots.txt")
        # scenes
        self.scene_path = os.path.join(self.store_path, "scenes_1.json")
        # + lines
        self.scene_path_1 = os.path.join(self.store_path, "scenes_2.json")
        # + positions
        self.scene_path_2 = os.path.join(self.store_path, "scenes_3.json")
        # + actions
        self.scene_path_3 = os.path.join(self.store_path, "scenes_4.json")
        # stage1_verify
        self.scene_path_4 = os.path.join(self.store_path, "scenes_5.json")
        # stage2_verify
        self.scene_path_5 = os.path.join(self.store_path, "scenes_6.json")
        # + movement
        self.scene_path_6 = os.path.join(self.store_path, "scenes_7.json")
        # + shot (stage3_verify)
        self.scene_path_7 = os.path.join(self.store_path, "scenes_8.json")
        # The final script
        self.script_path = os.path.join(self.store_path, "script.json")
        # director's shot annotation
        self.director_shot_path = os.path.join(self.store_path, "director_shot.json")
        # cinematographer's shot annotation
        self.cinematographer_shot_path = os.path.join(self.store_path, "cinematographer_shot.json")
        # The maximum number of characters in a film
        self.character_limit = 4
        # The maximum number of scenes in a film
        self.scene_limit = 3
        # The maximum number of discussions between director and screenwriter
        self.stage1_verify_limit = 3
        # The maximum number of discussions between director, actor and screenwriter
        self.stage2_verify_limit = 3
        # The maximum number of discussions between director and cinematographer
        self.stage3_verify_limit = 4
        if not os.path.exists(self.store_path):
            os.makedirs(self.store_path)
    def call(self, identity: str, params: Dict, trans2json: bool = True) -> Union[str, dict, list]:
        prompt = read_prompt(os.path.join(ROOT_PATH, f"Prompt\{identity}.txt") )
        prompt = prompt_format(prompt, params)
        log_prompt(self.log_path, prompt)
        result = GPTCall(prompt)
        if trans2json:
            result = clean_text(result)
            result = GPTResponse2JSON(result)
        log_prompt(self.log_path, result)
        return result
    def casting(self):
        '''
            Role: Director
            Behavior: Create the main characters and their bios for the film script.
        '''
        params = {"{topic}": self.topic, "{character_limit}": self.character_limit}
        result = self.call("director_1", params)
        write_json(self.profile_path, result)
    def scenes_plan(self):
        '''
            Role: Director
            Behavior:
                Plan the outline of script, include:
                1. The number of scenes.
                2. The characters, location and main plot of each scene.
        '''
        profile = read_json(self.profile_path)
        male_characters = ", ".join(list(map(lambda x: x['name'],
                                             filter(lambda x: x['gender'].lower() == 'male', profile))))
        female_characters = ", ".join(list(map(lambda x: x['name'],
                                               filter(lambda x: x['gender'].lower() == 'female', profile))))
        params = {"{topic}": self.topic,
                  "{male_characters}": male_characters,
                  "{female_characters}": female_characters,
                  "{scene_limit}": self.scene_limit}
        result = self.call("director_2", params)
        write_json(self.scene_path, result)
    def lines_generate(self):
        '''
            Role: Screenwriter
            Behavior: Write lines for the script.
        '''
        scenes = read_json(self.scene_path)
        script_outline = ""
        who = []
        where = []
        what = []
        for id,scene in enumerate(scenes):
            selected_roles = scene[return_most_similar("selected-characters", list(scene.keys()))]
            selected_location = scene[return_most_similar("selected-location", list(scene.keys()))]
            story_plot = scene[return_most_similar("story-plot", list(scene.keys()))]
            who.append(selected_roles)
            where.append(selected_location)
            what.append(story_plot)
            topic = scene[return_most_similar("sub-topic", list(scene.keys()))]
            characters = ", ".join(selected_roles)
            plot = story_plot
            location = selected_location
            goal = scene[return_most_similar("dialogue-goal", list(scene.keys()))]
            script_outline = script_outline + f"{id + 1}. **Scene {id + 1}**:\n   - topic: {topic}\n   - involved characters: {characters}\n   - plot: {plot}\n   - location: {location}\n   - dialogue goal: {goal}\n\n"
        params = {"{script_outline}": script_outline.strip()}
        result = self.call("screenwriter_1", params)
        lines = []
        assert len(result) == len(scenes)
        for j in range(len(scenes)):
            line = {}
            line['scene_information'] = {}
            line['scene_information']['who'] = who[j]
            line['scene_information']['where'] = where[j]
            line['scene_information']['what'] = what[j]
            line['dialogues'] = result[j][return_most_similar("scene-dialogue", list(result[j].keys()))]
            lines.append(line)
        write_json(self.scene_path_1, lines)
    def position_mark(self):
        '''
            Role: Screenwriter
            Behavior: Choose an appropriate initial position for each character in each scene of the script.
        '''
        scenes = read_json(self.scene_path_1)
        script_information = ""
        optional_positions = ""
        for id,scene in enumerate(scenes):
            i = id + 1
            who = scene['scene_information']['who']
            where = scene['scene_information']['where']
            what = scene['scene_information']['what']
            script_information = script_information + f"{i}. **Scene {i}**:\n   - characters: {who}\n   - location: {where}\n   - plot: {what}\n\n"
            position_path = os.path.join(ROOT_PATH, f"Locations\{where}\position.json")
            positions = read_json(position_path)
            normal_position = [item for item in positions if item['fixed_angle'] == False]
            # This "if judgment" is related to the position, and camera settings in Unity.
            if len(who) >= len(positions) - len(normal_position) + 2:
                p = ""
                for it,position in enumerate(positions):
                    j = it + 1
                    p = p + f"   - Position {j}: " + position['description'] + '\n'
            else:
                p = ""
                for it,position in enumerate(normal_position):
                    j = it + 1
                    p = p + f"   - Position {j}: " + position['description'] + '\n'
            optional_positions = optional_positions + f"{i}. **Positions in {where}**:\n{p}\n"
        params = {"{script_information}": script_information.strip(),
                        "{optional_positions}": optional_positions.strip()}
        result = self.call("screenwriter_2", params)
        assert len(result) == len(scenes)
        for j in range(len(scenes)):
            scenes[j]["initial position"] = result[j][return_most_similar("scene-position", list(result[j].keys()))]
        write_json(self.scene_path_2, scenes)
    def action_mark(self):
        '''
            Role: Screenwriter
            Behavior: Choose appropriate actions for the characters engaged in the dialogue.
        '''
        scenes = read_json(self.scene_path_2)
        all_actions = read_prompt(self.action_description_path)
        data = []
        for scene in scenes:
            position_path = os.path.join(ROOT_PATH, f"Locations\{scene['scene_information']['where']}\position.json")
            positions = read_json(position_path)
            ini = ""
            for id,item in enumerate(scene['initial position']):
                if [it['sittable'] for it in positions if get_number(it['id']) == get_number(item['position'])][0]:
                    sit = "sittable"
                else:
                    sit = "unsittable"
                ini = ini + f"   - {item['character']}: " + f"{sit} {item['position']}, standing\n"
            ini = "   " + ini.strip()
            params = {"{initial}": ini,
                        "{plot}": scene['scene_information']['what'],
                        "{dialogues}": scene['dialogues'],
                        "{all_actions}": all_actions}
            result = self.call("screenwriter_3", params)
            assert len(result) == len(scene['dialogues'])
            scene['dialogues'] = result
            data.append(scene)
        write_json(self.scene_path_3, data)
    def find_unknown_actions(self, scenes: List) -> List:
        '''
            Input: The complete script
            Output: The list of actions appearing in the script that are not set in Unity.
        '''
        unknown_actions = []
        all_actions = read_json(os.path.join(ROOT_PATH, "Locations\\actions.json"))
        for scene in scenes:
            for line in scene['dialogues']:
                for action in line['actions']:
                    if action['action'] not in all_actions.keys() and action['action'] not in unknown_actions:
                        unknown_actions.append(action['action'])
        return unknown_actions
    def stage1_verify(self):
        '''
            Role: Director and Screenwriter
            Behavior: The director and screenwriter have a comprehensive discussion about the script to improve it, focusing on the following three aspects: Action Reasonableness, Theme Consistency, Script Fluency.
        '''
        scenes = read_json(self.scene_path_3)
        current_script = []
        unknown_actions = self.find_unknown_actions(scenes)
        characters_position = ""
        for id,scene in enumerate(scenes):
            new_scene = {}
            new_scene['scene_information'] = scene['scene_information']
            new_scene['initial position'] = scene['initial position']
            new_scene['dialogues'] = []
            for line in scene['dialogues']:
                new_line = copy.deepcopy(line)
                for action in new_line['actions']:
                    action.pop("reasoning")
                new_scene['dialogues'].append(new_line)
            current_script.append(new_scene)
            position_path = os.path.join(ROOT_PATH, f"Locations\{scene['scene_information']['where']}\position.json")
            positions = read_json(position_path)
            p = []
            for position in scene['initial position']:
                position_id = get_number(position['position'])
                sittable = "sittable" if positions[position_id-1]['sittable'] else "unsittable"
                p.append(f"{position['character']}'s position: {sittable}")
            characters_position = characters_position + f"{id+1}. **Scene {id+1}**:\n{', '.join(p)}\n\n"
        all_actions = read_prompt(self.action_description_path)
        for i in range(self.stage1_verify_limit):
            params = {"{theme}": self.topic,
                        "{original_script}": current_script,
                        "{all_actions}": all_actions,
                        "{unknown_actions}": ', '.join(unknown_actions)}
            feedback = self.call("director_3", params, trans2json=False)
            params = {"{theme}": self.topic,
                      "{feedback}": feedback,
                        "{script}": current_script,
                        "{all_actions}": all_actions,
                        "{characters_position}": characters_position}
            revised_script = self.call("screenwriter_4", params)
            current_script = revised_script
            unknown_actions = self.find_unknown_actions(revised_script)
            # If there are still unknown actions, discuss again immediately.
            if len(unknown_actions)>0:
                continue
            params = {"{feedback}": feedback,
                        "{revised_script}": revised_script}
            verify = self.call("director_4", params, trans2json=False)
            if verify.find("finalize") == -1:
                continue
            verify = verify[verify.find("finalize"):]
            if "True" in verify or "true" in verify:
                break
        write_json(self.scene_path_4, revised_script)
    def stage2_verify(self):
        '''
            Role: Actor, Director and Screenwriter
            Behavior: The actors suggest minor adjustments to the script lines, and the director and screenwriter discuss the revisions.
        '''
        scenes = read_json(self.scene_path_4)
        profiles = read_json(self.profile_path)
        feedback = {}
        scenes_for_actor = []
        for scene in scenes:
            item = {}
            item['scene_information'] = scene[return_most_similar('scene_information', list(scene.keys()))]
            item["dialogues"] = []
            for line in scene['dialogues']:
                new_line = {}
                new_line['speaker'] = line['speaker']
                new_line['content'] = line['content']
                item["dialogues"].append(new_line)
            scenes_for_actor.append(item)
        for profile in profiles:
            params = {"{character}": profile['name'],
                        "{profile}": profile,
                        "{script}": scenes_for_actor}
            result = self.call("actor", params, trans2json=False)
            feedback[profile['name']] = result
        suggestions = ""
        for name, suggestion in feedback.items():
            suggestions = suggestions + f"   - **{name}**: {suggestion}\n"
        params = {"{suggestions}": suggestions}
        result = self.call("director_5", params)
        if result[return_most_similar("adopted-suggestions", list(result.keys()))] == "None":
            write_json(self.scene_path_5, scenes)
        else:
            current_script = scenes_for_actor
            adopted_suggestions = result[return_most_similar("adopted-suggestions", list(result.keys()))]
            for sugg in adopted_suggestions:
                sugg.pop("reason")
            for i in range(self.stage2_verify_limit):
                params = {"{feedback}": adopted_suggestions,
                            "{script}": current_script}
                revised_script = self.call("screenwriter_5", params)
                current_script = revised_script
                params = {"{feedback}": adopted_suggestions,
                            "{revised_script}": revised_script}
                verify = self.call("director_6", params, trans2json=False)
                verify = verify[verify.find("finalize"):]
                if "True" in verify or "true" in verify:
                    break
            assert len(revised_script) == len(scenes)
            for id,scene in enumerate(scenes):
                assert len(scene['dialogues']) == len(revised_script[id]['dialogues'])
                for it,line in enumerate(scene['dialogues']):
                    assert line['speaker'] == revised_script[id]['dialogues'][it]['speaker']
                    line['content'] = revised_script[id]['dialogues'][it]['content']
            write_json(self.scene_path_5, scenes)
    def is_keep_standing(self, lines, character):
        '''
            Description: Check if the character remains standing throughout the script.
            Input: The complete script, a character's name
            Output: True or False
        '''
        for line in lines:
            actions = line['actions']
            for action in actions:
                if action['character'] == character and action['state'] == 'sitting':
                    return False
        return True
    def moveable_options(self, scene):
        '''
            Input: The complete script
            Output:
                1. All movable characters (i.e., the characters that remain standing throughout the script)
                2. All positions that character can move to (i.e., the unoccupied positions)
        '''
        position_path = os.path.join(ROOT_PATH, f"Locations\{scene[return_most_similar('scene_information', list(scene.keys()))]['where']}\position.json")
        positions = read_json(position_path)
        occupied_positions = [get_number(item['position']) for item in scene[return_most_similar('initial position', list(scene.keys()))]]
        unoccupied_positions = [f"{item['id']}: {item['description']}" for item in positions if get_number(item['id']) not in occupied_positions]
        if len(unoccupied_positions) == 0:
            return None, None
        who = scene[return_most_similar('scene_information', list(scene.keys()))]['who']
        moveable_characters = []
        for character in who:
            if self.is_keep_standing(scene['dialogues'], character):
                moveable_characters.append(character)
        if len(moveable_characters) == 0:
            return None, None
        return moveable_characters, unoccupied_positions
    def move_mark(self):
        '''
            Role: Director
            Behavior: The director adds appropriate character movements into the script.
        '''
        scenes = read_json(self.scene_path_5)
        data = []
        for scene in scenes:
            moveable_characters, unoccupied_positions = self.moveable_options(scene)
            moved_charatcter, moveto_position = None, None
            if moveable_characters:
                move2destination = ""
                for pn in unoccupied_positions:
                    move2destination = move2destination + f"   - {pn}\n"
                move2destination = "   " + move2destination.strip()
                lines = []
                for id in range(len(scene['dialogues'])):
                    lines.append(f"<Insertion Position {id}>")
                    item = {}
                    item['speaker'] = scene['dialogues'][id]['speaker']
                    item['content'] = scene['dialogues'][id]['content']
                    lines.append(item)
                params = {"{moveable_characters}": moveable_characters,
                                "{story}": scene[return_most_similar('scene_information', list(scene.keys()))]['what'],
                                "{lines}": lines,
                                "{destinations}": move2destination,
                                "{current_positions}": scene[return_most_similar('initial position', list(scene.keys()))]}
                result = self.call("director_7", params)
                if 'insertion' in result.keys():
                    moved_charatcter = result['move']['character']
                    moveto_position = result['move']['destination']
                    scene['dialogues'].insert(get_number(result['insertion'][return_most_similar('insertion position', list(result['insertion'].keys()))]), result)
            # Update the characters' position in real time
            position_change = False
            for line in scene['dialogues']:
                if "move" not in line.keys():
                    line['current position'] = scene[return_most_similar('initial position', list(scene.keys()))]
                else:
                    position_change = True
                    line['current position'] = scene[return_most_similar('initial position', list(scene.keys()))]
                    continue
                if position_change:
                    line['current position'] = [item if item['character'] !=  moved_charatcter else {'character': moved_charatcter, 'position': moveto_position} for item in line['current position']]
            data.append(scene)
        write_json(self.scene_path_6, data)
    def shot_mark(self):
        '''
            Input: None
            Output:
                1. Director's shot annotations
                2. Cinematographer's shot annotations
                3. The complete script before adding shot annotations
                4. The script after inserting the shot annotation points.
        '''
        scenes = read_json(self.scene_path_6)
        script = {}
        for ID,scene in enumerate(scenes):
            I = ID + 1
            script[f'scene {I}'] = []
            for id,item in enumerate(scene['dialogues']):
                line = {}
                i = id + 1
                if "speaker" in item.keys():
                    line['dialogue'] = f"{item['speaker']}: {item['content']}"
                    line['actions'] = item['actions']
                    line[f'selected-shot-{i}'] = "..."
                else:
                    line['move'] = {}
                    line['move']['character'] = item['move']['character']
                    line['move']['destination'] = item['move']['destination']
                    line[f'selected-shot-{i}'] = "..."
                script[f'scene {I}'].append(line)
        all_shots = read_prompt(self.shot_description_path)
        params = {"{script}": script, "{all_shots}": all_shots}
        result1 = self.call("cinematographer", params)
        result2 = self.call("director_8", params)
        for scene_id, scene in result1.items():
            for shot_id, shot in scene.items():
                shot.pop("reasoning")
        for scene_id, scene in result2.items():
            for shot_id, shot in scene.items():
                shot.pop("reasoning")
        write_json(self.director_shot_path, result2)
        write_json(self.cinematographer_shot_path, result1)
        return script, result1, result2, scenes
    def revise_shot_annotation(self, src, feedback):
        '''
            Input: Original shot annotation, revision suggestion
            Output: Revised shot annotation
        '''
        new = src
        for scene_id, scene in new.items():
            for shot_id, shot in scene.items():
                if shot['shot'] != feedback[scene_id][shot_id]['shot']:
                    continue
                need_update = feedback[scene_id][shot_id][return_most_similar("need update", list(feedback[scene_id][shot_id].keys()))]
                if isinstance(need_update, str) and need_update.lower() == "false":
                    continue
                if isinstance(need_update, bool) and not need_update:
                    continue
                shot['shot'] = feedback[scene_id][shot_id][return_most_similar("updated shot", list(feedback[scene_id][shot_id].keys()))]
        return new
    def stage3_verify(self):
        '''
            Role: Director and Cinematographer
            Behavior: The director and the cinematographer provide their own shot annotations, then discuss and revise them together, and finally, the director selects the better one.
        '''
        script, shot_mark_cinematographer, shot_mark_director, scenes = self.shot_mark()
        current_shot_c, current_shot_d = shot_mark_cinematographer, shot_mark_director
        all_shots = read_prompt(self.shot_description_path)
        for i in range(self.stage3_verify_limit):
            params = {"{identity_1}": "Director",
                      "{identity_2}": "Cinematographer",
                      "{script}": script,
                      "{shot_annotation}": current_shot_c,
                      "{all_shots}": all_shots
                      }
            result1 = self.call("shot_review", params)
            current_shot_c = self.revise_shot_annotation(current_shot_c, result1)
            params = {"{identity_1}": "Cinematographer",
                      "{identity_2}": "Director",
                      "{script}": script,
                      "{shot_annotation}": current_shot_d,
                      "{all_shots}": all_shots
                      }
            result2 = self.call("shot_review", params)
            current_shot_d = self.revise_shot_annotation(current_shot_d, result2)
        params = {"{shot_annotation_1}": current_shot_d,
                    "{shot_annotation_2}": current_shot_c,
                    "{script}": script,
                    "{all_shots}": all_shots
                    }
        result = self.call("director_9", params)
        last_shots = current_shot_d if result['better'].lower()=="director" else current_shot_c
        assert len(list(last_shots.keys())) == len(scenes)
        for id in range(len(list(last_shots.keys()))):
            i = id + 1
            assert len(list(last_shots[f'scene {i}'].keys())) == len(scenes[id]['dialogues'])
            for key,value in last_shots[f'scene {i}'].items():
                scenes[id]['dialogues'][get_number(key)-1]['selected shot'] = value[return_most_similar('shot', list(value.keys()))]
        write_json(self.scene_path_7, scenes)
    # Used for clean_script()
    def process_action(self, actions, v_characters, v_actions):
        new_actions = []
        for item in actions:
            new_item = {}
            new_item['character'] = return_most_similar(item['character'], v_characters)
            new_item['state'] = return_most_similar(item['state'], ['standing', 'sitting'])
            new_item['action'] = return_most_similar(item['action'], v_actions)
            if new_item['state'] == "standing" and ("Standing" in new_item['action'] or new_item['action'] == "Joyful Jump" or new_item['action'] == "Sit Down"):
                if new_item['action'] == "Standing Talking":
                    new_item['action'] = "Standing Talking " + str(random.randint(1, 6))
                if new_item['action'] == "Standing Angry":
                    new_item['action'] = "Standing Angry " + str(random.randint(1, 4))
                if new_item['action'] == "Standing Arguing":
                    new_item['action'] = "Standing Arguing " + str(random.randint(1, 2))
                if new_item['action'] == "Standing Agree":
                    new_item['action'] = "Standing Agree " + str(random.randint(1, 2))
                new_actions.append(new_item)
            elif new_item['state'] == "sitting" and ("Sitting" in new_item['action'] or new_item['action'] == "Stand Up"):
                if new_item['action'] == "Sitting Talking":
                    new_item['action'] = "Sitting Talking " + str(random.randint(1, 2))
                new_actions.append(new_item)
            else:
                pass
        return new_actions
    # Used for clean_script()
    def process_shot(self, info, location, shot, v_shots):
        shot = return_most_similar(shot, v_shots)
        if shot == "Pan Shot":
            return "Pan Shot 1"
        elif shot == "Track Shot":
            return "Track Shot " + str(random.randint(1, int(info[location]['track'])))
        elif shot == "Long Shot":
            return "Long Shot " + str(random.randint(1, int(info[location]['long'])))
        else:
            return shot
    def clean_script(self):
        '''
            Description: Only keep the necessary information in the script and perform certain checks to avoid errors when executing the script in Unity.
        '''
        scenes = read_json(self.scene_path_7)
        profiles = read_json(self.profile_path)
        v_characters = [item['name'] for item in profiles]
        info = read_json(os.path.join(ROOT_PATH, "Locations\\rotateandtrack.json"))
        v_locations = [location for location in info.keys()]
        info_1 = read_json(os.path.join(ROOT_PATH, "Locations\\actions.json"))
        v_actions = [action for action in info_1.keys()]
        info_2 = read_json(os.path.join(ROOT_PATH, "Locations\\shots.json"))
        v_shots = [shot for shot in info_2.keys()]
        data = []
        for scene in scenes:
            new_scene = {}
            scene_information_key = return_most_similar('scene_information', list(scene.keys()))
            new_scene['scene information'] = scene[scene_information_key]
            # verify
            for role in new_scene['scene information']['who']:
                role = return_most_similar(role, v_characters)
            new_scene['scene information']['where'] = return_most_similar(new_scene['scene information']['where'], v_locations)
            # verify
            new_scene['scene'] = []
            for line in scene['dialogues']:
                new_line = {}
                selected_shot_key = return_most_similar('selected shot', list(line.keys()))
                current_position_key = return_most_similar('current position', list(line.keys()))
                # verify
                if 'speaker' in line.keys():
                    new_line['speaker'] = return_most_similar(line['speaker'], v_characters)
                    new_line['content'] = line['content']
                    new_line['actions'] = self.process_action(line['actions'], v_characters, v_actions)
                    new_line['shot'] = self.process_shot(info, scene[scene_information_key]['where'], line[selected_shot_key], v_shots)
                    new_line['current position'] = line[current_position_key]
                else:
                    new_line['move'] = {}
                    new_line['move']['character'] = return_most_similar(line['move']['character'], v_characters)
                    new_line['move']['destination'] = "Position " + str(get_number(line['move']['destination']))
                    new_line['shot'] = self.process_shot(info, scene[scene_information_key]['where'], line[selected_shot_key], v_shots)
                    new_line['current position'] = line[current_position_key]
                # verify
                # verify
                for item in new_line['current position']:
                    item['character'] = return_most_similar(item['character'], v_characters)
                    item['position'] = "Position " + str(get_number(item['position']))
                # verify
                new_scene['scene'].append(new_line)
            initial_position_key = return_most_similar('initial position', list(scene.keys()))
            new_scene['initial position'] = scene[initial_position_key]
            for ini in new_scene['initial position']:
                ini['character'] = return_most_similar(ini['character'], v_characters)
                ini['position'] = "Position " + str(get_number(ini['position']))
            data.append(new_scene)
        write_json(self.script_path, data)
if __name__ == '__main__':
    f = FilmCrafter(topic = topics[ID-1])
    print("Characters selecting >>>")
    f.casting()
    print("Scenes planning >>>")
    f.scenes_plan()
    print("Lines generating >>>")
    f.lines_generate()
    print("Positions marking >>>")
    f.position_mark()
    print("Actions marking >>>")
    f.action_mark()
    print("Director discusses with screenwriter about the script >>>")
    f.stage1_verify()
    print("Actors give comments on the lines >>>")
    f.stage2_verify()
    print("Movement marking >>>")
    f.move_mark()
    print("Director discusses with cinematographer about the shots >>>")
    f.stage3_verify()
    print("Script cleaning >>>")
    f.clean_script()
FilmAgent/test_no_interation.py
New file
@@ -0,0 +1,487 @@
from util import *
from LLMCaller import *
from typing import Dict, List, Union
import random
import copy
# TO DO
ROOT_PATH = "/path/to/FilmAgent"
ID = 13
# TO DO
topics=["Reconcilation in a friend reunion", "A quarrel and breakup scene", "Casual meet-up with an old friend", "Emergency meeting after a security breach", "Late night brainstorming for a startup", "Family argument during dinner", "Emotional farewell at the roadside", "Heated debate over investments in the office", "Heated family discussion ending in a heartfelt apology", "Office gossip turning into a major understanding", "Celebratory end of project cheers with team members", "Planning a secret escape from a mundane routine", "Unexpected guest crashes a small house party", "An employee's emotional breakdown after being terminated", "Confession of a long-held secret among close friends"]
class FilmCrafter:
    def __init__(self, topic: str) -> None:
        self.topic = topic
        self.store_path = os.path.join(ROOT_PATH, f"store\\no_interation\{ID}")
        self.log_path = os.path.join(self.store_path, "prompt.txt")
        self.profile_path = os.path.join(self.store_path, "actors_profile.json")
        self.action_description_path = os.path.join(ROOT_PATH, "Locations\\actions.txt")
        self.shot_description_path = os.path.join(ROOT_PATH, "Locations\\shots.txt")
        # scenes
        self.scene_path = os.path.join(self.store_path, "scenes_1.json")
        # + lines
        self.scene_path_1 = os.path.join(self.store_path, "scenes_2.json")
        # + positions
        self.scene_path_2 = os.path.join(self.store_path, "scenes_3.json")
        # + actions
        self.scene_path_3 = os.path.join(self.store_path, "scenes_4.json")
        # + movement
        self.scene_path_4 = os.path.join(self.store_path, "scenes_5.json")
        # + shot (stage3_verify)
        self.scene_path_5 = os.path.join(self.store_path, "scenes_6.json")
        # The final script
        self.script_path = os.path.join(self.store_path, "script.json")
        # The maximum number of characters in a film
        self.character_limit = 4
        # The maximum number of scenes in a film
        self.scene_limit = 3
        # The maximum number of discussions between director and screenwriter
        self.stage1_verify_limit = 3
        # The maximum number of discussions between director, actor and screenwriter
        self.stage2_verify_limit = 3
        # The maximum number of discussions between director and cinematographer
        self.stage3_verify_limit = 3
        if not os.path.exists(self.store_path):
            os.makedirs(self.store_path)
    def call(self, identity: str, params: Dict, trans2json: bool = True) -> Union[str, dict, list]:
        prompt = read_prompt(os.path.join(ROOT_PATH, f"Prompt\{identity}.txt") )
        prompt = prompt_format(prompt, params)
        log_prompt(self.log_path, prompt)
        result = GPTCall(prompt)
        if trans2json:
            result = clean_text(result)
            result = GPTResponse2JSON(result)
        log_prompt(self.log_path, result)
        return result
    def casting(self):
        '''
            Role: Director
            Behavior: Create the main characters and their bios for the film script.
        '''
        params = {"{topic}": self.topic, "{character_limit}": self.character_limit}
        result = self.call("director_1", params)
        write_json(self.profile_path, result)
    def scenes_plan(self):
        '''
            Role: Director
            Behavior:
                Plan the outline of script, include:
                1. The number of scenes.
                2. The characters, location and main plot of each scene.
        '''
        profile = read_json(self.profile_path)
        male_characters = ", ".join(list(map(lambda x: x['name'],
                                             filter(lambda x: x['gender'].lower() == 'male', profile))))
        female_characters = ", ".join(list(map(lambda x: x['name'],
                                               filter(lambda x: x['gender'].lower() == 'female', profile))))
        params = {"{topic}": self.topic,
                  "{male_characters}": male_characters,
                  "{female_characters}": female_characters,
                  "{scene_limit}": self.scene_limit}
        result = self.call("director_2", params)
        write_json(self.scene_path, result)
    def lines_generate(self):
        '''
            Role: Screenwriter
            Behavior: Write lines for the script.
        '''
        scenes = read_json(self.scene_path)
        script_outline = ""
        who = []
        where = []
        what = []
        for id,scene in enumerate(scenes):
            selected_roles = scene[return_most_similar("selected-characters", list(scene.keys()))]
            selected_location = scene[return_most_similar("selected-location", list(scene.keys()))]
            story_plot = scene[return_most_similar("story-plot", list(scene.keys()))]
            who.append(selected_roles)
            where.append(selected_location)
            what.append(story_plot)
            topic = scene[return_most_similar("sub-topic", list(scene.keys()))]
            characters = ", ".join(selected_roles)
            plot = story_plot
            location = selected_location
            goal = scene[return_most_similar("dialogue-goal", list(scene.keys()))]
            script_outline = script_outline + f"{id + 1}. **Scene {id + 1}**:\n   - topic: {topic}\n   - involved characters: {characters}\n   - plot: {plot}\n   - location: {location}\n   - dialogue goal: {goal}\n\n"
        params = {"{script_outline}": script_outline.strip()}
        result = self.call("screenwriter_1", params)
        lines = []
        assert len(result) == len(scenes)
        for j in range(len(scenes)):
            line = {}
            line['scene_information'] = {}
            line['scene_information']['who'] = who[j]
            line['scene_information']['where'] = where[j]
            line['scene_information']['what'] = what[j]
            line['dialogues'] = result[j][return_most_similar("scene-dialogue", list(result[j].keys()))]
            lines.append(line)
        write_json(self.scene_path_1, lines)
    def position_mark(self):
        '''
            Role: Screenwriter
            Behavior: Choose an appropriate initial position for each character in each scene of the script.
        '''
        scenes = read_json(self.scene_path_1)
        script_information = ""
        optional_positions = ""
        for id,scene in enumerate(scenes):
            i = id + 1
            who = scene['scene_information']['who']
            where = scene['scene_information']['where']
            what = scene['scene_information']['what']
            script_information = script_information + f"{i}. **Scene {i}**:\n   - characters: {who}\n   - location: {where}\n   - plot: {what}\n\n"
            position_path = os.path.join(ROOT_PATH, f"Locations\{where}\position.json")
            positions = read_json(position_path)
            normal_position = [item for item in positions if item['fixed_angle'] == False]
            # This "if judgment" is related to the position, and camera settings in Unity.
            if len(who) >= len(positions) - len(normal_position) + 2:
                p = ""
                for it,position in enumerate(positions):
                    j = it + 1
                    p = p + f"   - Position {j}: " + position['description'] + '\n'
            else:
                p = ""
                for it,position in enumerate(normal_position):
                    j = it + 1
                    p = p + f"   - Position {j}: " + position['description'] + '\n'
            optional_positions = optional_positions + f"{i}. **Positions in {where}**:\n{p}\n"
        params = {"{script_information}": script_information.strip(),
                        "{optional_positions}": optional_positions.strip()}
        result = self.call("screenwriter_2", params)
        assert len(result) == len(scenes)
        for j in range(len(scenes)):
            scenes[j]["initial position"] = result[j][return_most_similar("scene-position", list(result[j].keys()))]
        write_json(self.scene_path_2, scenes)
    def action_mark(self):
        '''
            Role: Screenwriter
            Behavior: Choose appropriate actions for the characters engaged in the dialogue.
        '''
        scenes = read_json(self.scene_path_2)
        all_actions = read_prompt(self.action_description_path)
        data = []
        for scene in scenes:
            position_path = os.path.join(ROOT_PATH, f"Locations\{scene['scene_information']['where']}\position.json")
            positions = read_json(position_path)
            ini = ""
            for id,item in enumerate(scene['initial position']):
                if [it['sittable'] for it in positions if get_number(it['id']) == get_number(item['position'])][0]:
                    sit = "sittable"
                else:
                    sit = "unsittable"
                ini = ini + f"   - {item['character']}: " + f"{sit} {item['position']}, standing\n"
            ini = "   " + ini.strip()
            params = {"{initial}": ini,
                        "{plot}": scene['scene_information']['what'],
                        "{dialogues}": scene['dialogues'],
                        "{all_actions}": all_actions}
            result = self.call("screenwriter_3", params)
            assert len(result) == len(scene['dialogues'])
            scene['dialogues'] = result
            data.append(scene)
        write_json(self.scene_path_3, data)
    def is_keep_standing(self, lines, character):
        '''
            Description: Check if the character remains standing throughout the script.
            Input: The complete script, a character's name
            Output: True or False
        '''
        for line in lines:
            actions = line['actions']
            for action in actions:
                if action['character'] == character and action['state'] == 'sitting':
                    return False
        return True
    def moveable_options(self, scene):
        '''
            Input: The complete script
            Output:
                1. All movable characters (i.e., the characters that remain standing throughout the script)
                2. All positions that character can move to (i.e., the unoccupied positions)
        '''
        position_path = os.path.join(ROOT_PATH, f"Locations\{scene[return_most_similar('scene_information', list(scene.keys()))]['where']}\position.json")
        positions = read_json(position_path)
        occupied_positions = [get_number(item['position']) for item in scene[return_most_similar('initial position', list(scene.keys()))]]
        unoccupied_positions = [f"{item['id']}: {item['description']}" for item in positions if get_number(item['id']) not in occupied_positions]
        if len(unoccupied_positions) == 0:
            return None, None
        who = scene[return_most_similar('scene_information', list(scene.keys()))]['who']
        moveable_characters = []
        for character in who:
            if self.is_keep_standing(scene['dialogues'], character):
                moveable_characters.append(character)
        if len(moveable_characters) == 0:
            return None, None
        return moveable_characters, unoccupied_positions
    def move_mark(self):
        '''
            Role: Director
            Behavior: The director adds appropriate character movements into the script.
        '''
        scenes = read_json(self.scene_path_3)
        data = []
        for scene in scenes:
            moveable_characters, unoccupied_positions = self.moveable_options(scene)
            moved_charatcter, moveto_position = None, None
            if moveable_characters:
                move2destination = ""
                for pn in unoccupied_positions:
                    move2destination = move2destination + f"   - {pn}\n"
                move2destination = "   " + move2destination.strip()
                lines = []
                for id in range(len(scene['dialogues'])):
                    lines.append(f"<Insertion Position {id}>")
                    item = {}
                    item['speaker'] = scene['dialogues'][id]['speaker']
                    item['content'] = scene['dialogues'][id]['content']
                    lines.append(item)
                params = {"{moveable_characters}": moveable_characters,
                                "{story}": scene[return_most_similar('scene_information', list(scene.keys()))]['what'],
                                "{lines}": lines,
                                "{destinations}": move2destination,
                                "{current_positions}": scene[return_most_similar('initial position', list(scene.keys()))]}
                result = self.call("director_7", params)
                if 'insertion' in result.keys():
                    moved_charatcter = result['move']['character']
                    moveto_position = result['move']['destination']
                    scene['dialogues'].insert(get_number(result['insertion'][return_most_similar('insertion position', list(result['insertion'].keys()))]), result)
            # Update the characters' position in real time
            position_change = False
            for line in scene['dialogues']:
                if "move" not in line.keys():
                    line['current position'] = scene[return_most_similar('initial position', list(scene.keys()))]
                else:
                    position_change = True
                    line['current position'] = scene[return_most_similar('initial position', list(scene.keys()))]
                    continue
                if position_change:
                    line['current position'] = [item if item['character'] !=  moved_charatcter else {'character': moved_charatcter, 'position': moveto_position} for item in line['current position']]
            data.append(scene)
        write_json(self.scene_path_4, data)
    def shot_mark(self):
        '''
            Input: None
            Output:
                1. Director's shot annotations
                2. Cinematographer's shot annotations
                3. The complete script before adding shot annotations
                4. The script after inserting the shot annotation points.
        '''
        scenes = read_json(self.scene_path_4)
        script = {}
        for ID,scene in enumerate(scenes):
            I = ID + 1
            script[f'scene {I}'] = []
            for id,item in enumerate(scene['dialogues']):
                line = {}
                i = id + 1
                if "speaker" in item.keys():
                    line['dialogue'] = f"{item['speaker']}: {item['content']}"
                    line['actions'] = item['actions']
                    # line['plot'] = ' '.join([it['reason'] for it in item['actions']])
                    line[f'selected-shot-{i}'] = "..."
                else:
                    line['move'] = {}
                    line['move']['character'] = item['move']['character']
                    line['move']['destination'] = item['move']['destination']
                    line[f'selected-shot-{i}'] = "..."
                script[f'scene {I}'].append(line)
        all_shots = read_prompt(self.shot_description_path)
        params = {"{script}": script, "{all_shots}": all_shots}
        result1 = self.call("cinematographer", params)
        for scene_id, scene in result1.items():
            for shot_id, shot in scene.items():
                shot.pop("reasoning")
        assert len(list(result1.keys())) == len(scenes)
        for id in range(len(list(result1.keys()))):
            i = id + 1
            assert len(list(result1[f'scene {i}'].keys())) == len(scenes[id]['dialogues'])
            for key,value in result1[f'scene {i}'].items():
                scenes[id]['dialogues'][get_number(key)-1]['selected shot'] = value[return_most_similar('shot', list(value.keys()))]
        write_json(self.scene_path_5, scenes)
    # Used for clean_script()
    def process_action(self, actions, v_characters, v_actions):
        new_actions = []
        for item in actions:
            new_item = {}
            new_item['character'] = return_most_similar(item['character'], v_characters)
            new_item['state'] = return_most_similar(item['state'], ['standing', 'sitting'])
            new_item['action'] = return_most_similar(item['action'], v_actions)
            if new_item['state'] == "standing" and ("Standing" in new_item['action'] or new_item['action'] == "Joyful Jump" or new_item['action'] == "Sit Down"):
                if new_item['action'] == "Standing Talking":
                    new_item['action'] = "Standing Talking " + str(random.randint(1, 6))
                if new_item['action'] == "Standing Angry":
                    new_item['action'] = "Standing Angry " + str(random.randint(1, 4))
                if new_item['action'] == "Standing Arguing":
                    new_item['action'] = "Standing Arguing " + str(random.randint(1, 2))
                if new_item['action'] == "Standing Agree":
                    new_item['action'] = "Standing Agree " + str(random.randint(1, 2))
                new_actions.append(new_item)
            elif new_item['state'] == "sitting" and ("Sitting" in new_item['action'] or new_item['action'] == "Stand Up"):
                if new_item['action'] == "Sitting Talking":
                    new_item['action'] = "Sitting Talking " + str(random.randint(1, 2))
                new_actions.append(new_item)
            else:
                pass
        return new_actions
    # Used for clean_script()
    def process_shot(self, info, location, shot, v_shots):
        shot = return_most_similar(shot, v_shots)
        if shot == "Pan Shot":
            return "Pan Shot 1"
        elif shot == "Track Shot":
            return "Track Shot " + str(random.randint(1, int(info[location]['track'])))
        elif shot == "Long Shot":
            return "Long Shot " + str(random.randint(1, int(info[location]['long'])))
        else:
            return shot
    def clean_script(self):
        '''
            Description: Only keep the necessary information in the script and perform certain checks to avoid errors when executing the script in Unity.
        '''
        scenes = read_json(self.scene_path_5)
        profiles = read_json(self.profile_path)
        v_characters = [item['name'] for item in profiles]
        info = read_json(os.path.join(ROOT_PATH, "Locations\\rotateandtrack.json"))
        v_locations = [location for location in info.keys()]
        info_1 = read_json(os.path.join(ROOT_PATH, "Locations\\actions.json"))
        v_actions = [action for action in info_1.keys()]
        info_2 = read_json(os.path.join(ROOT_PATH, "Locations\\shots.json"))
        v_shots = [shot for shot in info_2.keys()]
        data = []
        for scene in scenes:
            new_scene = {}
            scene_information_key = return_most_similar('scene_information', list(scene.keys()))
            new_scene['scene information'] = scene[scene_information_key]
            # verify
            for role in new_scene['scene information']['who']:
                role = return_most_similar(role, v_characters)
            new_scene['scene information']['where'] = return_most_similar(new_scene['scene information']['where'], v_locations)
            # verify
            new_scene['scene'] = []
            for line in scene['dialogues']:
                new_line = {}
                selected_shot_key = return_most_similar('selected shot', list(line.keys()))
                current_position_key = return_most_similar('current position', list(line.keys()))
                # verify
                if 'speaker' in line.keys():
                    new_line['speaker'] = return_most_similar(line['speaker'], v_characters)
                    new_line['content'] = line['content']
                    new_line['actions'] = self.process_action(line['actions'], v_characters, v_actions)
                    new_line['shot'] = self.process_shot(info, scene[scene_information_key]['where'], line[selected_shot_key], v_shots)
                    new_line['current position'] = line[current_position_key]
                else:
                    new_line['move'] = {}
                    new_line['move']['character'] = return_most_similar(line['move']['character'], v_characters)
                    new_line['move']['destination'] = "Position " + str(get_number(line['move']['destination']))
                    new_line['shot'] = self.process_shot(info, scene[scene_information_key]['where'], line[selected_shot_key], v_shots)
                    new_line['current position'] = line[current_position_key]
                # verify
                # verify
                for item in new_line['current position']:
                    item['character'] = return_most_similar(item['character'], v_characters)
                    item['position'] = "Position " + str(get_number(item['position']))
                # verify
                new_scene['scene'].append(new_line)
            initial_position_key = return_most_similar('initial position', list(scene.keys()))
            new_scene['initial position'] = scene[initial_position_key]
            for ini in new_scene['initial position']:
                ini['character'] = return_most_similar(ini['character'], v_characters)
                ini['position'] = "Position " + str(get_number(ini['position']))
            data.append(new_scene)
        write_json(self.script_path, data)
if __name__ == '__main__':
    f = FilmCrafter(topic = topics[ID-1])
    print("Characters selecting >>>")
    f.casting()
    print("Scenes planning >>>")
    f.scenes_plan()
    print("Lines generating >>>")
    f.lines_generate()
    print("Positions marking >>>")
    f.position_mark()
    print("Actions marking >>>")
    f.action_mark()
    print("Movement marking >>>")
    f.move_mark()
    print("Shots marking >>>")
    f.shot_mark()
    print("Script cleaning >>>")
    f.clean_script()
FilmAgent/util.py
New file
@@ -0,0 +1,163 @@
import json
import os
import re
import Levenshtein
from LLMCaller import *
def read_json(input_path):
    with open(input_path, 'r', encoding='utf-8',errors='ignore') as f:
        r = toString(json.load(f))
        r = r.replace("�",".")
        return json.loads(r)
def write_json(output_path, output_data):
    with open(output_path, 'w', encoding='utf-8') as f:
        json.dump(output_data, f, ensure_ascii=False)
def read_prompt(input_path):
    with open(input_path, 'r', encoding='utf-8') as f:
        return f.read()
def log_prompt(prompt_log_path, input):
    if not isinstance(input, str):
        input = toString(input)
    with open(prompt_log_path, "a", encoding="utf-8") as log_file:
        log_file.write(f"{input}\n")
        log_file.write("#######################################################\n")
def cretae_new_path(path, filetype):
    if not os.path.exists(path):
        os.makedirs(path)
    files = os.listdir(path)
    if len(files) == 0:
        return os.path.join(path, f'0.{filetype}')
    else:
        max = 0
        for file in files:
            max = max if max>=int(os.path.splitext(file)[0]) else int(os.path.splitext(file)[0])
        return os.path.join(path, str(max+1) + f'.{filetype}')
def find_latest_file(path):
    files = os.listdir(path)
    max = 0
    f = ""
    for file in files:
        if max < int(os.path.splitext(file)[0]):
            max = int(os.path.splitext(file)[0])
            f = file
    return os.path.join(path, f)
def toString(input):
    return json.dumps(input, ensure_ascii=False, separators=(",", ":"))
def prompt_format(prompt, params):
    text = prompt
    for key, value in params.items():
        if isinstance(value, (dict, list)):
            value = toString(value)
        if isinstance(value, (int, float)):
            value = str(value)
        text = text.replace(key, value)
    return text
def GPTResponse2JSON(response):
    json_string = response
    prompt = f"Modify the following string so that it can be correctly parsed by the json.loads() method:\n{json_string}\n\nYou should just return the modified string."
    if "```json" in json_string:
        json_string = json_string.replace("```","")
        json_string = json_string.replace("json","")
        json_string = json_string.strip()
    try:
        result = json.loads(json_string)
    except:
        result = json.loads(clean_text(GPTCall(prompt)))
    return result
def clean_text(text):
    # Only keep json content
    pattern = r"```json(.*?)```"
    match = re.search(pattern, text, re.DOTALL)
    if match:
        text =  match.group(1)
    # Remove some unexpected characters
    punctuation_map = {
        ",": ",",
        "。": ".",
        "!": "!",
        "?": "?",
        ":": ":",
        ";": ";",
        "“": "\"",
        "”": "\"",
        "‘": "\'",
        "’": "\'",
        "(": "(",
        ")": ")",
        "【": "[",
        "】": "]",
        "——": "-",
        "…": "...",
        "–": "-",
        "—": "-",
        "�": "."
    }
    pattern = r'[^a-zA-Z0-9\s\.,!?;:\'"\-({})\[\]]'
    for chinese, english in punctuation_map.items():
        text = text.replace(chinese, english)
    text = re.sub(pattern, '', text)
    text = text.strip()
    return text
def get_number(text):
    pattern = r'[^0-9]'
    text = re.sub(pattern, '', text)
    return int(text)
def contains_digit(string):
    return bool(re.search(r'\d', string))
def translate_digit(string):
    prompt = f"Convert the numbers in the following sentence into correct English expressions:\n\n{string}\n\nYour answer should only contain the following JSON content:\n" + '{"Converted-sentence": "..."}'
    result = GPTResponse2JSON(GPTCall(prompt))
    return list(result.values())[0]
def calculate_similarity(str1, str2):
    distance = Levenshtein.distance(str1.lower(), str2.lower())
    max_len = max(len(str1), len(str2))
    similarity = 1 - distance / max_len
    return similarity
def return_most_similar(string, string_list):
    max_similarity = 0
    tgt = 0
    for id,item in enumerate(string_list):
        current_similarity = calculate_similarity(string, item)
        if current_similarity > max_similarity:
            max_similarity = current_similarity
            tgt = id
    return string_list[tgt]
def GetValueFromDictArray(dictarray, key1, key2, value1):
    for item in dictarray:
        if item[key1] == value1:
            return item[key2]
TTS/env_tts.txt
New file
@@ -0,0 +1,141 @@
aiofiles==23.2.1
altair==5.3.0
annotated-types==0.7.0
antlr4-python3-runtime==4.9.3
anyio==4.4.0
asttokens==2.4.1
attrs==23.2.0
av==12.1.0
cdifflib==1.2.6
certifi==2024.6.2
cffi==1.16.0
charset-normalizer==3.3.2
chattts @ git+https://github.com/2noise/ChatTTS@8397c5e8ee307e3d71ff6544bfd4641035482eba
click==8.1.7
contourpy==1.2.1
cycler==0.12.1
Cython==3.0.10
decorator==5.1.1
dnspython==2.6.1
editdistance==0.8.1
einops==0.8.0
einx==0.3.0
email_validator==2.2.0
encodec==0.1.1
exceptiongroup==1.2.1
executing==2.0.1
fastapi==0.111.0
fastapi-cli==0.0.4
ffmpy==0.3.2
filelock==3.15.4
fonttools==4.53.0
frozendict==2.4.4
fsspec==2024.6.0
gradio==4.36.1
gradio_client==1.0.1
h11==0.14.0
httpcore==1.0.5
httptools==0.6.1
httpx==0.27.0
huggingface-hub==0.23.4
idna==3.7
importlib_metadata==7.2.1
importlib_resources==6.4.0
inflect==7.3.0
ipython==8.18.1
jedi==0.19.1
Jinja2==3.1.4
joblib==1.4.2
jsonschema==4.22.0
jsonschema-specifications==2023.12.1
kiwisolver==1.4.5
llvmlite==0.43.0
markdown-it-py==3.0.0
MarkupSafe==2.1.5
matplotlib==3.9.0
matplotlib-inline==0.1.7
mdurl==0.1.2
more-itertools==10.3.0
mpmath==1.3.0
nemo_text_processing==1.0.2
networkx==3.2.1
numba==0.60.0
numpy==1.26.4
nvidia-cublas-cu12==12.1.3.1
nvidia-cuda-cupti-cu12==12.1.105
nvidia-cuda-nvrtc-cu12==12.1.105
nvidia-cuda-runtime-cu12==12.1.105
nvidia-cudnn-cu12==8.9.2.26
nvidia-cufft-cu12==11.0.2.54
nvidia-curand-cu12==10.3.2.106
nvidia-cusolver-cu12==11.4.5.107
nvidia-cusparse-cu12==12.1.0.106
nvidia-nccl-cu12==2.20.5
nvidia-nvjitlink-cu12==12.5.40
nvidia-nvtx-cu12==12.1.105
omegaconf==2.3.0
orjson==3.10.5
packaging==24.1
pandas==2.2.2
parso==0.8.4
pexpect==4.9.0
pillow==10.3.0
prompt_toolkit==3.0.47
ptyprocess==0.7.0
pure-eval==0.2.2
pybase16384==0.3.7
pycparser==2.22
pydantic==2.7.4
pydantic_core==2.18.4
pydub==0.25.1
Pygments==2.18.0
pynini==2.1.5
pyparsing==3.1.2
python-dateutil==2.9.0.post0
python-dotenv==1.0.1
python-multipart==0.0.9
pytz==2024.1
PyYAML==6.0.1
referencing==0.35.1
regex==2024.5.15
requests==2.32.3
rich==13.7.1
rpds-py==0.18.1
ruff==0.4.10
sacremoses==0.1.1
safetensors==0.4.3
scipy==1.13.1
semantic-version==2.10.0
shellingham==1.5.4
six==1.16.0
sniffio==1.3.1
soundfile==0.12.1
stack-data==0.6.3
starlette==0.37.2
sympy==1.12.1
tokenizers==0.19.1
tomlkit==0.12.0
toolz==0.12.1
torch==2.3.1
torchaudio==2.3.1
tqdm==4.66.4
traitlets==5.14.3
transformers==4.41.2
triton==2.3.1
typeguard==4.3.0
typer==0.12.3
typing_extensions==4.12.2
tzdata==2024.1
ujson==5.10.0
urllib3==2.2.2
uvicorn==0.30.1
uvloop==0.19.0
vector-quantize-pytorch==1.14.30
vocos==0.1.0
watchfiles==0.22.0
wcwidth==0.2.13
websockets==11.0.3
WeTextProcessing==1.0.2
wget==3.2
wrapt==1.16.0
zipp==3.19.2
TTS/spk/female/seed_1151_restored_emb.pt
Binary files differ
TTS/spk/female/seed_1397_restored_emb.pt
Binary files differ
TTS/spk/female/seed_2279_restored_emb.pt
Binary files differ
TTS/spk/female/seed_492_restored_emb.pt
Binary files differ
TTS/spk/female/seed_874_restored_emb.pt
Binary files differ
TTS/spk/male/seed_1185_restored_emb.pt
Binary files differ
TTS/spk/male/seed_11_restored_emb.pt
Binary files differ
TTS/spk/male/seed_1259_restored_emb.pt
Binary files differ
TTS/spk/male/seed_1431_restored_emb.pt
Binary files differ
TTS/spk/male/seed_1453_restored_emb.pt
Binary files differ
TTS/tts_main.py
New file
@@ -0,0 +1,70 @@
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse
import uvicorn
import torch
import soundfile
import ChatTTS
import json
import os
app = FastAPI()
ROOT = "/Path to/TTS"
torch._dynamo.config.cache_size_limit = 64
torch._dynamo.config.suppress_errors = True
torch.set_float32_matmul_precision('high')
chat = ChatTTS.Chat()
# compile=True works well, but is slower
chat.load_models(source='custom', custom_path=os.path.join(ROOT, "model/ChatTTS"), compile=False)
spk = {"male": [], "female": []}
male_path = os.path.join(ROOT, "spk/male")
for file in os.listdir(male_path):
    t = torch.load(os.path.join(male_path, file))
    spk['male'].append(t)
female_path = os.path.join(ROOT, "spk/female")
for file in os.listdir(female_path):
    t = torch.load(os.path.join(female_path, file))
    spk['female'].append(t)
def cretae_new_path(path, filetype):
    if not os.path.exists(path):
        os.makedirs(path)
    files = os.listdir(path)
    if len(files) == 0:
        return os.path.join(path, f'0.{filetype}')
    else:
        max = 0
        for file in files:
            max = max if max>=int(os.path.splitext(file)[0]) else int(os.path.splitext(file)[0])
        return os.path.join(path, str(max+1) + f'.{filetype}')
@app.post("/")
async def AudioGenerate(request: Request):
    params = await request.json()
    speaker = spk[params['gender']][params['id']]
    params_refine_text = params['params_refine_text']
    params_infer_code = params['params_infer_code']
    params_infer_code['spk_emb'] = speaker
    print("text: ", params['text'])
    wavs = chat.infer(params['text'],
                #   do_text_normalization=True,
                  skip_refine_text=True,
                  params_refine_text=params_refine_text,
                  params_infer_code=params_infer_code)
    file_path = cretae_new_path(os.path.join(ROOT, "Audio"), "wav")
    soundfile.write(file_path, wavs[0][0], 24000)
    return FileResponse(path=file_path, filename=os.path.basename(file_path), media_type='audio/wav')
if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8080)