ViewAppV02 / app.py
sohfossted's picture
Upload app.py
995f14c verified
import gradio as gr
import os
import tempfile
from datetime import datetime
import logging
import json
from ai_enhance import AIEnhance
from presentation_generator import PresentationGenerator
# Configuration logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Initialisation des services
ai_service = AIEnhance()
presentation_generator = PresentationGenerator()
def create_presentation_structure(texte):
"""Crée la structure de présentation avec analyse IA"""
analysis = ai_service.analyze_text_advanced(texte)
summary = ai_service.smart_summarize(texte)
structure = {
"title": f"Présentation: {analysis['content_analysis'].capitalize()}",
"slides": analysis["recommended_structure"]["slides"],
"key_points": analysis["keywords"][:8],
"style_recommendation": analysis["recommended_structure"]["recommended_style"],
"analysis_metadata": analysis
}
return structure, summary
def generate_presentation_gradio(texte, style="professionnel"):
"""Version Gradio de votre fonction generate()"""
try:
if not texte or len(texte.strip()) < 50:
return None, "❌ Veuillez entrer au moins 50 caractères."
logger.info(f"🚀 Génération IA pour {len(texte)} caractères")
# VOTRE LOGIQUE EXISTANTE
structure, summary = create_presentation_structure(texte)
filename = presentation_generator.generate_presentation(structure, style)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
download_filename = f"presentation_ia_{timestamp}.pptx"
logger.info("✅ Présentation générée avec succès!")
return filename, f"🎉 Présentation générée! ({len(structure['slides'])} slides)"
except Exception as e:
logger.error(f"❌ Erreur lors de la génération: {e}")
return None, f"❌ Erreur: {str(e)}"
def analyze_text_gradio(texte):
"""Version Gradio de votre api_analyze()"""
try:
if not texte or len(texte.strip()) < 10:
return "❌ Texte trop court. Minimum 10 caractères."
# VOTRE LOGIQUE EXISTANTE
structure, summary = create_presentation_structure(texte)
# Formatage pour l'interface Gradio
result = f"""
## 📊 Analyse IA du Texte
**Statistiques:**
- {structure['analysis_metadata']['statistics']['word_count']} mots
- {structure['analysis_metadata']['statistics']['sentence_count']} phrases
- {structure['analysis_metadata']['statistics']['paragraph_count']} paragraphes
**🎯 Thèmes identifiés:**
{', '.join(structure['key_points'][:8])}
**📝 Résumé:**
{summary}
**🏗️ Structure proposée:**
"""
for i, slide in enumerate(structure['slides']):
result += f"\n{i+1}. **{slide['title']}** - {slide['content'][:100]}..."
return result
except Exception as e:
return f"❌ Erreur d'analyse: {str(e)}"
def summarize_text_gradio(texte):
"""Version Gradio de votre api_summarize()"""
try:
if not texte.strip():
return "❌ Texte manquant"
# VOTRE LOGIQUE EXISTANTE
summary = ai_service.smart_summarize(texte)
return f"**📄 Résumé:**\n\n{summary}"
except Exception as e:
return f"❌ Erreur résumé: {str(e)}"
# INTERFACE GRADIO
with gr.Blocks(theme=gr.themes.Soft(), title="Générateur de Présentation IA") as demo:
gr.Markdown("# 🧠 Générateur de Présentation IA Intelligente")
gr.Markdown("Powered by Lab_Math_and Labhp & CIE Label_Bertoua")
with gr.Tab("🚀 Générer Présentation"):
with gr.Row():
with gr.Column():
text_input = gr.Textbox(
label="📝 Collez votre texte ici",
placeholder="Collez ou tapez votre texte, article, rapport...",
lines=10,
max_lines=20
)
style_dropdown = gr.Dropdown(
choices=["professionnel", "moderne", "creatif"],
label="🎨 Style de présentation",
value="professionnel"
)
generate_btn = gr.Button("🚀 Générer la Présentation", variant="primary")
with gr.Column():
output_file = gr.File(label="📥 Présentation Générée")
output_message = gr.Textbox(label="📋 Statut", interactive=False)
generate_btn.click(
fn=generate_presentation_gradio,
inputs=[text_input, style_dropdown],
outputs=[output_file, output_message]
)
with gr.Tab("🔍 Analyser le Texte"):
with gr.Row():
with gr.Column():
analyze_text_input = gr.Textbox(
label="📝 Texte à analyser",
placeholder="Collez votre texte pour l'analyse IA...",
lines=8
)
analyze_btn = gr.Button("🔍 Analyser avec IA", variant="secondary")
with gr.Column():
analysis_output = gr.Markdown(label="📊 Résultats de l'analyse")
analyze_btn.click(
fn=analyze_text_gradio,
inputs=[analyze_text_input],
outputs=[analysis_output]
)
with gr.Tab("📄 Résumer le Texte"):
with gr.Row():
with gr.Column():
summarize_text_input = gr.Textbox(
label="📝 Texte à résumer",
placeholder="Collez votre texte pour le résumé IA...",
lines=8
)
summarize_btn = gr.Button("📊 Générer Résumé", variant="secondary")
with gr.Column():
summary_output = gr.Markdown(label="📋 Résumé généré")
summarize_btn.click(
fn=summarize_text_gradio,
inputs=[summarize_text_input],
outputs=[summary_output]
)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)