如何用 Python 建立相片轉影片舞蹈選擇器:兩張肖像與九種舞蹈提示詞
Two portraits, nine dance prompts: building a photo-to-video picker in Python
這篇 Python 教學示範建立相片轉影片舞蹈選擇器,按肖像數目篩選舞蹈,避免雙人影片顯示錯誤選項。資料集中九種舞蹈有兩種需要兩張肖像,其餘七種各需一張;文章亦示範如何用 CSV 解析器處理提示詞內的逗號,並以測試核對選擇結果。
Say you’ve picked two portraits for a Christmas dance video. You want your friend on the left, you on the right, and both of you in the same shot. The style menu offers nine dances. Which ones should it show?
For the ViGen Deck the Halls generator, the answer is two: Fireplace Duo and Kitchen Duo. The other seven styles each use one portrait. A perfectly reasonable-looking filter, required_photos <= len(photos), returns all nine. It passes a capacity check and still gives the person holding the phone the wrong menu.
That little mismatch is enough material for a useful Python exercise. We’ll use the public style catalog to build a command-line picker, reproduce a CSV bug that only shows up on certain dances, and use one of the returned prompts to plan a video review. Everything through the tests runs locally with the Python standard library. Generating a video is a separate, optional step.
Start with the two rows that look almost identical
Download the CSV once and keep it next to your script. A local copy lets you rerun the examples even while the dataset viewer is rebuilding.
curl -fL 'https://huggingface.co/datasets/aiddroid/deck-the-halls-ai-dance-video-prompts/resolve/main/styles.csv' -o styles.csv
Open the file and look at the first two entries. Both say duet,2,2. One prompt begins with both dancers standing beside a fireplace. The other places them on opposite sides of a kitchen island. The numbers happen to match, but they answer two different questions. dancers describes what appears in the shot. required_photos tells the uploader how many inputs to collect. When your UI is deciding whether the user can proceed, the second field is the one you want.
There’s another distinction worth keeping in the interface. style_name is the label you can match to the generator’s style picker. prompt is an original English storyboard suggestion written for this dataset. Selecting Kitchen Duo on the website gives you that preset. Reading the example prompt tells you how you might stage or evaluate a kitchen duet yourself. The dataset card documents all five fields. Dataset card and prompt examples
Reproduce the bug before writing the picker
Here’s a quick experiment in a Python shell, in the directory where you saved the CSV:
import csv
from pathlib import Path
lines = Path("styles.csv").read_text(encoding="utf-8").splitlines()
for line in lines[1:3]:
print(line.partition(",")[0], len(line.split(",")), len(next(csv.reader([line]))))
Fireplace Duo 5 5
Kitchen Duo 7 5
If you tested a hand-written parser with just the first row, it would look fine. In the kitchen prompt, the dancers step out into the aisle, mirror a shoulder shuffle, then meet palms. Those two commas belong to the sentence. The CSV encloses that field in double quotes. Splitting on every comma silently chops off the last two actions if your code just takes the fifth value as the prompt.
The line-by-line experiment is handy for these two records. In the actual loader, hand the open file to the parser. A quoted CSV field can also contain a newline.
Build the picker around one explicit promise
The command takes the number of portraits you intend to use in this clip. That last phrase matters. Someone browsing everything they could make from a folder of photos might genuinely want the seven solo options alongside the two duets. Someone assigning a left and right dancer has already made a different choice.
Save this as pick_dance.py:
import argparse
import csv
from pathlib import Path
def matching_styles(stream, photos):
for row in csv.DictReader(stream):
if int(row["required_photos"]) == photos:
yield row
def main():
parser = argparse.ArgumentParser(description="Find dances for exactly this many portraits.")
parser.add_argument("photos", type=int, choices=(1, 2))
parser.add_argument("--catalog", type=Path, default=Path("styles.csv"))
args = parser.parse_args()
with args.catalog.open(encoding="utf-8", newline="") as stream:
for row in matching_styles(stream, args.photos):
print(row["style_name"])
print(row["prompt"])
print()
if __name__ == "__main__":
main()
Run python3 pick_dance.py 2. The command prints both duet names with their full prompts. Run it with 1 and the first match changes to Elf Dance. Try 3 and the command tells you which counts it accepts. If you downloaded the file elsewhere, pass the path with --catalog.
There’s an easy mistake hiding in that one-line comparison. Try removing int(). The command runs successfully and prints a blank screen: the CSV contains the string "2", while the argument parser gives you the integer 2. A web interface built on that result might tell the user there are no matching styles. The explicit conversion also makes a malformed count visible: a value like two raises an error while loading the record.
Test the thing the user would notice
Save the following beside the script as test_pick_dance.py. These tests exercise the downloaded catalog. If an editor later adds a third duet, the first assertion will flag the change for review.
import unittest
from pathlib import Path
from pick_dance import matching_styles
class DanceCatalogTests(unittest.TestCase):
def picks(self, photos):
with Path("styles.csv").open(encoding="utf-8", newline="") as source:
return list(matching_styles(source, photos))
def test_two_portraits_offer_both_duets(self):
rows = self.picks(2)
self.assertCountEqual(
[row["style_name"] for row in rows], ["Fireplace Duo", "Kitchen Duo"]
)
kitchen = next(row for row in rows if row["style_name"] == "Kitchen Duo")
self.assertTrue(kitchen["prompt"].endswith("then meet palms on the last beat."))
def test_one_portrait_offers_seven_solos_with_prompts(self):
rows = self.picks(1)
self.assertEqual(len(rows), 7)
self.assertTrue(all(row["dance_type"] == "solo" for row in rows))
self.assertTrue(all(row["prompt"].strip() for row in rows))
Run python3 -m unittest -v test_pick_dance. The kitchen assertion is deliberate. Checking only that the prompt is nonempty would happily accept a broken sentence ending at “aisle.” Checking for the final action catches exactly the truncation we saw earlier.
Turn one returned prompt into a shot review
The picker can tell you that Fireplace Duo takes two portraits. What should you look at once you actually have a clip? Start with the choreography in the example:
Frame both dancers head to toe beside a glowing fireplace. Let the left dancer clap twice and the right dancer answer with two heel taps before they turn together.
Play the clip once with your attention on the left dancer. Count the claps. On the second pass, watch the right dancer’s shoes. Can you see two taps? Do they begin after the claps? Finally, pause at the turn and check whether both dancers’ feet are still in frame. If the camera has cropped them out, mark the taps as unobservable. That’s a different editing decision from seeing the feet clearly and counting only one tap.
Kitchen Duo calls for a different check. Scrub straight to the last beat: can you see the two palms meet, and can you follow each arm back to the correct person? A wide shot might make the side steps easy to read but leave that contact too small to judge. For a second attempt, keep the portraits and movement instructions fixed and change only the framing. You’ll have a clearer basis for deciding whether that change helped. These are suggested review steps; the catalog contains text examples and no measured video results.
For a small style picker, I’d put the dance name on the button, the number of required portraits beside the upload control, and the prompt on the review screen. That puts each piece of information where someone can act on it. By the time the right dancer is supposed to tap a heel, nobody should still be wondering where to put the second photo.
來源:DEV Community · dev.to