Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -10,33 +10,44 @@ from PIL import Image
|
|
10 |
import os
|
11 |
import logging
|
12 |
import tempfile
|
|
|
|
|
13 |
|
14 |
logging.basicConfig(level=logging.INFO)
|
15 |
logger = logging.getLogger(__name__)
|
16 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
class MultimodalProcessor:
|
18 |
def __init__(self):
|
|
|
19 |
self.load_models()
|
20 |
-
self.temp_dir = tempfile.mkdtemp()
|
21 |
|
22 |
def load_models(self):
|
23 |
"""Charge les modèles"""
|
24 |
try:
|
25 |
logger.info("Chargement des modèles...")
|
26 |
-
# BLIP pour l'analyse d'image
|
27 |
self.blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
28 |
self.blip_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
|
29 |
-
|
30 |
-
# Whisper pour la transcription audio
|
31 |
self.audio_transcriber = pipeline("automatic-speech-recognition",
|
32 |
model="openai/whisper-base")
|
33 |
-
|
34 |
-
# ModelScope pour la génération vidéo
|
35 |
self.video_pipeline = ms_pipeline(
|
36 |
'text-to-video-synthesis',
|
37 |
model='damo/text-to-video-synthesis'
|
38 |
)
|
39 |
-
|
40 |
logger.info("Modèles chargés avec succès")
|
41 |
except Exception as e:
|
42 |
logger.error(f"Erreur lors du chargement des modèles: {str(e)}")
|
@@ -44,16 +55,14 @@ class MultimodalProcessor:
|
|
44 |
|
45 |
def analyze_image(self, image):
|
46 |
"""Analyse une image avec BLIP"""
|
|
|
|
|
47 |
try:
|
48 |
-
if image is None:
|
49 |
-
return ""
|
50 |
-
|
51 |
questions = [
|
52 |
"What is in the picture?",
|
53 |
"What are the main colors?",
|
54 |
"What is the setting or background?"
|
55 |
]
|
56 |
-
|
57 |
responses = {}
|
58 |
for question in questions:
|
59 |
inputs = self.blip_processor(images=image, text=question, return_tensors="pt")
|
@@ -66,7 +75,6 @@ class MultimodalProcessor:
|
|
66 |
f"The main colors are {responses['What are the main colors?']}. "
|
67 |
f"The setting is {responses['What is the setting or background?']}."
|
68 |
)
|
69 |
-
|
70 |
return description
|
71 |
except Exception as e:
|
72 |
logger.error(f"Erreur lors de l'analyse de l'image: {str(e)}")
|
@@ -74,9 +82,9 @@ class MultimodalProcessor:
|
|
74 |
|
75 |
def transcribe_audio(self, audio_path):
|
76 |
"""Transcrit un fichier audio avec Whisper"""
|
|
|
|
|
77 |
try:
|
78 |
-
if audio_path is None:
|
79 |
-
return ""
|
80 |
return self.audio_transcriber(audio_path)["text"]
|
81 |
except Exception as e:
|
82 |
logger.error(f"Erreur lors de la transcription audio: {str(e)}")
|
@@ -84,19 +92,24 @@ class MultimodalProcessor:
|
|
84 |
|
85 |
def generate_video(self, prompt):
|
86 |
"""Génère une vidéo avec ModelScope"""
|
|
|
|
|
87 |
try:
|
88 |
-
|
89 |
-
return None
|
90 |
-
|
91 |
-
output_path = os.path.join(self.temp_dir, "output.mp4")
|
92 |
result = self.video_pipeline({
|
93 |
'text': prompt,
|
94 |
'output_path': output_path
|
95 |
})
|
96 |
|
97 |
-
if os.path.exists(output_path):
|
98 |
-
|
99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
|
101 |
except Exception as e:
|
102 |
logger.error(f"Erreur lors de la génération de vidéo: {str(e)}")
|
@@ -107,36 +120,30 @@ class MultimodalProcessor:
|
|
107 |
try:
|
108 |
combined_parts = []
|
109 |
|
110 |
-
# Analyse de l'image si présente
|
111 |
if image is not None:
|
112 |
image_desc = self.analyze_image(image)
|
113 |
if image_desc:
|
114 |
combined_parts.append(f"Scene: {image_desc}")
|
115 |
|
116 |
-
# Transcription audio si présent
|
117 |
if audio is not None:
|
118 |
audio_text = self.transcribe_audio(audio)
|
119 |
if audio_text:
|
120 |
combined_parts.append(f"Audio narration: {audio_text}")
|
121 |
|
122 |
-
# Ajout du texte si présent
|
123 |
if text:
|
124 |
combined_parts.append(f"Additional context: {text}")
|
125 |
|
126 |
-
|
127 |
-
if combined_parts:
|
128 |
-
final_prompt = " ".join(combined_parts)
|
129 |
-
else:
|
130 |
-
final_prompt = "Empty scene with neutral background"
|
131 |
|
132 |
-
# Génération de la vidéo
|
133 |
output_video = self.generate_video(final_prompt)
|
134 |
-
|
135 |
return output_video, final_prompt
|
136 |
|
137 |
except Exception as e:
|
138 |
logger.error(f"Erreur lors du traitement des entrées: {str(e)}")
|
139 |
return None, "Une erreur est survenue lors du traitement des entrées."
|
|
|
|
|
|
|
140 |
|
141 |
def create_interface():
|
142 |
"""Crée l'interface Gradio"""
|
@@ -163,7 +170,6 @@ def create_interface():
|
|
163 |
4. Générer une vidéo basée sur la description combinée
|
164 |
"""
|
165 |
)
|
166 |
-
|
167 |
return interface
|
168 |
|
169 |
if __name__ == "__main__":
|
|
|
10 |
import os
|
11 |
import logging
|
12 |
import tempfile
|
13 |
+
import shutil
|
14 |
+
import atexit
|
15 |
|
16 |
logging.basicConfig(level=logging.INFO)
|
17 |
logger = logging.getLogger(__name__)
|
18 |
|
19 |
+
class TempFileManager:
|
20 |
+
def __init__(self):
|
21 |
+
self.temp_dir = tempfile.mkdtemp(prefix='multimodal_app_')
|
22 |
+
atexit.register(self.cleanup)
|
23 |
+
|
24 |
+
def get_path(self, filename):
|
25 |
+
return os.path.join(self.temp_dir, filename)
|
26 |
+
|
27 |
+
def cleanup(self):
|
28 |
+
try:
|
29 |
+
if os.path.exists(self.temp_dir):
|
30 |
+
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
31 |
+
except Exception as e:
|
32 |
+
logger.error(f"Erreur lors du nettoyage des fichiers temporaires: {str(e)}")
|
33 |
+
|
34 |
class MultimodalProcessor:
|
35 |
def __init__(self):
|
36 |
+
self.temp_manager = TempFileManager()
|
37 |
self.load_models()
|
|
|
38 |
|
39 |
def load_models(self):
|
40 |
"""Charge les modèles"""
|
41 |
try:
|
42 |
logger.info("Chargement des modèles...")
|
|
|
43 |
self.blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
|
44 |
self.blip_model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
|
|
|
|
|
45 |
self.audio_transcriber = pipeline("automatic-speech-recognition",
|
46 |
model="openai/whisper-base")
|
|
|
|
|
47 |
self.video_pipeline = ms_pipeline(
|
48 |
'text-to-video-synthesis',
|
49 |
model='damo/text-to-video-synthesis'
|
50 |
)
|
|
|
51 |
logger.info("Modèles chargés avec succès")
|
52 |
except Exception as e:
|
53 |
logger.error(f"Erreur lors du chargement des modèles: {str(e)}")
|
|
|
55 |
|
56 |
def analyze_image(self, image):
|
57 |
"""Analyse une image avec BLIP"""
|
58 |
+
if image is None:
|
59 |
+
return ""
|
60 |
try:
|
|
|
|
|
|
|
61 |
questions = [
|
62 |
"What is in the picture?",
|
63 |
"What are the main colors?",
|
64 |
"What is the setting or background?"
|
65 |
]
|
|
|
66 |
responses = {}
|
67 |
for question in questions:
|
68 |
inputs = self.blip_processor(images=image, text=question, return_tensors="pt")
|
|
|
75 |
f"The main colors are {responses['What are the main colors?']}. "
|
76 |
f"The setting is {responses['What is the setting or background?']}."
|
77 |
)
|
|
|
78 |
return description
|
79 |
except Exception as e:
|
80 |
logger.error(f"Erreur lors de l'analyse de l'image: {str(e)}")
|
|
|
82 |
|
83 |
def transcribe_audio(self, audio_path):
|
84 |
"""Transcrit un fichier audio avec Whisper"""
|
85 |
+
if audio_path is None:
|
86 |
+
return ""
|
87 |
try:
|
|
|
|
|
88 |
return self.audio_transcriber(audio_path)["text"]
|
89 |
except Exception as e:
|
90 |
logger.error(f"Erreur lors de la transcription audio: {str(e)}")
|
|
|
92 |
|
93 |
def generate_video(self, prompt):
|
94 |
"""Génère une vidéo avec ModelScope"""
|
95 |
+
if not prompt:
|
96 |
+
return None
|
97 |
try:
|
98 |
+
output_path = self.temp_manager.get_path("output.mp4")
|
|
|
|
|
|
|
99 |
result = self.video_pipeline({
|
100 |
'text': prompt,
|
101 |
'output_path': output_path
|
102 |
})
|
103 |
|
104 |
+
if not os.path.exists(output_path):
|
105 |
+
raise Exception("La vidéo n'a pas été générée correctement")
|
106 |
+
|
107 |
+
# Copie la vidéo vers un emplacement permanent si nécessaire
|
108 |
+
permanent_path = f"outputs/video_{hash(prompt)}.mp4"
|
109 |
+
os.makedirs(os.path.dirname(permanent_path), exist_ok=True)
|
110 |
+
shutil.copy2(output_path, permanent_path)
|
111 |
+
|
112 |
+
return permanent_path
|
113 |
|
114 |
except Exception as e:
|
115 |
logger.error(f"Erreur lors de la génération de vidéo: {str(e)}")
|
|
|
120 |
try:
|
121 |
combined_parts = []
|
122 |
|
|
|
123 |
if image is not None:
|
124 |
image_desc = self.analyze_image(image)
|
125 |
if image_desc:
|
126 |
combined_parts.append(f"Scene: {image_desc}")
|
127 |
|
|
|
128 |
if audio is not None:
|
129 |
audio_text = self.transcribe_audio(audio)
|
130 |
if audio_text:
|
131 |
combined_parts.append(f"Audio narration: {audio_text}")
|
132 |
|
|
|
133 |
if text:
|
134 |
combined_parts.append(f"Additional context: {text}")
|
135 |
|
136 |
+
final_prompt = " ".join(combined_parts) if combined_parts else "Empty scene with neutral background"
|
|
|
|
|
|
|
|
|
137 |
|
|
|
138 |
output_video = self.generate_video(final_prompt)
|
|
|
139 |
return output_video, final_prompt
|
140 |
|
141 |
except Exception as e:
|
142 |
logger.error(f"Erreur lors du traitement des entrées: {str(e)}")
|
143 |
return None, "Une erreur est survenue lors du traitement des entrées."
|
144 |
+
finally:
|
145 |
+
# Nettoyage explicite des fichiers temporaires après chaque traitement
|
146 |
+
self.temp_manager.cleanup()
|
147 |
|
148 |
def create_interface():
|
149 |
"""Crée l'interface Gradio"""
|
|
|
170 |
4. Générer une vidéo basée sur la description combinée
|
171 |
"""
|
172 |
)
|
|
|
173 |
return interface
|
174 |
|
175 |
if __name__ == "__main__":
|