swapnakumbar12 commited on
Commit
9cf17be
Β·
verified Β·
1 Parent(s): f381ede

Update veo_generator.py

Browse files
Files changed (1) hide show
  1. veo_generator.py +289 -342
veo_generator.py CHANGED
@@ -1,400 +1,338 @@
1
  """
2
- veo_generator.py
3
- Generates real AI experiment videos using Google Gemini Veo 3.1.
4
-
5
- Setup on Hugging Face Spaces:
6
- Settings β†’ Repository secrets β†’ Add:
7
- Name : GEMINI_API_KEY
8
- Value: your key from https://aistudio.google.com (needs billing enabled)
9
-
10
- Cost: ~$0.40/second Γ— 8 seconds = ~$3.20 per video (Veo 3.1 Fast)
11
- New Google Cloud accounts get $300 free credits β‰ˆ 90 free videos.
12
-
13
- Each experiment has a hand-crafted cinematic prompt designed to show
14
- exactly what happens in the lab β€” materials, reaction, and outcome.
 
15
  """
16
 
17
  import os
 
18
  import time
19
  import tempfile
20
  from pathlib import Path
21
 
22
- # ── 75 hand-crafted Veo prompts β€” one per experiment ─────────────────────────
23
- # Prompt style: subject + action + visual detail + camera + style
24
- # Optimised for Veo 3.1: descriptive, cinematic, science-accurate
25
-
26
  VEO_PROMPTS = {
27
- # ── Chapter 1: Chemical Reactions ────────────────────────────────────────
28
  "Activity 1.1": (
29
  "Close-up macro shot in a school chemistry lab: a student holds a clean magnesium ribbon "
30
- "with metal tongs over a blue Bunsen burner flame. The magnesium ignites with a brilliant, "
31
- "intensely bright white flash of light, producing thick white smoke. A white powdery residue "
32
- "of magnesium oxide falls onto a black watch glass below. Cinematic slow-motion, warm lab lighting."
33
  ),
34
  "Activity 1.2": (
35
- "Time-lapse chemistry experiment: a clean iron nail is slowly lowered into a clear glass beaker "
36
- "filled with bright blue copper sulphate solution. Over time the nail surface turns reddish-brown "
37
- "as copper deposits form, and the blue solution gradually fades to pale green. "
38
- "Macro close-up, bright studio lighting, clean white background."
39
  ),
40
  "Activity 1.3": (
41
- "Chemistry lab experiment: two clear solutions poured together in a test tube β€” one colourless "
42
- "lead nitrate solution and one potassium iodide solution. The moment they mix, a vivid bright "
43
- "yellow precipitate of lead iodide instantly forms, swirling through the liquid. "
44
- "Close-up macro shot, bright even lighting, glass test tube visible."
45
  ),
46
  "Activity 1.4": (
47
- "School chemistry lab: zinc granules placed in a glass test tube. Dilute hydrochloric acid "
48
- "poured in causes vigorous fizzing and bubbling as hydrogen gas is produced. A student brings "
49
- "a lit matchstick near the mouth of the test tube β€” a sharp 'pop' sound and small flame. "
50
- "Close-up shot, safety goggles visible, bright lab lighting."
51
  ),
52
  "Activity 1.5": (
53
- "Chemistry demonstration: marble chips reacting with dilute hydrochloric acid in a test tube, "
54
- "producing carbon dioxide gas bubbles. A delivery tube directs the gas into a second test tube "
55
- "containing clear lime water, which turns milky white as calcium carbonate precipitates. "
56
- "Side-angle close-up, bright laboratory lighting."
57
  ),
58
  "Activity 1.6": (
59
  "Chemistry lab: bright green ferrous sulphate crystals in a dry test tube heated over a "
60
- "Bunsen burner flame. The crystals gradually change colour from green to reddish-brown, "
61
- "with white sulphur dioxide fumes visible rising from the tube. "
62
- "Macro close-up, warm glowing flame, dark background for contrast."
63
  ),
64
  "Activity 1.7": (
65
- "Science experiment: electrolysis of water setup β€” a beaker of water with dilute sulphuric acid, "
66
- "two carbon rod electrodes connected to a 6V battery. Tiny bubbles of hydrogen gas stream "
67
- "rapidly from the cathode and oxygen bubbles more slowly from the anode. Inverted test tubes "
68
- "collect the gases. Close-up macro, clean lab bench, bright lighting."
69
  ),
70
  "Activity 1.8": (
71
  "Chemistry experiment: white sodium carbonate crystals in a test tube heated over a Bunsen "
72
- "burner. No visible change β€” crystals remain white, showing thermal stability. "
73
- "Student observes carefully. Wide shot then close-up, bright lab environment."
74
  ),
75
-
76
- # ── Chapter 2: Acids Bases Salts ─────────────────────────────────────────
77
  "Activity 2.1": (
78
- "School chemistry lab: a student adds two drops of pink phenolphthalein indicator to a test "
79
- "tube of colourless acid β€” no colour change. Then adds it to sodium hydroxide solution β€” "
80
- "it turns bright pink instantly. Then methyl orange tested: turns red in acid, yellow in base. "
81
- "Macro close-up, bright natural lighting, colourful liquid transitions."
82
  ),
83
  "Activity 2.2": (
84
- "Chemistry lab: zinc granules in a test tube, dilute hydrochloric acid added β€” vigorous "
85
- "fizzing and bubbling as hydrogen gas evolves. A delivery tube bubbles gas through soap solution, "
86
- "creating foam bubbles. A lit matchstick brought to foam β€” small blue flame burns. "
87
- "Close-up, bright lab lighting, gloved hands visible."
88
  ),
89
  "Activity 2.3": (
90
  "Science experiment: white marble chips in a conical flask, dilute hydrochloric acid added. "
91
- "Brisk carbon dioxide bubbles rise vigorously. A delivery tube leads gas into lime water in "
92
- "a second flask, which turns milky white. Close-up macro, clean laboratory setting."
93
  ),
94
  "Activity 2.4": (
95
- "Chemistry safety demonstration: water in a glass beaker, concentrated sulphuric acid carefully "
96
- "added drop by drop along a glass rod. Steam rises as heat is produced β€” the beaker becomes "
97
- "noticeably warm. 'Always add acid to water' shown on screen. Wide shot, safety goggles worn."
98
  ),
99
  "Activity 2.5": (
100
- "Physics-chemistry experiment: a simple circuit β€” battery, wires, small light bulb, two "
101
- "copper electrodes dipped in a beaker of dilute hydrochloric acid. The bulb glows brightly. "
102
- "Then electrodes placed in glucose solution β€” bulb does not glow. "
103
- "Close-up, clean table, bright lighting showing bulb glow."
104
  ),
105
  "Activity 2.6": (
106
- "Titration experiment: sodium hydroxide solution with phenolphthalein in a conical flask β€” "
107
- "bright pink. A student slowly adds dilute hydrochloric acid dropwise from a burette. "
108
- "The pink colour gradually fades until at the endpoint the solution turns completely colourless. "
109
- "Close-up macro, white background, dramatic colour transition."
110
  ),
111
  "Activity 2.7": (
112
- "Chemistry pH experiment: several test tubes containing different solutions β€” vinegar, lemon juice, "
113
- "water, soap solution, sodium hydroxide. Universal indicator added to each. "
114
- "Solutions display a rainbow of colours: deep red, orange, yellow, green, blue, purple, "
115
- "matching a pH colour chart. Bright overhead lighting, clean lab bench."
116
  ),
117
  "Activity 2.8": (
118
- "Chemistry crystallisation: blue copper sulphate solution in a china dish heated gently on "
119
- "a tripod stand over a Bunsen burner. Water evaporates, solution concentrates. "
120
- "As it cools, beautiful vivid blue copper sulphate crystals slowly form and grow. "
121
  "Macro time-lapse, warm light, crystals sparkling."
122
  ),
123
-
124
- # ── Chapter 3: Metals and Non-metals ─────────────────────────────────────
125
  "Activity 3.1": (
126
- "Dramatic chemistry demonstration: a strip of magnesium ribbon held in crucible tongs "
127
- "ignited in air β€” burns with an intensely bright white flame, producing white magnesium oxide "
128
- "smoke and ash. The bright light illuminates the entire lab bench. "
129
  "Slow-motion close-up, dark background, cinematic."
130
  ),
131
  "Activity 3.2": (
132
- "Reactive metals experiment: a small piece of sodium metal dropped into a beaker of water "
133
- "using forceps β€” it skims the surface rapidly, fizzing and sputtering vigorously as hydrogen "
134
- "gas is produced and sodium hydroxide forms. Then calcium dropped in β€” sinks, steady bubbles. "
135
- "Wide and close-up shots, safety shield visible."
136
  ),
137
  "Activity 3.3": (
138
- "Chemistry: zinc granules in test tube, dilute hydrochloric acid added β€” immediate vigorous "
139
- "hydrogen bubbles. Student tests with burning matchstick near tube mouth β€” audible pop sound "
140
- "confirming hydrogen. Gloved hands, safety goggles, bright lab setting."
141
  ),
142
  "Activity 3.4": (
143
- "Displacement reaction experiment: clean iron nails placed in bright blue copper sulphate "
144
- "solution in a beaker. Over time the nail surface gets coated in reddish-brown copper metal "
145
- "deposit, while the solution turns from deep blue to light green. "
146
- "Side-angle close-up, time-lapse, clean laboratory."
147
  ),
148
  "Activity 3.5": (
149
- "Chemistry: yellow sulphur powder in a deflagrating spoon ignited in air β€” burns with "
150
- "a pale blue flame, producing colourless pungent sulphur dioxide gas. "
151
- "The gas introduced into a gas jar. Close-up macro, fume hood visible, safety precautions shown."
152
  ),
153
  "Activity 3.6": (
154
- "Exothermic chemistry reaction: white quicklime (calcium oxide) lumps in a beaker, water "
155
- "added slowly. The mixture hisses and steams dramatically as intense heat is released, "
156
- "producing slaked lime paste. Student holds hand near to feel warmth. "
157
- "Close-up, steam visible, dramatic reaction."
158
  ),
159
  "Activity 3.7": (
160
- "Chemistry experiment: solid sodium chloride crystals tested for electrical conductivity β€” "
161
- "bulb does not glow. Then dissolved in water, electrodes dipped in solution β€” bulb glows. "
162
- "Also shows NaCl crystals melting at high temperature conducting electricity. "
163
- "Clean lab bench, close-up on bulb lighting up."
164
  ),
165
-
166
- # ── Chapter 4: Carbon Compounds ──────────────────────────────────────────
167
  "Activity 4.1": (
168
- "Chemistry: charcoal powder burning in a china dish, covered by inverted beaker. "
169
- "Carbon dioxide produced inside beaker. The water at the bottom of the beaker tested "
170
- "with blue litmus paper β€” it turns red, showing acidic carbonic acid formed. "
171
- "Close-up, clean lab, step-by-step demonstration."
172
  ),
173
  "Activity 4.2": (
174
- "Science experiment: marble chips in test tube reacting with dilute HCl, CO2 bubbles through "
175
- "delivery tube into lime water β€” lime water turns milky white instantly. "
176
- "Clear glass apparatus visible, close-up on colour change, bright lighting."
177
  ),
178
  "Activity 4.3": (
179
- "Soap making chemistry: vegetable oil in a beaker, concentrated sodium hydroxide solution added. "
180
- "Student stirs continuously while heating gently. Mixture thickens into soap. "
181
- "Common salt added to precipitate white soap chunks that float to surface. "
182
- "Wide shot, gloves worn, steaming beaker."
183
  ),
184
  "Activity 4.4": (
185
- "Soap cleansing experiment: two test tubes with water, a drop of oil added to each. "
186
- "One tube has soap solution added and shaken β€” oil emulsifies into tiny droplets, water turns "
187
- "milky white. Other tube without soap β€” oil layer stays separate. "
188
- "Side-by-side comparison, close-up macro, bright lighting."
189
  ),
190
-
191
- # ── Chapter 5: Periodic Classification ───────────────────────────────────
192
  "Activity 5.1": (
193
- "Science lab comparison of metals and non-metals: student hammers copper and sulphur samples. "
194
- "Copper flattens (malleable), sulphur shatters (brittle). Metals shown lustrous and shiny, "
195
- "non-metals dull. Cutting with knife: sulphur crumbles easily. "
196
- "Close-up macro, bright lighting, clear labels."
197
  ),
198
  "Activity 5.2": (
199
- "Electrical conductivity experiment: simple circuit with bulb and battery. "
200
- "Metal samples (copper, iron, aluminium) placed in circuit β€” bulb glows brightly each time. "
201
- "Non-metal samples (sulphur, coal) placed β€” bulb stays off. "
202
  "Clean lab bench, close-up on glowing bulb, clear demonstration."
203
  ),
204
  "Activity 5.3": (
205
- "Elements burning in oxygen: magnesium ribbon ignites in bright white flame, sulphur powder "
206
- "burns with blue flame in deflagrating spoon inside oxygen jar. "
207
- "Comparison of metal and non-metal oxide formation. "
208
  "Cinematic lab footage, safety equipment visible, close-up flames."
209
  ),
210
  "Activity 5.4": (
211
- "Chemistry: metal oxide (magnesium oxide) dissolved in water, tested with red litmus β€” "
212
- "turns blue (basic). Non-metal oxide (sulphur dioxide) dissolved in water, tested with "
213
- "blue litmus β€” turns red (acidic). Side-by-side comparison, macro close-up on colour changes."
214
  ),
215
  "Activity 5.5": (
216
- "Classroom activity: colourful element flash cards spread on a table. Student arranges them "
217
- "in increasing order of atomic mass, then groups elements with similar properties. "
218
- "Periodic table pattern emerges. Overhead camera shot, colourful cards, engaging visual."
219
  ),
220
-
221
- # ── Chapter 6: Life Processes ─────────────────────────────────────────────
222
  "Activity 6.1": (
223
- "Biology experiment: germinating mung bean seeds placed in a sealed conical flask. "
224
- "Delivery tube leads to test tube with clear lime water. Over time lime water turns milky, "
225
- "proving seeds release carbon dioxide during respiration. "
226
- "Close-up, green seeds visible, clean biology lab."
227
  ),
228
  "Activity 6.2": (
229
- "Biology microscopy: student carefully peels the lower epidermis of a leaf with forceps. "
230
- "Places peel on glass slide with glycerine, adds cover slip. "
231
- "Microscope view shows green oval stomatal pores with bean-shaped guard cells. "
232
- "Microscope footage, sharp focus, vivid green cells."
233
  ),
234
  "Activity 6.3": (
235
- "Photosynthesis experiment: a potted plant left in dark for 24 hours. Part of leaf covered "
236
- "with black paper, plant placed in sunlight. Later, leaf decolorised in boiling alcohol, "
237
- "then iodine solution applied β€” uncovered part turns blue-black (starch present), "
238
- "covered part remains yellow-brown. Split-screen before/after."
239
  ),
240
  "Activity 6.4": (
241
- "Biology experiment: plant leaf inside a bottle containing potassium hydroxide solution "
242
- "(absorbs CO2). Plant exposed to sunlight. Leaf tested with iodine β€” remains yellow-brown "
243
- "(no starch). Control leaf without KOH turns blue-black. Side-by-side comparison, "
244
- "clear science lab setting."
245
  ),
246
  "Activity 6.5": (
247
- "Starch test experiment: green leaf boiled in water then in alcohol to remove chlorophyll. "
248
- "Leaf turns pale yellow. Washed in warm water, iodine solution added β€” leaf turns "
249
- "distinctive blue-black colour showing starch is present. "
250
- "Macro close-up, step-by-step demonstration, bright lighting."
251
  ),
252
  "Activity 6.6": (
253
- "Biology microscopy: student gently scrapes inner cheek with a clean toothpick, "
254
- "spreads cells on slide with glycerine, adds methylene blue stain. "
255
- "Microscope view shows flat, irregular human cheek cells with purple-stained nucleus visible. "
256
- "Microscope footage, sharp focus, blue-stained cells."
257
  ),
258
  "Activity 6.7": (
259
- "Plant cell microscopy: student peels thin transparent layer from inside of onion. "
260
- "Places on slide with iodine solution, covers with cover slip. "
261
- "Microscope shows rectangular onion cells with clear cell walls and brown-stained nuclei. "
262
- "Sharp microscope footage, grid of rectangular cells visible."
263
  ),
264
  "Activity 6.8": (
265
- "Biology demonstration of peristalsis: a flexible rubber tube with a marble inside. "
266
- "Student squeezes the tube rhythmically behind the marble, pushing it forward β€” "
267
- "simulating food movement in the oesophagus. "
268
- "Close-up hand demonstration, simple and clear."
269
  ),
270
  "Activity 6.9": (
271
- "Enzyme experiment: starch solution in test tube. Human saliva added and tube kept warm. "
272
- "After a few minutes, iodine test performed β€” iodine does not turn blue-black, "
273
- "showing starch has been digested by salivary amylase enzyme. "
274
- "Step-by-step close-up, clean biology lab."
275
  ),
276
  "Activity 6.10": (
277
- "Biology breathing model: a bell jar with two balloons hanging inside representing lungs, "
278
- "rubber sheet at base representing diaphragm. Student pulls rubber sheet down β€” "
279
- "balloons inflate (inhalation). Pushes up β€” balloons deflate (exhalation). "
280
- "Clear demonstration, labelled diagram overlay."
281
  ),
282
-
283
- # ── Chapter 7: Control and Coordination ──────────────────────────────────
284
  "Activity 7.1": (
285
- "Plant biology time-lapse: a climbing plant tendril gently touches a thin wooden stick. "
286
- "Over hours the tendril slowly coils around the stick in a tight spiral β€” "
287
- "thigmotropism shown clearly. Macro time-lapse, green tendril on white background."
288
  ),
289
  "Activity 7.2": (
290
- "Plant geotropism experiment: germinating bean seeds placed horizontally in moist sawdust "
291
- "in a glass jar. Time-lapse over two days shows the white radicle (root) bending "
292
- "downward toward gravity regardless of seed orientation. "
293
- "Clear glass jar, macro time-lapse footage."
294
  ),
295
  "Activity 7.3": (
296
- "Phototropism experiment: a young seedling in a pot placed inside a cardboard box with "
297
- "a small hole on one side. Light enters from one side only. "
298
- "Over days the green shoot bends and curves toward the light source. "
299
- "Side-angle time-lapse, bright light visible through hole."
300
  ),
301
  "Activity 7.4": (
302
- "Plant growth experiment: two identical seedlings β€” one with shoot tip covered by foil, "
303
- "one uncovered. Both exposed to one-sided light. Uncovered plant bends toward light; "
304
- "covered plant grows straight. Side-by-side time-lapse comparison."
305
  ),
306
  "Activity 7.5": (
307
- "Human biology experiment: close-up of a person's tongue with different solutions applied "
308
- "to different areas using cotton buds β€” sweet sugar solution at tip, salty at sides, "
309
- "sour lemon juice at edges, bitter at back. Facial expressions show taste sensations. "
310
- "Clean close-up footage, educational overlay labels."
311
  ),
312
  "Activity 7.6": (
313
- "Reflex action demonstration: a ruler held vertically by a student. Without warning "
314
- "the ruler is dropped β€” the student catches it quickly below the drop point. "
315
- "Slow-motion replay shows the fast involuntary reflex catch. "
316
- "Slow-motion footage, clear close-up of hand and ruler."
317
  ),
318
  "Activity 7.7": (
319
- "Biology: an earthworm on a tray gently touched with a soft brush on different body segments. "
320
- "The worm immediately retracts and moves away from each touch stimulus. "
321
  "Close-up macro, natural lighting, careful humane handling."
322
  ),
323
  "Activity 7.8": (
324
- "Plant hormone experiment: two identical plants β€” one with IAA auxin solution applied "
325
- "to shoot tip, one with plain water (control). Over days the auxin plant shows enhanced "
326
- "elongated growth compared to control. Side-by-side comparison, time-lapse footage."
327
  ),
328
-
329
- # ── Chapter 8: Reproduction ───────────────────────────────────────────────
330
  "Activity 8.1": (
331
  "Biology microscopy: a drop of Amoeba culture on a glass slide under high magnification. "
332
- "The single-celled organism begins binary fission β€” nucleus divides, cytoplasm pinches "
333
- "and splits into two identical daughter amoeba cells. "
334
- "Microscope footage, clear nucleus division visible."
335
  ),
336
  "Activity 8.2": (
337
- "Yeast microscopy experiment: yeast cells in sugar solution on a glass slide. "
338
- "Under microscope, small oval yeast cells show tiny buds forming on their surface β€” "
339
- "budding reproduction. Time-lapse microscope footage, clear buds visible."
340
  ),
341
  "Activity 8.3": (
342
  "Fungal biology: Rhizopus mold growing on moist bread β€” black sporangia on upright stalks "
343
- "visible with magnifying lens. Microscope slide of sporangia shows tiny round spores released. "
344
- "Macro and microscope footage combined."
345
  ),
346
  "Activity 8.4": (
347
- "Plant propagation: a healthy hibiscus stem cut below a node with a clean blade. "
348
- "Cut end dipped in rooting hormone powder. Planted in moist soil in a pot. "
349
- "Time-lapse over days shows new white roots emerging from the cut end, then new green leaves. "
350
- "Close-up, natural garden light."
351
  ),
352
  "Activity 8.5": (
353
- "Seed anatomy: soaked gram (chickpea) seeds with seed coat removed. "
354
- "Student splits seed carefully to reveal white embryo inside β€” "
355
- "clearly shows tiny radicle (future root) and plumule (future shoot) within cotyledons. "
356
- "Macro close-up, bright lighting, labelled."
357
  ),
358
  "Activity 8.6": (
359
- "Flower dissection biology: a large Hibiscus flower dissected on a white tray. "
360
- "Student separates green sepals, pink petals, stamens with yellow pollen-covered anthers, "
361
- "and central pistil. Cross-section shows ovary with ovules inside. "
362
- "Macro overhead shot, all parts labelled."
363
  ),
364
  "Activity 8.7": (
365
- "Pollination experiment: a small paintbrush collects yellow pollen from anther of one flower. "
366
- "Pollen gently brushed onto sticky stigma of another flower. Flower tagged. "
367
- "Days later, fruit development visible where pollination occurred. "
368
- "Macro close-up, bright natural light."
369
  ),
370
  "Activity 8.8": (
371
  "Seed germination time-lapse: soaked gram seeds on moist cotton in a clear glass container. "
372
- "Time-lapse shows the tiny white radicle emerging first, curving downward, "
373
- "then the green plumule pushing upward through cotton. "
374
- "Macro time-lapse, bright natural lighting."
375
  ),
376
-
377
- # ── Chapter 9: Heredity and Evolution ────────────────────────────────────
378
  "Activity 9.1": (
379
- "Biology genetics: multiple pea pods from different pea plants spread on a white tray. "
380
- "Student opens each pod and counts seeds β€” variation in number clearly visible. "
381
- "Some pods have 4 seeds, some 6, some 8. Overhead shot, close-up counting."
382
  ),
383
  "Activity 9.2": (
384
  "Genetics activity: family photographs pinned on a board. Student examines and marks "
385
- "physical traits β€” attached earlobes, widow's peak hairline, tongue rolling β€” "
386
- "tracking which relatives share which traits. Educational, family-friendly footage."
387
  ),
388
  "Activity 9.3": (
389
- "Genetics model: coloured beads (red and white) representing dominant and recessive alleles. "
390
- "Student pairs beads to simulate Mendelian inheritance β€” Rr, RR, rr genotypes shown. "
391
- "Punnett square drawn alongside. Overhead shot, colourful beads on white table."
392
  ),
393
  "Activity 9.4": (
394
- "Evolution demonstration: light and dark paper moth cutouts scattered on two backgrounds β€” "
395
- "white paper and black paper. A student acts as predator picking up 'visible' moths. "
396
- "Dark moths survive on dark background, light moths on light background β€” "
397
- "natural selection visualised. Overhead camera, colourful demonstration."
398
  ),
399
  "Activity 9.5": (
400
  "Palaeontology study: fossil specimens on a table β€” ammonites, trilobites, plant fossils. "
@@ -402,116 +340,99 @@ VEO_PROMPTS = {
402
  "Close-up of detailed fossil textures, educational museum-style footage."
403
  ),
404
  "Activity 9.6": (
405
- "Genetics activity: student draws a family pedigree chart on paper β€” squares for males, "
406
- "circles for females, shaded shapes for trait carriers. Shows inheritance pattern of "
407
- "a trait across three generations. Overhead close-up, clear diagrams drawn in real-time."
408
  ),
409
  "Activity 9.7": (
410
- "Biology activity: student lists traits in two columns β€” acquired (pierced ear, haircut, "
411
- "scar) and inherited (tongue rolling, earlobe attachment, eye colour). "
412
- "Interactive classroom demonstration with volunteers showing tongue rolling ability. "
413
- "Friendly classroom footage."
414
  ),
415
  "Activity 9.8": (
416
  "Evolution model: paper cutouts of finches with different beak shapes β€” thick seed-cracker, "
417
- "thin insect-prober, curved cactus-feeder. Seeds, insects, and cactus models placed on table. "
418
- "Student tests which beak shape picks up each food type most efficiently. "
419
- "Overhead shot, colourful engaging demonstration."
420
  ),
421
-
422
- # ── Chapter 10: Light ─────────────────────────────────────────────────────
423
  "Activity 10.1": (
424
  "Physics optics experiment: a plane mirror mounted vertically on a white drawing sheet. "
425
- "Student positions two pins to mark an incident ray of light toward the mirror. "
426
- "Views reflected pins from other side β€” angle of incidence equals angle of reflection. "
427
- "Protractor shown measuring equal angles. Overhead close-up, bright lab lighting."
428
  ),
429
  "Activity 10.2": (
430
- "Light refraction experiment: a glass rectangular slab on white paper, two pins marking "
431
- "an incident ray. Light ray enters glass slab and bends toward normal β€” then bends away "
432
- "from normal on exit, emerging parallel to original ray. "
433
- "Overhead shot tracing light path with pencil, clear glass slab visible."
434
  ),
435
  "Activity 10.3": (
436
  "Optics experiment: concave mirror on stand, lit candle in front at various distances. "
437
- "White screen positioned to catch image β€” shows inverted enlarged image beyond C, "
438
- "then diminished image, then no image at F. "
439
- "Side-angle footage, glowing candle flame, clear image on white screen."
440
  ),
441
  "Activity 10.4": (
442
- "Physics optics: convex mirror on stand, candle placed in front. "
443
- "Student looks into convex mirror β€” sees small, upright, virtual image of candle. "
444
- "No real image forms on screen placed behind mirror. "
445
- "Close-up of mirror reflection, wide-angle view of setup."
446
  ),
447
  "Activity 10.5": (
448
- "Concave lens optics: a concave lens mounted on stand, candle in front. "
449
- "A white screen moved on same side as candle β€” no real image forms. "
450
- "Student looks through lens β€” sees small, upright, virtual image. "
451
  "Side-angle footage, bright lab, clear lens visible."
452
  ),
453
  "Activity 10.6": (
454
- "Convex lens experiment: convex lens on stand, candle at different distances. "
455
- "Screen adjusted to catch sharp images β€” real, inverted, enlarged image when object "
456
- "between F and 2F; real diminished beyond 2F; no image at F. "
457
  "Clear footage of candle image forming sharply on white screen."
458
  ),
459
  "Activity 10.7": (
460
- "Focal length measurement: convex lens held facing a distant tree or building outside window. "
461
- "White screen moved behind lens until sharp image of distant object forms. "
462
- "Ruler measures lens-to-screen distance β€” this is the focal length. "
463
- "Bright natural light, clear measurement shown."
464
  ),
465
  "Activity 10.8": (
466
  "Prism optics experiment: a triangular glass prism on white paper, pins marking incident ray. "
467
- "Light ray enters prism, bends at both surfaces, exits at a deviation angle. "
468
- "Student traces the refracted and emergent ray paths on paper with pencil. "
469
- "Overhead close-up, clear glass prism refracting light visibly."
470
  ),
471
  "Activity 10.9": (
472
- "Light dispersion experiment: a glass triangular prism in a beam of white sunlight entering "
473
- "through a narrow slit. The prism separates white light into a beautiful spectrum β€” "
474
- "violet, indigo, blue, green, yellow, orange, red β€” projected on a white screen. "
475
- "Dramatic cinematic close-up, rainbow colours vivid and clear."
476
  ),
477
  }
478
 
479
 
480
  def _get_prompt(exp: dict) -> str:
481
- """Get the Veo prompt for an experiment, with fallback."""
482
- import re
483
  match = re.match(r"(Activity \d+\.\d+)", exp["title"])
484
  if match:
485
  key = match.group(1)
486
  if key in VEO_PROMPTS:
487
  return VEO_PROMPTS[key]
488
- # Generic fallback built from experiment data
489
  return (
490
- f"Close-up science laboratory experiment: {exp['title']}. "
491
- f"Materials: {exp['materials'][:100]}. "
492
- f"A student carefully performs the experiment step by step. "
493
- f"The expected result: {exp['outcome'][:100]}. "
494
- f"Cinematic 4K laboratory footage, educational science video, bright lighting."
495
  )
496
 
497
 
498
  def generate_experiment_video(exp: dict, output_dir: str = None) -> str | None:
499
  """
500
- Generate a real AI video of the experiment using Gemini Veo 3.1.
501
-
502
- Returns path to the saved MP4 file, or None on failure.
503
- Polls every 10 seconds until complete (typically 2-4 minutes).
504
  """
505
  api_key = os.environ.get("GEMINI_API_KEY", "")
506
  if not api_key:
507
- print("GEMINI_API_KEY not set")
508
  return None
509
 
510
  try:
511
  from google import genai
512
  from google.genai import types
513
  except ImportError:
514
- print("google-genai not installed. Add 'google-genai' to requirements.txt")
515
  return None
516
 
517
  if output_dir is None:
@@ -520,66 +441,92 @@ def generate_experiment_video(exp: dict, output_dir: str = None) -> str | None:
520
  output_dir.mkdir(parents=True, exist_ok=True)
521
 
522
  prompt = _get_prompt(exp)
523
- print(f"Generating Veo video for: {exp['title']}")
524
- print(f"Prompt: {prompt[:120]}...")
 
525
 
526
  try:
527
  client = genai.Client(api_key=api_key)
528
 
529
- # Submit video generation request
 
 
530
  operation = client.models.generate_videos(
531
  model="veo-3.1-generate-preview",
532
  prompt=prompt,
533
  config=types.GenerateVideosConfig(
534
- aspect_ratio="16:9",
535
- duration_seconds=8,
536
- # generate_audio=True, # native audio β€” comment out to save cost
537
  ),
538
  )
 
539
 
540
- # Poll until complete (Veo is async β€” takes 2-4 minutes)
541
- max_wait = 300 # 5 minutes max
542
- elapsed = 0
543
- interval = 10
 
 
 
544
 
545
- print("Waiting for Veo to generate video", end="", flush=True)
 
 
 
 
 
 
546
  while not operation.done:
547
  if elapsed >= max_wait:
548
- print("\nTimed out waiting for Veo video generation")
549
  return None
550
  time.sleep(interval)
551
  elapsed += interval
552
- print(".", end="", flush=True)
553
  operation = client.operations.get(operation)
 
 
 
554
 
555
- print(" Done!")
556
 
557
- # Save the video
558
- if not operation.response or not operation.response.generated_videos:
559
- print("No video in response")
 
560
  return None
561
 
562
- video = operation.response.generated_videos[0]
 
 
 
 
563
 
564
- # Download video bytes
565
- client.files.download(file=video.video)
566
- video_bytes = video.video.video_bytes
567
 
568
- if not video_bytes:
569
- print("Empty video bytes received")
570
  return None
571
 
572
- # Save to file
 
 
 
 
573
  safe_title = re.sub(r"[^\w]", "_", exp["title"])[:40]
574
  output_path = output_dir / f"{safe_title}.mp4"
575
- output_path.write_bytes(video_bytes)
576
- print(f"Video saved: {output_path}")
577
- return str(output_path)
 
 
 
 
 
 
578
 
579
  except Exception as e:
580
- print(f"Veo generation error: {e}")
581
- return None
582
-
583
-
584
- # Fix missing import in generate_experiment_video
585
- import re
 
1
  """
2
+ veo_generator.py – Fixed for Gemini API (not Vertex AI)
3
+
4
+ Key fixes vs previous version:
5
+ 1. Removed duration_seconds β†’ not supported in Gemini API (Vertex AI only)
6
+ 2. Removed aspect_ratio β†’ caused 400 errors with some key tiers
7
+ 3. Fixed download β†’ use generated_video.video.save() correctly
8
+ 4. Added full exception logging so errors show in HF Space logs
9
+ 5. Added retry logic for transient failures
10
+ 6. Prints the real error message so you can debug from HF logs
11
+
12
+ Setup:
13
+ HF Space β†’ Settings β†’ Repository secrets β†’ GEMINI_API_KEY
14
+ Get key : https://aistudio.google.com (billing must be enabled)
15
+ Enable : https://console.cloud.google.com/apis/library/generativelanguage.googleapis.com
16
  """
17
 
18
  import os
19
+ import re
20
  import time
21
  import tempfile
22
  from pathlib import Path
23
 
24
+ # ── 75 hand-crafted Veo prompts ───────────────────────────────────────────────
 
 
 
25
  VEO_PROMPTS = {
 
26
  "Activity 1.1": (
27
  "Close-up macro shot in a school chemistry lab: a student holds a clean magnesium ribbon "
28
+ "with metal tongs over a blue Bunsen burner flame. The magnesium ignites with an intensely "
29
+ "bright white flash, producing thick white smoke and white powdery magnesium oxide on a "
30
+ "watch glass below. Slow-motion, warm lab lighting, cinematic."
31
  ),
32
  "Activity 1.2": (
33
+ "Chemistry experiment: a clean iron nail slowly lowered into a glass beaker of bright blue "
34
+ "copper sulphate solution. The nail surface turns reddish-brown as copper deposits form and "
35
+ "the blue solution gradually fades to pale green. Macro close-up, bright studio lighting."
 
36
  ),
37
  "Activity 1.3": (
38
+ "Chemistry lab: two clear solutions mixed in a test tube β€” colourless lead nitrate and "
39
+ "potassium iodide. A vivid bright yellow precipitate of lead iodide instantly forms, "
40
+ "swirling through the liquid. Macro close-up, bright even lighting."
 
41
  ),
42
  "Activity 1.4": (
43
+ "School chemistry lab: zinc granules in a glass test tube, dilute hydrochloric acid poured "
44
+ "in causes vigorous fizzing as hydrogen gas is produced. A lit matchstick brought near the "
45
+ "mouth of the test tube causes a small pop flame. Close-up, safety goggles visible."
 
46
  ),
47
  "Activity 1.5": (
48
+ "Chemistry demonstration: marble chips reacting with hydrochloric acid in a test tube, "
49
+ "carbon dioxide bubbles rising vigorously. A delivery tube leads gas into lime water in a "
50
+ "second flask, which turns milky white. Side-angle close-up, bright laboratory lighting."
 
51
  ),
52
  "Activity 1.6": (
53
  "Chemistry lab: bright green ferrous sulphate crystals in a dry test tube heated over a "
54
+ "Bunsen burner flame. Crystals gradually change colour from green to reddish-brown with "
55
+ "white fumes rising from the tube. Macro close-up, warm glowing flame."
 
56
  ),
57
  "Activity 1.7": (
58
+ "Science electrolysis experiment: a beaker of water with two carbon electrodes connected "
59
+ "to a battery. Tiny bubbles of hydrogen gas stream from the cathode and oxygen bubbles more "
60
+ "slowly from the anode. Inverted test tubes collect the gases. Macro close-up, bright lab."
 
61
  ),
62
  "Activity 1.8": (
63
  "Chemistry experiment: white sodium carbonate crystals in a test tube heated over a Bunsen "
64
+ "burner. No visible change occurs, crystals remain white showing thermal stability. "
65
+ "Student observes carefully. Wide then close-up shot."
66
  ),
 
 
67
  "Activity 2.1": (
68
+ "Chemistry lab: drops of phenolphthalein indicator added to acid stay colourless, then "
69
+ "added to sodium hydroxide solution turn bright pink instantly. Methyl orange turns red in "
70
+ "acid, yellow in base. Macro close-up, colourful liquid transitions, bright lighting."
 
71
  ),
72
  "Activity 2.2": (
73
+ "Chemistry lab: zinc granules in test tube, dilute hydrochloric acid added causing vigorous "
74
+ "hydrogen gas bubbles. A burning matchstick brought to soap bubbles filled with gas β€” a "
75
+ "small blue flame burns. Close-up, bright lab, gloved hands visible."
 
76
  ),
77
  "Activity 2.3": (
78
  "Science experiment: white marble chips in a conical flask, dilute hydrochloric acid added. "
79
+ "Brisk carbon dioxide bubbles rise. Delivery tube leads gas into lime water in second flask "
80
+ "which turns milky white. Macro close-up, clean laboratory setting."
81
  ),
82
  "Activity 2.4": (
83
+ "Chemistry safety demonstration: water in a glass beaker, concentrated sulphuric acid "
84
+ "carefully added drop by drop along a glass rod. Steam rises as heat is produced. "
85
+ "Wide shot, safety goggles worn, dramatic steam visible."
86
  ),
87
  "Activity 2.5": (
88
+ "Physics-chemistry experiment: a circuit with battery, light bulb and two copper electrodes "
89
+ "dipped in dilute hydrochloric acid. The bulb glows brightly. Electrodes then placed in "
90
+ "glucose solution β€” bulb does not glow. Close-up, clean table, bright lighting."
 
91
  ),
92
  "Activity 2.6": (
93
+ "Titration experiment: sodium hydroxide with phenolphthalein in a conical flask is bright "
94
+ "pink. Student slowly adds hydrochloric acid from a burette. The pink colour gradually fades "
95
+ "until the solution turns completely colourless at the endpoint. Macro close-up."
 
96
  ),
97
  "Activity 2.7": (
98
+ "Chemistry pH experiment: several test tubes containing different solutions. Universal "
99
+ "indicator added to each displays a rainbow of colours from deep red to purple matching a "
100
+ "pH chart. Bright overhead lighting, clean lab bench, colourful comparison."
 
101
  ),
102
  "Activity 2.8": (
103
+ "Crystallisation: blue copper sulphate solution in a china dish heated gently. Water "
104
+ "evaporates and as it cools beautiful vivid blue copper sulphate crystals slowly grow. "
 
105
  "Macro time-lapse, warm light, crystals sparkling."
106
  ),
 
 
107
  "Activity 3.1": (
108
+ "Dramatic chemistry: a magnesium ribbon held in tongs ignites in air burning with an "
109
+ "intensely bright white flame producing white magnesium oxide smoke and ash. "
 
110
  "Slow-motion close-up, dark background, cinematic."
111
  ),
112
  "Activity 3.2": (
113
+ "Reactive metals experiment: a small piece of sodium dropped into a beaker of water β€” it "
114
+ "skims the surface rapidly fizzing and sputtering vigorously as hydrogen gas is produced. "
115
+ "Then calcium dropped in β€” sinks with steady bubbles. Wide and close-up shots."
 
116
  ),
117
  "Activity 3.3": (
118
+ "Chemistry: zinc granules in test tube, dilute hydrochloric acid causes immediate vigorous "
119
+ "hydrogen bubbles. Student tests with burning matchstick β€” audible pop sound confirming "
120
+ "hydrogen gas. Gloved hands, safety goggles, bright lab setting."
121
  ),
122
  "Activity 3.4": (
123
+ "Displacement reaction: clean iron nails placed in bright blue copper sulphate solution. "
124
+ "Over time nail surface gets coated in reddish-brown copper metal deposit while solution "
125
+ "turns from deep blue to light green. Side-angle close-up, time-lapse, clean laboratory."
 
126
  ),
127
  "Activity 3.5": (
128
+ "Chemistry: yellow sulphur powder in a deflagrating spoon ignited in air burns with a pale "
129
+ "blue flame producing pungent sulphur dioxide gas. The gas introduced into a gas jar. "
130
+ "Close-up macro, fume hood visible, clear demonstration."
131
  ),
132
  "Activity 3.6": (
133
+ "Exothermic chemistry reaction: white quicklime lumps in a beaker, water added slowly. "
134
+ "The mixture hisses and steams dramatically as intense heat is released producing slaked "
135
+ "lime paste. Close-up, steam clearly visible, dramatic reaction."
 
136
  ),
137
  "Activity 3.7": (
138
+ "Chemistry: solid sodium chloride crystals placed in circuit β€” bulb does not glow. Then "
139
+ "dissolved in water, electrodes dipped in solution β€” bulb glows brightly. "
140
+ "Clean lab bench, close-up on glowing bulb lighting up."
 
141
  ),
 
 
142
  "Activity 4.1": (
143
+ "Chemistry: charcoal powder burning in a china dish covered by inverted beaker. Carbon "
144
+ "dioxide produced inside tested with blue litmus paper β€” it turns red showing acidic "
145
+ "carbonic acid formed. Close-up, clean lab, step-by-step demonstration."
 
146
  ),
147
  "Activity 4.2": (
148
+ "Science: marble chips in test tube reacting with hydrochloric acid, CO2 bubbles through "
149
+ "delivery tube into lime water which turns milky white instantly. Clear glass apparatus, "
150
+ "close-up on colour change, bright lighting."
151
  ),
152
  "Activity 4.3": (
153
+ "Soap making chemistry: vegetable oil in a beaker, sodium hydroxide solution added. Student "
154
+ "stirs continuously while heating. Mixture thickens into soap, common salt added to "
155
+ "precipitate white soap chunks that float to surface. Wide shot, gloves worn."
 
156
  ),
157
  "Activity 4.4": (
158
+ "Soap cleansing experiment: two test tubes with water and oil. One tube with soap added and "
159
+ "shaken β€” oil emulsifies into tiny droplets, water turns milky. Other tube without soap β€” "
160
+ "oil layer stays separate. Side-by-side comparison, macro, bright lighting."
 
161
  ),
 
 
162
  "Activity 5.1": (
163
+ "Science lab: student hammers copper and sulphur samples. Copper flattens showing "
164
+ "malleability, sulphur shatters showing brittleness. Metals shown lustrous and shiny, "
165
+ "non-metals dull. Cutting with knife: sulphur crumbles. Close-up macro, bright lighting."
 
166
  ),
167
  "Activity 5.2": (
168
+ "Electrical conductivity: simple circuit with bulb and battery. Metal samples placed in "
169
+ "circuit β€” bulb glows brightly. Non-metal samples placed β€” bulb stays off. "
 
170
  "Clean lab bench, close-up on glowing bulb, clear demonstration."
171
  ),
172
  "Activity 5.3": (
173
+ "Elements burning in air: magnesium ribbon burns with bright white flame, sulphur powder "
174
+ "burns with blue flame in deflagrating spoon. Comparison of metal and non-metal combustion. "
 
175
  "Cinematic lab footage, safety equipment visible, close-up flames."
176
  ),
177
  "Activity 5.4": (
178
+ "Chemistry: magnesium oxide dissolved in water tested with red litmus β€” turns blue showing "
179
+ "basic nature. Sulphur dioxide dissolved in water tested with blue litmus β€” turns red "
180
+ "showing acidic nature. Side-by-side comparison, macro close-up on colour changes."
181
  ),
182
  "Activity 5.5": (
183
+ "Classroom: colourful element flash cards spread on a table. Student arranges them in "
184
+ "increasing order of atomic mass, then groups elements with similar properties. Periodic "
185
+ "table pattern emerges. Overhead camera shot, colourful cards, engaging visual."
186
  ),
 
 
187
  "Activity 6.1": (
188
+ "Biology experiment: germinating mung bean seeds in a sealed conical flask. Delivery tube "
189
+ "leads to test tube with clear lime water. Over time lime water turns milky, proving seeds "
190
+ "release carbon dioxide during respiration. Close-up, green seeds visible, clean lab."
 
191
  ),
192
  "Activity 6.2": (
193
+ "Biology microscopy: student carefully peels lower epidermis of a leaf with forceps, places "
194
+ "on glass slide with glycerine, adds cover slip. Microscope view shows oval stomatal pores "
195
+ "with bean-shaped guard cells. Microscope footage, sharp focus, vivid green cells."
 
196
  ),
197
  "Activity 6.3": (
198
+ "Photosynthesis experiment: part of leaf covered with black paper, plant placed in sunlight. "
199
+ "Later leaf decolorised in boiling alcohol then iodine applied β€” uncovered part turns "
200
+ "blue-black showing starch, covered part stays yellow-brown. Split-screen comparison."
 
201
  ),
202
  "Activity 6.4": (
203
+ "Biology experiment: plant leaf inside bottle with potassium hydroxide absorbing CO2. Plant "
204
+ "in sunlight. Leaf tested with iodine β€” stays yellow-brown showing no starch without CO2. "
205
+ "Control leaf without KOH turns blue-black. Side-by-side comparison, clear science lab."
 
206
  ),
207
  "Activity 6.5": (
208
+ "Starch test: green leaf boiled in water then alcohol removes chlorophyll. Leaf turns pale "
209
+ "yellow. Washed in warm water, iodine solution added β€” leaf turns blue-black showing starch "
210
+ "present. Macro close-up, step-by-step demonstration, bright lighting."
 
211
  ),
212
  "Activity 6.6": (
213
+ "Biology microscopy: student gently scrapes inner cheek with clean toothpick, spreads cells "
214
+ "on slide with glycerine, adds methylene blue stain. Microscope view shows flat irregular "
215
+ "human cheek cells with purple-stained nucleus visible. Sharp microscope footage."
 
216
  ),
217
  "Activity 6.7": (
218
+ "Plant cell microscopy: student peels thin transparent layer from inside of onion, places on "
219
+ "slide with iodine solution, covers with cover slip. Microscope shows rectangular onion cells "
220
+ "with clear cell walls and brown-stained nuclei. Sharp microscope footage."
 
221
  ),
222
  "Activity 6.8": (
223
+ "Biology demonstration of peristalsis: a flexible rubber tube with a marble inside. Student "
224
+ "squeezes tube rhythmically behind the marble pushing it forward, simulating food movement "
225
+ "in the oesophagus. Close-up hand demonstration, simple and clear."
 
226
  ),
227
  "Activity 6.9": (
228
+ "Enzyme experiment: starch solution in test tube, human saliva added and tube kept warm. "
229
+ "After a few minutes iodine test performed β€” iodine does not turn blue-black, showing starch "
230
+ "digested by salivary amylase enzyme. Step-by-step close-up, clean biology lab."
 
231
  ),
232
  "Activity 6.10": (
233
+ "Biology breathing model: a bell jar with two balloons representing lungs, rubber sheet at "
234
+ "base representing diaphragm. Student pulls rubber sheet down β€” balloons inflate showing "
235
+ "inhalation. Pushes up β€” balloons deflate showing exhalation. Clear demonstration."
 
236
  ),
 
 
237
  "Activity 7.1": (
238
+ "Plant biology time-lapse: a climbing plant tendril gently touches a thin wooden stick. Over "
239
+ "hours the tendril slowly coils around the stick in a tight spiral showing thigmotropism. "
240
+ "Macro time-lapse, green tendril on white background."
241
  ),
242
  "Activity 7.2": (
243
+ "Plant geotropism: germinating bean seeds placed horizontally in moist sawdust in a glass "
244
+ "jar. Time-lapse over two days shows the white radicle bending downward toward gravity "
245
+ "regardless of seed orientation. Clear glass jar, macro time-lapse footage."
 
246
  ),
247
  "Activity 7.3": (
248
+ "Phototropism experiment: a young seedling in a pot inside a cardboard box with a small hole "
249
+ "on one side. Light enters from one side only. Over days the shoot bends and curves toward "
250
+ "the light source. Side-angle time-lapse, bright light visible through hole."
 
251
  ),
252
  "Activity 7.4": (
253
+ "Plant growth: two identical seedlings β€” one with shoot tip covered by foil, one uncovered. "
254
+ "Both exposed to one-sided light. Uncovered plant bends toward light; covered plant grows "
255
+ "straight. Side-by-side time-lapse comparison."
256
  ),
257
  "Activity 7.5": (
258
+ "Human biology: close-up of a tongue with different solutions applied to different areas "
259
+ "using cotton buds β€” sweet at tip, salty at sides, sour at edges, bitter at back. "
260
+ "Facial expressions show taste sensations. Clean close-up footage."
 
261
  ),
262
  "Activity 7.6": (
263
+ "Reflex action: a ruler held vertically by a student, dropped without warning β€” the student "
264
+ "catches it quickly below the drop point. Slow-motion replay shows the fast involuntary "
265
+ "reflex catch. Slow-motion footage, clear close-up of hand and ruler."
 
266
  ),
267
  "Activity 7.7": (
268
+ "Biology: an earthworm on a tray gently touched with a soft brush on different body "
269
+ "segments. The worm immediately retracts and moves away from each touch stimulus. "
270
  "Close-up macro, natural lighting, careful humane handling."
271
  ),
272
  "Activity 7.8": (
273
+ "Plant hormone experiment: two identical plants β€” one with auxin hormone applied to shoot "
274
+ "tip, one with plain water. Over days the auxin plant shows enhanced elongated growth "
275
+ "compared to control. Side-by-side comparison, time-lapse footage."
276
  ),
 
 
277
  "Activity 8.1": (
278
  "Biology microscopy: a drop of Amoeba culture on a glass slide under high magnification. "
279
+ "The single-celled organism undergoes binary fission β€” nucleus divides, cytoplasm pinches "
280
+ "and splits into two identical daughter cells. Microscope footage, clear division visible."
 
281
  ),
282
  "Activity 8.2": (
283
+ "Yeast microscopy: yeast cells in sugar solution on a glass slide. Under microscope small "
284
+ "oval yeast cells show tiny buds forming on their surface showing budding reproduction. "
285
+ "Time-lapse microscope footage, clear buds visible."
286
  ),
287
  "Activity 8.3": (
288
  "Fungal biology: Rhizopus mold growing on moist bread β€” black sporangia on upright stalks "
289
+ "visible with magnifying lens. Microscope slide of sporangia shows tiny round spores "
290
+ "released. Macro and microscope footage combined."
291
  ),
292
  "Activity 8.4": (
293
+ "Plant propagation: a hibiscus stem cut below a node with a clean blade, cut end dipped in "
294
+ "rooting hormone powder, planted in moist soil. Time-lapse shows new white roots emerging "
295
+ "from the cut end, then new green leaves. Close-up, natural garden light."
 
296
  ),
297
  "Activity 8.5": (
298
+ "Seed anatomy: soaked gram seeds with seed coat removed. Student splits seed carefully to "
299
+ "reveal white embryo inside showing tiny radicle and plumule within cotyledons. "
300
+ "Macro close-up, bright lighting, educational."
 
301
  ),
302
  "Activity 8.6": (
303
+ "Flower dissection biology: a large Hibiscus flower dissected on a white tray. Student "
304
+ "separates green sepals, pink petals, stamens with yellow pollen-covered anthers, and "
305
+ "central pistil. Cross-section shows ovary with ovules inside. Macro overhead shot."
 
306
  ),
307
  "Activity 8.7": (
308
+ "Pollination experiment: a small paintbrush collects yellow pollen from anther of one "
309
+ "flower and gently brushes onto sticky stigma of another flower. Flower tagged. Days later "
310
+ "fruit development visible where pollination occurred. Macro close-up, bright natural light."
 
311
  ),
312
  "Activity 8.8": (
313
  "Seed germination time-lapse: soaked gram seeds on moist cotton in a clear glass container. "
314
+ "Time-lapse shows the tiny white radicle emerging first curving downward, then the green "
315
+ "plumule pushing upward through cotton. Macro time-lapse, bright natural lighting."
 
316
  ),
 
 
317
  "Activity 9.1": (
318
+ "Biology genetics: multiple pea pods from different plants spread on a white tray. Student "
319
+ "opens each pod and counts seeds β€” variation in number clearly visible across pods. "
320
+ "Overhead shot, close-up counting, educational."
321
  ),
322
  "Activity 9.2": (
323
  "Genetics activity: family photographs pinned on a board. Student examines and marks "
324
+ "physical traits tracking which relatives share which traits across generations. "
325
+ "Educational, family-friendly footage."
326
  ),
327
  "Activity 9.3": (
328
+ "Genetics model: coloured beads representing dominant and recessive alleles. Student pairs "
329
+ "beads to simulate Mendelian inheritance showing Rr, RR, rr genotypes. Punnett square drawn "
330
+ "alongside. Overhead shot, colourful beads on white table."
331
  ),
332
  "Activity 9.4": (
333
+ "Evolution demonstration: light and dark paper moth cutouts scattered on white and black "
334
+ "paper backgrounds. A student picks up visible moths. Dark moths survive on dark background, "
335
+ "light moths on light background β€” natural selection visualised. Overhead camera."
 
336
  ),
337
  "Activity 9.5": (
338
  "Palaeontology study: fossil specimens on a table β€” ammonites, trilobites, plant fossils. "
 
340
  "Close-up of detailed fossil textures, educational museum-style footage."
341
  ),
342
  "Activity 9.6": (
343
+ "Genetics: student draws a family pedigree chart on paper β€” squares for males, circles for "
344
+ "females, shaded shapes for trait carriers. Shows inheritance pattern across three "
345
+ "generations. Overhead close-up, clear diagrams drawn in real-time."
346
  ),
347
  "Activity 9.7": (
348
+ "Biology activity: student lists traits in two columns β€” acquired traits like haircut and "
349
+ "scar versus inherited traits like eye colour and tongue rolling. Interactive classroom "
350
+ "demonstration with volunteers showing tongue rolling ability. Friendly classroom footage."
 
351
  ),
352
  "Activity 9.8": (
353
  "Evolution model: paper cutouts of finches with different beak shapes β€” thick seed-cracker, "
354
+ "thin insect-prober, curved cactus-feeder. Student tests which beak shape picks up each "
355
+ "food type most efficiently. Overhead shot, colourful engaging demonstration."
 
356
  ),
 
 
357
  "Activity 10.1": (
358
  "Physics optics experiment: a plane mirror mounted vertically on a white drawing sheet. "
359
+ "Student positions two pins to mark an incident ray of light toward the mirror. Views "
360
+ "reflected pins from other side. Protractor shows angle of incidence equals angle of "
361
+ "reflection. Overhead close-up, bright lab lighting."
362
  ),
363
  "Activity 10.2": (
364
+ "Light refraction experiment: a glass rectangular slab on white paper, two pins marking an "
365
+ "incident ray. Light ray enters glass slab and bends toward normal then bends away on exit, "
366
+ "emerging parallel to original ray. Overhead shot, clear glass slab visible."
 
367
  ),
368
  "Activity 10.3": (
369
  "Optics experiment: concave mirror on stand, lit candle in front at various distances. "
370
+ "White screen positioned to catch image β€” shows inverted enlarged image beyond C, then "
371
+ "diminished image. Side-angle footage, glowing candle flame, clear image on white screen."
 
372
  ),
373
  "Activity 10.4": (
374
+ "Physics optics: convex mirror on stand, candle placed in front. Student looks into convex "
375
+ "mirror and sees small upright virtual image of candle. No real image forms on screen placed "
376
+ "behind mirror. Close-up of mirror reflection, wide-angle view of setup."
 
377
  ),
378
  "Activity 10.5": (
379
+ "Concave lens optics: a concave lens mounted on stand, candle in front. No real image forms "
380
+ "on screen. Student looks through lens and sees small upright virtual image. "
 
381
  "Side-angle footage, bright lab, clear lens visible."
382
  ),
383
  "Activity 10.6": (
384
+ "Convex lens experiment: convex lens on stand, candle at different distances. Screen adjusted "
385
+ "to catch sharp images β€” real inverted enlarged image when object between F and 2F. "
 
386
  "Clear footage of candle image forming sharply on white screen."
387
  ),
388
  "Activity 10.7": (
389
+ "Focal length measurement: convex lens held facing a distant object outside window. White "
390
+ "screen moved behind lens until a sharp image of the distant object forms. Ruler measures "
391
+ "lens-to-screen distance as focal length. Bright natural light, clear measurement shown."
 
392
  ),
393
  "Activity 10.8": (
394
  "Prism optics experiment: a triangular glass prism on white paper, pins marking incident ray. "
395
+ "Light ray enters prism, bends at both surfaces and exits at a deviation angle. Student "
396
+ "traces refracted and emergent ray paths on paper. Overhead close-up, clear glass prism."
 
397
  ),
398
  "Activity 10.9": (
399
+ "Light dispersion: a glass triangular prism in a beam of white sunlight entering through a "
400
+ "narrow slit separates white light into a beautiful spectrum β€” violet, indigo, blue, green, "
401
+ "yellow, orange, red β€” projected on a white screen. Dramatic cinematic close-up, vivid."
 
402
  ),
403
  }
404
 
405
 
406
  def _get_prompt(exp: dict) -> str:
 
 
407
  match = re.match(r"(Activity \d+\.\d+)", exp["title"])
408
  if match:
409
  key = match.group(1)
410
  if key in VEO_PROMPTS:
411
  return VEO_PROMPTS[key]
412
+ # Generic fallback
413
  return (
414
+ f"Close-up science laboratory experiment demonstrating: {exp['title']}. "
415
+ f"A student carefully performs the experiment step by step in a clean science lab. "
416
+ f"The result shows: {exp['outcome'][:100]}. "
417
+ f"Cinematic educational science video, bright professional lighting."
 
418
  )
419
 
420
 
421
  def generate_experiment_video(exp: dict, output_dir: str = None) -> str | None:
422
  """
423
+ Generate a real AI video using Gemini Veo 3.1.
424
+ Returns path to saved MP4 file, or None on failure.
 
 
425
  """
426
  api_key = os.environ.get("GEMINI_API_KEY", "")
427
  if not api_key:
428
+ print("ERROR: GEMINI_API_KEY environment variable not set")
429
  return None
430
 
431
  try:
432
  from google import genai
433
  from google.genai import types
434
  except ImportError:
435
+ print("ERROR: google-genai not installed. Add 'google-genai>=1.0.0' to requirements.txt")
436
  return None
437
 
438
  if output_dir is None:
 
441
  output_dir.mkdir(parents=True, exist_ok=True)
442
 
443
  prompt = _get_prompt(exp)
444
+ print(f"\n--- Veo Video Generation ---")
445
+ print(f"Experiment : {exp['title']}")
446
+ print(f"Prompt : {prompt[:100]}...")
447
 
448
  try:
449
  client = genai.Client(api_key=api_key)
450
 
451
+ # ── Submit generation request ───────────────────────────────────────
452
+ # NOTE: Only use params supported by Gemini API (not Vertex AI)
453
+ # duration_seconds, resolution, fps, seed are Vertex AI only
454
  operation = client.models.generate_videos(
455
  model="veo-3.1-generate-preview",
456
  prompt=prompt,
457
  config=types.GenerateVideosConfig(
458
+ number_of_videos=1,
459
+ enhance_prompt=True,
460
+ # generate_audio=False, # set True if you want native audio (costs more)
461
  ),
462
  )
463
+ print(f"Operation submitted: {getattr(operation, 'name', 'unknown')}")
464
 
465
+ except Exception as e:
466
+ print(f"ERROR submitting to Veo: {type(e).__name__}: {e}")
467
+ # Common causes:
468
+ # 400 β†’ invalid param (check config)
469
+ # 403 β†’ billing not enabled or API not activated
470
+ # 429 β†’ quota exceeded
471
+ return None
472
 
473
+ # ── Poll until complete ─────────────────────────────────────────────────
474
+ max_wait = 360 # 6 minutes max
475
+ elapsed = 0
476
+ interval = 15 # poll every 15 seconds
477
+
478
+ print("Polling Veo (every 15s, max 6 min):", end="", flush=True)
479
+ try:
480
  while not operation.done:
481
  if elapsed >= max_wait:
482
+ print(f"\nERROR: Timed out after {max_wait}s")
483
  return None
484
  time.sleep(interval)
485
  elapsed += interval
486
+ print(f"..{elapsed}s", end="", flush=True)
487
  operation = client.operations.get(operation)
488
+ except Exception as e:
489
+ print(f"\nERROR during polling: {type(e).__name__}: {e}")
490
+ return None
491
 
492
+ print(" Done!")
493
 
494
+ # ── Extract video ───────────────────────────────────────────────────────
495
+ try:
496
+ if not operation.response:
497
+ print("ERROR: operation.response is None")
498
  return None
499
 
500
+ generated_videos = getattr(operation.response, "generated_videos", None)
501
+ if not generated_videos:
502
+ print("ERROR: no generated_videos in response")
503
+ print(f"Full response: {operation.response}")
504
+ return None
505
 
506
+ gen_video = generated_videos[0]
507
+ video_obj = gen_video.video
 
508
 
509
+ if video_obj is None:
510
+ print("ERROR: video object is None")
511
  return None
512
 
513
+ # ── Download video bytes ────────────────────────────────────────────
514
+ # The Files API populates video_bytes after download()
515
+ client.files.download(file=video_obj)
516
+
517
+ # Save using the SDK's save() method
518
  safe_title = re.sub(r"[^\w]", "_", exp["title"])[:40]
519
  output_path = output_dir / f"{safe_title}.mp4"
520
+ video_obj.save(str(output_path))
521
+
522
+ if output_path.exists() and output_path.stat().st_size > 0:
523
+ size_kb = output_path.stat().st_size // 1024
524
+ print(f"Video saved: {output_path} ({size_kb} KB)")
525
+ return str(output_path)
526
+ else:
527
+ print("ERROR: video file is empty or was not created")
528
+ return None
529
 
530
  except Exception as e:
531
+ print(f"ERROR saving video: {type(e).__name__}: {e}")
532
+ return None