Spaces:
Runtime error
Runtime error
| !pip install fastapi transformers gradio bitsandbytes sounddevice PyAudio gtts --upgrade | |
| !apt-get update && apt-get install -y portaudio19-dev libportaudio2 libportaudiocpp0 | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AutoConfig | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import gradio as gr | |
| import sounddevice as sd | |
| import numpy as np | |
| import wave | |
| import tempfile | |
| from gtts import gTTS | |
| import os | |
| # Клонирование репозитория Hugging Face | |
| !git clone https://huggingface.co/spaces/Wtiger/Prosto_Ai | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| # Определяем стратегию загрузки модели | |
| if torch.cuda.is_available(): | |
| vram_total = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3) | |
| if vram_total >= 16: | |
| quantization_config = BitsAndBytesConfig( | |
| load_in_4bit=True, | |
| bnb_4bit_compute_dtype=torch.float16, | |
| bnb_4bit_use_double_quant=True, | |
| bnb_4bit_quant_type="nf4" | |
| ) | |
| device_map = "auto" | |
| elif vram_total >= 10: | |
| quantization_config = BitsAndBytesConfig(load_in_8bit=True) | |
| device_map = "auto" | |
| else: | |
| quantization_config = None | |
| device_map = {"": "cpu"} | |
| else: | |
| quantization_config = None | |
| device_map = {"": "cpu"} | |
| # Загружаем модель FreedomIntelligence/RAG-Instruct-Llama3-3B | |
| model_name = "FreedomIntelligence/RAG-Instruct-Llama3-3B" | |
| config = AutoConfig.from_pretrained(model_name) | |
| if quantization_config is not None: | |
| quantization_config.llm_int8_enable_fp32_cpu_offload = True | |
| quantization_config.offload_folder = "offload_weights" | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| config=config, | |
| quantization_config=quantization_config, | |
| device_map=device_map, | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| # FastAPI | |
| app = FastAPI() | |
| class MathQuery(BaseModel): | |
| topic: str | |
| difficulty: str = "medium" | |
| def generate_math_lesson(topic: str, difficulty: str): | |
| prompt = f"Create a {difficulty} level math lesson on {topic} in English." | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| def generate_english_task(): | |
| prompt = "Generate a random English learning exercise." | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| def generate_random_task(difficulty): | |
| """ | |
| This function generates a random English learning exercise using the | |
| language model. It's similar to generate_english_task but can be | |
| modified to generate different types of random tasks. | |
| """ | |
| prompt = f"Generate a random English learning exercise {difficulty}" | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| def answer_help_question(question: str): | |
| prompt = f"Answer this question: {question}" | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # Gradio Web UI - Киберпанк стиль | |
| custom_css = """ | |
| body { | |
| background-color: #000; | |
| color: #0ff; | |
| font-family: 'Orbitron', sans-serif; | |
| background-image: url('https://wallpaperaccess.com/full/1503811.jpg'); | |
| background-size: cover; | |
| } | |
| .container { | |
| max-width: 900px; | |
| margin: auto; | |
| padding: 20px; | |
| background: rgba(10, 10, 10, 0.9); | |
| border-radius: 10px; | |
| box-shadow: 0px 0px 20px cyan; | |
| } | |
| button { | |
| background: linear-gradient(45deg, #ff00ff, #00ffff); | |
| color: black; | |
| padding: 10px; | |
| border: none; | |
| border-radius: 5px; | |
| cursor: pointer; | |
| font-weight: bold; | |
| } | |
| button:hover { | |
| background: linear-gradient(45deg, #ff0000, #00ff00); | |
| } | |
| """ | |
| # Проверяем доступность устройства | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| # Проверяем наличие необходимых библиотек и загружаем модель для распознавания речи | |
| try: | |
| model_name = "openai/whisper-small" | |
| model = AutoModelForSpeechSeq2Seq.from_pretrained(model_name).to(device) | |
| processor = AutoProcessor.from_pretrained(model_name) | |
| stt_pipeline = pipeline( | |
| "automatic-speech-recognition", model=model, tokenizer=processor.tokenizer, | |
| feature_extractor=processor.feature_extractor, device=0 if torch.cuda.is_available() else -1 | |
| ) | |
| except ModuleNotFoundError as e: | |
| print(f"Ошибка: {e}. Убедитесь, что все зависимости установлены.") | |
| exit() | |
| def record_audio(duration=5, samplerate=16000): | |
| print("Recording...") | |
| audio_data = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=1, dtype='int16') | |
| sd.wait() | |
| print("Recording finished") | |
| return np.squeeze(audio_data) | |
| def save_audio(audio_data, samplerate=16000): | |
| with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_wav: | |
| with wave.open(temp_wav.name, 'wb') as wf: | |
| wf.setnchannels(1) | |
| wf.setsampwidth(2) | |
| wf.setframerate(samplerate) | |
| wf.writeframes(audio_data.tobytes()) | |
| return temp_wav.name | |
| def transcribe_audio(): | |
| try: | |
| audio_data = record_audio() | |
| audio_path = save_audio(audio_data) | |
| result = stt_pipeline(audio_path) | |
| return result.get("text", "Ошибка распознавания") | |
| except Exception as e: | |
| return f"Ошибка обработки аудио: {e}" | |
| def generate_ai_response(user_text): | |
| return f"Вы сказали: {user_text}. Это тестовый ответ AI." | |
| def tts_response(text): | |
| try: | |
| tts = gTTS(text, lang='ru') | |
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") | |
| tts.save(temp_file.name) | |
| return temp_file.name | |
| except Exception as e: | |
| print(f"Ошибка генерации речи: {e}") | |
| return None | |
| def voice_interaction(): | |
| greeting_text = "Привет! Я ваш голосовой ассистент. Как я могу помочь?" | |
| greeting_audio = tts_response(greeting_text) | |
| recognized_text = transcribe_audio() | |
| print("User said:", recognized_text) | |
| response_text = generate_ai_response(recognized_text) | |
| response_audio = tts_response(response_text) | |
| return greeting_text, greeting_audio, recognized_text, response_text, response_audio | |
| with gr.Blocks(css=custom_css) as demo: | |
| gr.Markdown(""" | |
| <div class='container'> | |
| <h1>⚡ CyberAI Learning Platform ⚡</h1> | |
| <h2>🚀 Powered by FreedomIntelligence/RAG-Instruct-Llama3-3B</h2> | |
| </div> | |
| """) | |
| with gr.Tabs() as tabs: | |
| with gr.TabItem("Math Lessons"): | |
| topic_input = gr.Textbox(label="Enter Math Topic") | |
| difficulty_level = gr.Radio(["Easy", "Medium", "Hard"], label="Select Difficulty", value="Medium") | |
| generate_button = gr.Button("Generate Lesson") | |
| lesson_output = gr.Textbox(label="Generated Lesson", interactive=False) | |
| generate_button.click(generate_math_lesson, inputs=[topic_input, difficulty_level], outputs=lesson_output) | |
| with gr.TabItem("English Tasks"): | |
| task_list = gr.Textbox(label="Generated English Task", interactive=False) | |
| refresh_button = gr.Button("Get New Task") | |
| refresh_button.click(generate_english_task, outputs=task_list) | |
| with gr.TabItem("English Study Plan"): | |
| study_plan_text = """<h3>English Tenses Overview</h3> | |
| <p>There are 12 tenses in English, divided into 4 groups...</p>""" | |
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, AutoConfig | |
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import gradio as gr | |
| # Определяем устройство | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| # Определяем стратегию загрузки модели | |
| if torch.cuda.is_available(): | |
| vram_total = torch.cuda.get_device_properties(0).total_memory / (1024 ** 3) | |
| if vram_total >= 16: | |
| quantization_config = BitsAndBytesConfig( | |
| load_in_4bit=True, | |
| bnb_4bit_compute_dtype=torch.float16, | |
| bnb_4bit_use_double_quant=True, | |
| bnb_4bit_quant_type="nf4" | |
| ) | |
| device_map = "auto" | |
| elif vram_total >= 10: | |
| quantization_config = BitsAndBytesConfig(load_in_8bit=True) | |
| device_map = "auto" | |
| else: | |
| quantization_config = None | |
| device_map = {"": "cpu"} | |
| else: | |
| quantization_config = None | |
| device_map = {"": "cpu"} | |
| # Загружаем модель FreedomIntelligence/RAG-Instruct-Llama3-3B | |
| model_name = "FreedomIntelligence/RAG-Instruct-Llama3-3B" | |
| config = AutoConfig.from_pretrained(model_name) | |
| if quantization_config is not None: | |
| quantization_config.llm_int8_enable_fp32_cpu_offload = True | |
| quantization_config.offload_folder = "offload_weights" | |
| model = AutoModelForCausalLM.from_pretrained( | |
| model_name, | |
| config=config, | |
| quantization_config=quantization_config, | |
| device_map=device_map, | |
| ) | |
| tokenizer = AutoTokenizer.from_pretrained(model_name) | |
| # FastAPI | |
| app = FastAPI() | |
| class MathQuery(BaseModel): | |
| topic: str | |
| difficulty: str = "medium" | |
| def generate_math_lesson(topic: str, difficulty: str): | |
| prompt = f"Create a {difficulty} level math lesson on {topic} in English." | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| def generate_english_task(difficulty): | |
| prompt = f"Generate a random English learning exercise, {difficulty}" | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| def generate_task_by_topic(topic: str,difficulty): | |
| prompt = f"Generate a random English learning {topic} exercise ,{difficulty} " | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| def answer_help_question(question: str): | |
| prompt = f"Answer this question: {question}" | |
| inputs = tokenizer(prompt, return_tensors="pt").to(device) | |
| outputs = model.generate(**inputs, max_new_tokens=200, temperature=0.7, top_p=0.9) | |
| return tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # Gradio Web UI - Киберпанк стиль | |
| custom_css = """ | |
| body { | |
| background-color: #000; | |
| color: #0ff; | |
| font-family: 'Orbitron', sans-serif; | |
| background-image: url('https://wallpaperaccess.com/full/1503811.jpg'); | |
| background-size: cover; | |
| } | |
| .container { | |
| max-width: 900px; | |
| margin: auto; | |
| padding: 20px; | |
| background: rgba(10, 10, 10, 0.9); | |
| border-radius: 10px; | |
| box-shadow: 0px 0px 20px cyan; | |
| } | |
| button { | |
| background: linear-gradient(45deg, #ff00ff, #00ffff); | |
| color: black; | |
| padding: 10px; | |
| border: none; | |
| border-radius: 5px; | |
| cursor: pointer; | |
| font-weight: bold; | |
| } | |
| button:hover { | |
| background: linear-gradient(45deg, #ff0000, #00ff00); | |
| } | |
| """ | |
| with gr.Blocks(css=custom_css) as demo: | |
| gr.Markdown(""" | |
| <div class='container'> | |
| <h1>⚡ Prosto AI⚡</h1> | |
| <h2></h2> | |
| </div> | |
| """) | |
| with gr.Tabs() as tabs: | |
| with gr.TabItem("Math Lessons"): | |
| topic_input = gr.Textbox(label="Enter Math Topic") | |
| difficulty_level = gr.Radio(["Easy", "Medium", "Hard"], label="Select Difficulty", value="Medium") | |
| generate_button = gr.Button("Generate Lesson") | |
| lesson_output = gr.Textbox(label="Generated Lesson", interactive=False) | |
| generate_button.click(generate_math_lesson, inputs=[topic_input, difficulty_level], outputs=lesson_output) | |
| with gr.TabItem("English Tasks"): | |
| difficulty_level = gr.Radio(["Easy", "Medium", "Hard"], label="Select Difficulty", value="Medium") | |
| gr.Markdown("**Generate a task based on a specific topic or randomly:**") | |
| task_topic_input = gr.Textbox(label="Enter a topic for the task") | |
| generate_task_button = gr.Button("Generate Task by Topic") | |
| generate_random_task_button = gr.Button("Generate Random Task") | |
| generated_task_output = gr.Textbox(label="Generated Task", interactive=False) | |
| generate_task_button.click(generate_task_by_topic, inputs=[task_topic_input, difficulty_level], outputs=generated_task_output) | |
| generate_random_task_button.click(generate_random_task, inputs=[difficulty_level], outputs=generated_task_output) | |
| with gr.TabItem("English Study Plan"): | |
| study_plan_text = """<h3>English Tenses Overview</h3> | |
| <p>План изучения английских времён | |
| Изучение времён английского языка лучше всего разбивать на этапы, начиная с самых простых и постепенно переходя к более сложным. Этот план поможет вам постепенно освоить все времена и научиться их применять. | |
| 🔹 Этап 1: Введение в систему времён | |
| 📌 Цель: Ознакомиться с группами времён и их особенностями. | |
| Понять, что в английском языке 12 времён, которые делятся на 4 группы: | |
| Simple (Простые) – действие как факт. | |
| Continuous (Длительные) – действие в процессе. | |
| Perfect (Совершенные) – результат. | |
| Perfect Continuous (Совершенные длительные) – процесс с акцентом на длительность. | |
| 🔹 Этап 2: Освоение группы Simple (Простые времена) | |
| 📌 Цель: Научиться выражать действия как факты, повторяющиеся события и события в будущем. | |
| Present Simple (Настоящее простое) | |
| Используется для регулярных действий, фактов и расписаний. | |
| Формула: (I/You/We/They + V / He/She/It + V+s/es) | |
| Пример: I go to school every day. | |
| Past Simple (Прошедшее простое) | |
| Действие, которое произошло в прошлом и закончилось. | |
| Формула: (V2 или V+ed) | |
| Пример: She visited Paris last year. | |
| Future Simple (Будущее простое) | |
| Действие, которое произойдёт в будущем. | |
| Формула: (will + V) | |
| Пример: They will travel to Japan next summer. | |
| 📝 Практика: ✔️ Напишите 10 предложений в каждом времени. | |
| ✔️ Используйте глаголы в разных формах. | |
| ✔️ Расскажите о своём дне, вчерашнем дне и планах на завтра. | |
| 🔹 Этап 3: Изучение группы Continuous (Длительные времена) | |
| 📌 Цель: Научиться говорить о процессах, которые происходят в конкретный момент времени. | |
| Present Continuous (Настоящее длительное) | |
| Действие происходит прямо сейчас или в ближайшем будущем. | |
| Формула: (am/is/are + V-ing) | |
| Пример: She is reading a book now. | |
| Past Continuous (Прошедшее длительное) | |
| Действие длилось в определённый момент в прошлом. | |
| Формула: (was/were + V-ing) | |
| Пример: They were watching TV when I called. | |
| Future Continuous (Будущее длительное) | |
| Действие будет происходить в определённый момент в будущем. | |
| Формула: (will be + V-ing) | |
| Пример: This time tomorrow, I will be flying to New York. | |
| 📝 Практика: ✔️ Опишите, что вы делаете прямо сейчас. | |
| ✔️ Расскажите о том, что вы делали вчера в определённое время. | |
| ✔️ Опишите, чем вы будете заниматься в завтрашний вечер. | |
| 🔹 Этап 4: Освоение группы Perfect (Совершенные времена) | |
| 📌 Цель: Научиться говорить о результатах действий. | |
| Present Perfect (Настоящее совершенное) | |
| Действие произошло в прошлом, но его результат важен сейчас. | |
| Формула: (have/has + V3) | |
| Пример: I have just finished my homework. | |
| Past Perfect (Прошедшее совершенное) | |
| Действие произошло до другого действия в прошлом. | |
| Формула: (had + V3) | |
| Пример: By the time I arrived, they had left. | |
| Future Perfect (Будущее совершенное) | |
| Действие завершится к определённому моменту в будущем. | |
| Формула: (will have + V3) | |
| Пример: I will have finished the report by tomorrow. | |
| 📝 Практика: ✔️ Опишите, что вы уже сделали сегодня. | |
| ✔️ Расскажите о событии, которое произошло до другого события в прошлом. | |
| ✔️ Напишите, что вы завершите к концу следующей недели. | |
| 🔹 Этап 5: Совершенные длительные времена (Perfect Continuous) | |
| 📌 Цель: Использовать времена для описания длительных процессов с акцентом на продолжительность. | |
| Present Perfect Continuous (Настоящее совершенное длительное) | |
| Действие началось в прошлом и продолжается до сих пор. | |
| Формула: (have/has been + V-ing) | |
| Пример: I have been studying English for 5 years. | |
| Past Perfect Continuous (Прошедшее совершенное длительное) | |
| Действие длилось до определённого момента в прошлом. | |
| Формула: (had been + V-ing) | |
| Пример: She had been working at that company for 3 years before she quit. | |
| Future Perfect Continuous (Будущее совершенное длительное) | |
| Действие будет продолжаться до определённого момента в будущем. | |
| Формула: (will have been + V-ing) | |
| Пример: By next year, I will have been living here for 10 years. | |
| 📝 Практика: ✔️ Опишите, как долго вы занимаетесь каким-либо хобби. | |
| ✔️ Напишите, как долго длилось какое-то действие до определённого момента в прошлом. | |
| ✔️ Составьте предложение о том, как долго вы будете чем-то заниматься в будущем. | |
| 🔹 Этап 6: Итоговое повторение и практика | |
| 📌 Цель: Закрепить знания и научиться использовать времена в речи. | |
| ✅ Повторите основные отличия времён. | |
| ✅ Составьте сравнительные таблицы, чтобы видеть разницу между временами. | |
| ✅ Практикуйтесь в устной и письменной речи: | |
| Опишите один день из жизни с разными временами. | |
| Составьте рассказ о себе, используя все времена. | |
| Потренируйтесь объяснять ситуации с разными временными формами. | |
| 🔹 Совет: Лучше всего изучать времена постепенно, разбирая примеры и активно используя их в речи! 🚀 | |
| Такой подход поможет вам поэтапно освоить все времена и научиться использовать их правильно. Если нужна дополнительная практика или примеры — дайте знать! 😊 | |
| </p>""" | |
| gr.Markdown(study_plan_text) | |
| help_button = gr.Button("❓ Need Help?") | |
| help_button.click(lambda: tabs.select(tabs.value)) #Fixed this line | |
| with gr.TabItem("Help"): | |
| question_input = gr.Textbox(label="Ask a question") | |
| answer_output = gr.Textbox(label="AI Response", interactive=False) | |
| ask_button = gr.Button("Ask AI") | |
| ask_button.click(answer_help_question, inputs=[question_input], outputs=answer_output) | |
| with gr.TabItem("Talking"): | |
| record_button = gr.Button("🎙️ Говорить") | |
| upload_audio = gr.File(label="Upload Audio") | |
| greeting_output = gr.Audio(label="AI Приветствие", autoplay=True) | |
| transcription_output = gr.Textbox(label="Распознанный текст") | |
| response_text_output = gr.Textbox(label="Ответ AI") | |
| audio_output = gr.Audio(label="Голосовой ответ AI", autoplay=True) | |
| record_button.click(voice_interaction, outputs=[greeting_output, transcription_output, response_text_output, audio_output]) | |
| upload_audio.change(transcribe_audio, inputs=[upload_audio], outputs=[transcription_output]) | |
| record_button.click(voice_interaction, outputs=[greeting_output, transcription_output, response_text_output, audio_output]) | |
| with gr.TabItem("Resources"): # Nested correctly under tabs | |
| gr.Markdown("## 📚 Полезные ресурсы для изучения английского") | |
| with gr.Row(): # Nested correctly under Resources TabItem | |
| gr.Markdown("[🎬 Фильмы на английском](https://www.netflix.com/)", label="Фильмы") | |
| gr.Markdown("[📖 Книги на английском](https://www.gutenberg.org/)", label="Книги") | |
| with gr.Row(): # Nested correctly under Resources TabItem | |
| gr.Markdown("[🎧 Аудиокниги](https://librivox.org/)", label="Аудиокниги") | |
| gr.Markdown("[📚 Уроки английского](https://www.ef.com/wwen/english-resources/)", label="Уроки английского") | |
| with gr.Row(): # Nested correctly under Resources TabItem | |
| gr.Markdown("[📺 Видео-уроки](https://www.youtube.com/results?search_query=learn+english)", label="Видео-уроки") | |
| gr.Markdown("[📝 Грамматические упражнения](https://www.englishclub.com/grammar/)", label="Грамматика") | |
| demo.launch() | |