Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import logging | |
| import random | |
| from openai import OpenAI | |
| import smtplib | |
| from email.mime.multipart import MIMEMultipart | |
| from email.mime.text import MIMEText | |
| import threading | |
| import time | |
| from tqdm import tqdm | |
| from dotenv import load_dotenv | |
| import os | |
| # Charger les variables d'environnement | |
| load_dotenv() | |
| client = OpenAI(api_key=os.getenv('OPENAI_API_KEY')) | |
| logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') | |
| categories = ["Nature", "Technologie", "Histoire", "Fantaisie", "Sports", "Arts", "Sciences", "Cuisine", "Voyage", "Musique"] | |
| def query(prompt, max_tokens=100): | |
| try: | |
| response = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=max_tokens, | |
| temperature=random.uniform(0.7, 1.2) | |
| ) | |
| return response.choices[0].message.content.strip() | |
| except Exception as e: | |
| logging.error(f"Erreur de requête API: {e}") | |
| return None | |
| def generate_single_theme(prompt, age_group, budget, location, index, used_categories): | |
| available_categories = [cat for cat in categories if cat not in used_categories] | |
| if not available_categories: | |
| return "Erreur: Pas de catégorie disponible", None | |
| category = random.choice(available_categories) | |
| full_prompt = (f"Thème {index}: Génère un thème de fête créatif et original basé sur : '{prompt}' " | |
| f"et la catégorie '{category}'. Pour un groupe d'âge {age_group}, avec un budget {budget}, " | |
| f"à organiser {location}. Le thème doit être unique et amusant en une phrase courte.") | |
| theme = query(full_prompt) | |
| return theme, category | |
| def translate_theme(theme): | |
| prompt = f"Traduis ce thème de fête en anglais : '{theme}'\nTraduction :" | |
| return query(prompt) | |
| def format_results(results): | |
| formatted = "# 🎉 Thèmes de fête générés\n\n" | |
| for i, theme in enumerate(results["themes"], 1): | |
| formatted += f"## Thème {i}: {theme['theme']}\n\n" | |
| formatted += f"**Traduction:** {theme['translation']}\n\n" | |
| formatted += "---\n\n" | |
| return formatted | |
| def generate_and_format(prompt, num_themes, age_group_val, budget_val, location_val, progress=gr.Progress()): | |
| results = {"themes": []} | |
| used_categories = set() | |
| for i in range(int(num_themes)): | |
| theme, category = generate_single_theme(prompt, age_group_val, budget_val, location_val, i+1, used_categories) | |
| if category: | |
| used_categories.add(category) | |
| translation = translate_theme(theme) | |
| results["themes"].append({"theme": theme, "translation": translation}) | |
| progress((i + 1) / int(num_themes)) | |
| formatted_results = format_results(results) | |
| developed_theme_output.value = "" | |
| developed_theme_output.visible = False | |
| return formatted_results, results | |
| def run_query(prompt, max_tokens=2000): | |
| try: | |
| response = client.chat.completions.create( | |
| model="gpt-4o-mini", | |
| messages=[{"role": "user", "content": prompt}], | |
| max_tokens=max_tokens, | |
| temperature=random.uniform(0.7, 1.2) | |
| ) | |
| return response.choices[0].message.content.strip() | |
| except Exception as e: | |
| logging.error(f"Erreur de requête API: {e}") | |
| return None | |
| def develop_theme(theme, age_group, budget, location): | |
| prompt = ( | |
| f"Développe un plan d'action détaillé pour organiser une fête sur le thème : '{theme}'. " | |
| f"Pour un groupe d'âge {age_group}, avec un budget {budget}, à organiser {location}. " | |
| f"Inclus des idées concrètes pour la décoration, les activités, la nourriture, les boissons et la musique." | |
| ) | |
| result = None | |
| thread = threading.Thread(target=lambda: setattr(threading.current_thread(), 'result', run_query(prompt))) | |
| thread.start() | |
| with tqdm(total=100, desc="Recherche en cours") as pbar: | |
| while thread.is_alive(): | |
| time.sleep(0.1) | |
| pbar.update(1) | |
| if pbar.n >= 100: | |
| pbar.n = 0 | |
| pbar.refresh() | |
| thread.join() | |
| developed_theme = thread.result | |
| return developed_theme | |
| def send_email(subject, body, to_email): | |
| sender_email = os.getenv('EMAIL_SENDER') | |
| sender_password = os.getenv('EMAIL_PASSWORD') | |
| smtp_server = "smtp.gmail.com" | |
| smtp_port = 587 | |
| message = MIMEMultipart() | |
| message['From'] = sender_email | |
| message['To'] = to_email | |
| message['Subject'] = subject | |
| message.attach(MIMEText(body, 'plain')) | |
| try: | |
| server = smtplib.SMTP(smtp_server, smtp_port) | |
| server.starttls() | |
| server.login(sender_email, sender_password) | |
| server.sendmail(sender_email, to_email, message.as_string()) | |
| return "E-mail envoyé avec succès !" | |
| except Exception as e: | |
| return f"Erreur lors de l'envoi de l'e-mail : {e}" | |
| finally: | |
| server.quit() | |
| with gr.Blocks(theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("# 🎉 Générateur de Thèmes de Fête Personnalisés") | |
| with gr.Row(): | |
| prompt_input = gr.Textbox(label="Inspiration pour la fête") | |
| num_themes_input = gr.Slider(minimum=1, maximum=5, step=1, value=3, label="Nombre de thèmes") | |
| with gr.Row(): | |
| age_group = gr.Dropdown(["Enfants", "Adolescents", "Adultes", "Tous âges"], label="Groupe d'âge") | |
| budget = gr.Dropdown(["Économique", "Modéré", "Luxe"], label="Budget") | |
| location = gr.Dropdown(["Intérieur", "Extérieur", "Les deux"], label="Lieu") | |
| with gr.Row(): | |
| theme_selector = gr.Dropdown(label="Sélectionner un thème à développer", visible=False) | |
| develop_theme_button = gr.Button("Développer le thème", visible=False) | |
| developed_theme_output = gr.Markdown(label="Plan d'action détaillé", visible=False) | |
| developed_theme_state = gr.State() | |
| generate_button = gr.Button("Générer les thèmes") | |
| output = gr.Markdown(label="Thèmes générés") | |
| include_detailed_theme = gr.Checkbox(label="Inclure le thème détaillé dans l'e-mail", visible=False) | |
| with gr.Row(): | |
| email_input = gr.Textbox(label="Votre adresse email", visible=False) | |
| send_email_button = gr.Button("Envoyer par email", visible=False) | |
| generated_themes = gr.State() | |
| def show_email_options(formatted_results, results): | |
| theme_choices = [f"Thème {i+1}: {theme['theme']}" for i, theme in enumerate(results['themes'])] | |
| return ( | |
| gr.update(visible=True), | |
| gr.update(visible=True), | |
| gr.update(choices=theme_choices, visible=True), | |
| gr.update(visible=True), | |
| formatted_results, | |
| gr.update(visible=True), | |
| results | |
| ) | |
| def send_email_wrapper(email, formatted_results, detailed_theme, include_detailed): | |
| subject = "Thèmes de fête générés" | |
| body = formatted_results | |
| if include_detailed and (detailed_theme is None or detailed_theme.strip() == ""): | |
| return "Erreur : Le thème détaillé n'est pas encore généré." | |
| if include_detailed and detailed_theme: | |
| body += "\n\nThème détaillé :\n" + detailed_theme | |
| return send_email(subject, body, email) | |
| def develop_selected_theme(selected_theme, age_group_val, budget_val, location_val, results): | |
| theme_index = int(selected_theme.split(':')[0].split()[1]) - 1 | |
| theme = results['themes'][theme_index]['theme'] | |
| developed = develop_theme(theme, age_group_val, budget_val, location_val) | |
| return gr.update(value=developed, visible=True) | |
| generate_button.click( | |
| generate_and_format, | |
| inputs=[prompt_input, num_themes_input, age_group, budget, location], | |
| outputs=[output, generated_themes] | |
| ).then( | |
| show_email_options, | |
| inputs=[output, generated_themes], | |
| outputs=[email_input, send_email_button, theme_selector, develop_theme_button, output, include_detailed_theme, generated_themes] | |
| ) | |
| send_email_button.click( | |
| send_email_wrapper, | |
| inputs=[email_input, output, developed_theme_output, include_detailed_theme], | |
| outputs=[gr.Markdown(label="Statut de l'email")] | |
| ) | |
| develop_theme_button.click( | |
| develop_selected_theme, | |
| inputs=[theme_selector, age_group, budget, location, generated_themes], | |
| outputs=[developed_theme_output] | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |