AI-Флешкарточки
import streamlit as st
import pandas as pd
import random
import pickle
import os
import openai
from dotenv import load_dotenv
# Загрузка API-ключа
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
# === Загрузка карточек ===
@st.cache_data
def load_flashcards(path="flashcards.csv"):
return pd.read_csv(path)
# === Загрузка истории ответов ===
def load_history(path="history.pkl"):
if os.path.exists(path):
with open(path, "rb") as f:
return pickle.load(f)
return {}
def save_history(history, path="history.pkl"):
with open(path, "wb") as f:
pickle.dump(history, f)
# === AI-переформулировка вопроса ===
def rephrase_question(question):
try:
prompt = f"Переформулируй вопрос так, чтобы он звучал по-другому, но имел тот же смысл:\n\"{question}\""
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
temperature=0.7,
max_tokens=60
)
return response['choices'][0]['message']['content'].strip()
except Exception as e:
return question + " (вариант 2)"
# === Интерфейс приложения ===
st.title("🧠 AI-Флешкарточки")
st.markdown("Проверь свою память — и прокачай её с помощью ИИ.")
cards = load_flashcards()
history = load_history()
# Выбор случайной карточки
if "current_card" not in st.session_state:
st.session_state.current_card = random.choice(cards.to_dict(orient="records"))
st.session_state.rephrased = False
card = st.session_state.current_card
question = card["question"]
# Если пользователь уже ошибался — переформулируем вопрос
card_key = question.lower()
mistake_count = history.get(card_key, 0)
if mistake_count >= 2 and not st.session_state.rephrased:
question = rephrase_question(question)
st.session_state.rephrased = True
st.subheader("Вопрос:")
st.write(f"❓ {question}")
user_input = st.text_input("Твой ответ:")
if user_input:
correct = user_input.strip().lower() == card["answer"].strip().lower()
if correct:
st.success("✅ Верно!")
history[card_key] = 0 # сбрасываем счётчик ошибок
else:
st.error(f"❌ Неверно. Правильный ответ: {card['answer']}")
history[card_key] = history.get(card_key, 0) + 1
# Показываем статистику
total = len(cards)
wrong = sum(1 for v in history.values() if v > 0)
st.info(f"Ошибок в {wrong} из {total} карточек.")
# Сохраняем историю
save_history(history)
# Следующая карточка
st.session_state.current_card = random.choice(cards.to_dict(orient="records"))
st.session_state.rephrased = False
st.rerun()