CoolFace
Apppublic

Santhosh54321/Test_model

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
app.py230 linesDownload Raw Back to root
1import streamlit as st2import requests3import os4import time  # Import time module for implementing delay5 6# Fetch Hugging Face and Groq API keys from secrets7Transalate_token = os.getenv('HUGGINGFACE_TOKEN')8Image_Token = os.getenv('HUGGINGFACE_TOKEN')9Content_Token = os.getenv('GROQ_API_KEY')10Image_prompt_token = os.getenv('GROQ_API_KEY')11 12# API Headers13Translate = {"Authorization": f"Bearer {Transalate_token}"}14Image_generation = {"Authorization": f"Bearer {Image_Token}"}15Content_generation = {16    "Authorization": f"Bearer {Content_Token}",17    "Content-Type": "application/json"18}19Image_Prompt = {20    "Authorization": f"Bearer {Image_prompt_token}",21    "Content-Type": "application/json"22}23 24# Translation Model API URL (Tamil to English)25translation_url = "https://api-inference.huggingface.co/models/facebook/mbart-large-50-many-to-one-mmt"26 27# Text-to-Image Model API URLs28image_generation_urls = {29    "black-forest-labs/FLUX.1-schnell": "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-schnell",30    "CompVis/stable-diffusion-v1-4": "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4",31    "black-forest-labs/FLUX.1-dev": "https://api-inference.huggingface.co/models/black-forest-labs/FLUX.1-dev"32}33 34# Default image generation model35default_image_model = "black-forest-labs/FLUX.1-schnell"36 37# Content generation models38content_models = {39    "llama-3.1-70b-versatile": "llama-3.1-70b-versatile",40    "llama3-8b-8192": "llama3-8b-8192",41    "gemma2-9b-it": "gemma2-9b-it",42    "mixtral-8x7b-32768": "mixtral-8x7b-32768"43}44 45# Default content generation model46default_content_model = "llama-3.1-70b-versatile"47 48# Function to query Hugging Face translation model with retry mechanism49def translate_text(text):50    payload = {"inputs": text}51    max_retries = 3  # Maximum number of retry attempts52    delay = 2  # Delay between retries in seconds53 54    for attempt in range(max_retries):55        response = requests.post(translation_url, headers=Translate, json=payload)56        if response.status_code == 200:57            result = response.json()58            translated_text = result[0]['generated_text']59            return translated_text60        else:61            st.warning(f"Translation failed (Attempt {attempt+1}/{max_retries}) - Retrying in {delay} seconds...")62            time.sleep(delay)  # Wait for 2 seconds before retrying63 64    # If all retries fail, show an error65    st.error(f"Translation failed after {max_retries} attempts. Please reload the page and try again later.")66    return None67 68# Function to query Groq content generation model69def generate_content(english_text, max_tokens, temperature, model):70    url = "https://api.groq.com/openai/v1/chat/completions"71    payload = {72        "model": model,73        "messages": [74            {"role": "system", "content": "You are a creative and insightful writer."},75            {"role": "user", "content": f"Write educational content about {english_text} within {max_tokens} tokens."}76        ],77        "max_tokens": max_tokens,78        "temperature": temperature79    }80    response = requests.post(url, json=payload, headers=Content_generation)81    if response.status_code == 200:82        result = response.json()83        return result['choices'][0]['message']['content']84    else:85        st.error(f"Content Generation Error: {response.status_code}")86        return None87 88# Function to generate image prompt89def generate_image_prompt(english_text):90    payload = {91        "model": "mixtral-8x7b-32768",92        "messages": [93            {"role": "system", "content": "You are a professional Text to image prompt generator."},94            {"role": "user", "content": f"Create a text to image generation prompt about {english_text} within 30 tokens."}95        ],96        "max_tokens": 3097    }98    response = requests.post("https://api.groq.com/openai/v1/chat/completions", json=payload, headers=Image_Prompt)99    if response.status_code == 200:100        result = response.json()101        return result['choices'][0]['message']['content']102    else:103        st.error(f"Prompt Generation Error: {response.status_code}")104        return None105 106# Function to generate an image from the prompt107def generate_image(image_prompt, model_url):108    data = {"inputs": image_prompt}109    response = requests.post(model_url, headers=Image_generation, json=data)110    if response.status_code == 200:111        return response.content112    else:113        st.error(f"Image Generation Error {response.status_code}: {response.text}")114        return None115 116# User Guide Section117def show_user_guide():118    st.title("FusionMind User Guide")119    st.write("""120    ### Welcome to the FusionMind User Guide!121 122    ### How to use this app:123    ... (omitted for brevity)124    """)125 126# Main Streamlit app127def main():128    # Sidebar Menu129    st.sidebar.title("FusionMind Options")130    page = st.sidebar.radio("Select a page:", ["Main App", "User Guide"])131 132    if page == "User Guide":133        show_user_guide()134        return135 136    # Custom CSS for background, borders, and other styling137    st.markdown(138        """139        <style>140        body {141            background-image: url('https://wallpapercave.com/wp/wp4008910.jpg');142            background-size: cover;143        }144        .reportview-container {145            background: rgba(255, 255, 255, 0.85);146            padding: 2rem;147            border-radius: 10px;148            box-shadow: 0px 0px 20px rgba(0, 0, 0, 0.1);149        }150        .result-container {151            border: 2px solid #4CAF50;152            padding: 20px;153            border-radius: 10px;154            margin-top: 20px;155            animation: fadeIn 2s ease;156        }157        @keyframes fadeIn {158            0% { opacity: 0; }159            100% { opacity: 1; }160        }161        .stButton button {162            background-color: #4CAF50;163            color: white;164            border-radius: 10px;165            padding: 10px;166        }167        .stButton button:hover {168            background-color: #45a049;169            transform: scale(1.05);170            transition: 0.2s ease-in-out;171        }172        </style>173        """, unsafe_allow_html=True174    )175 176    st.title("🅰️ℹ️ FusionMind ➡️ Multimodal")177 178    # Sidebar for temperature, token adjustment, and model selection179    st.sidebar.header("Settings")180    temperature = st.sidebar.slider("Select Temperature", 0.1, 1.0, 0.7)181    max_tokens = st.sidebar.slider("Max Tokens for Content Generation", 100, 400, 200)182 183    # Content generation model selection184    content_model = st.sidebar.selectbox("Select Content Generation Model", list(content_models.keys()), index=0)185 186    # Image generation model selection187    image_model = st.sidebar.selectbox("Select Image Generation Model", list(image_generation_urls.keys()), index=0)188 189    # Reminder about model availability190    st.sidebar.warning("Note: Based on availability, some models might not work. Please try another model if an error occurs.By default the perfect model is selected try with it and then experiment with different models")191 192    # Suggested inputs193    st.write("## Suggested Inputs")194    suggestions = ["தரவு அறிவியல்", "உளவியல்", "ராக்கெட் எப்படி வேலை செய்கிறது"]195    selected_suggestion = st.selectbox("Select a suggestion or enter your own:", [""] + suggestions)196 197    # Input box for user198    tamil_input = st.text_input("Enter Tamil text (or select a suggestion):", selected_suggestion)199 200    if st.button("Generate"):201        # Step 1: Translation (Tamil to English)202        if tamil_input:203            st.write("### Translated English Text:")204            english_text = translate_text(tamil_input)205            if english_text:206                st.write(english_text)207 208                # Step 2: Content Generation209                st.write("### Educational Content Generated:")210                content = generate_content(english_text, max_tokens, temperature, content_models[content_model])211                if content:212                    st.write(content)213 214                    # Step 3: Generate Image Prompt215                    st.write("### Image Prompt:")216                    image_prompt = generate_image_prompt(english_text)217                    if image_prompt:218                        st.write(image_prompt)219 220                        # Step 4: Image Generation221                        st.write("### Generated Image:")222                        image = generate_image(image_prompt, image_generation_urls[image_model])223                        if image:224                            st.image(image)225        else:226            st.error("Please enter or select Tamil text.")227 228if __name__ == "__main__":229    main()230