Update app.py
Browse files
app.py
CHANGED
|
@@ -1,77 +1,70 @@
|
|
| 1 |
-
import
|
| 2 |
import uuid
|
|
|
|
|
|
|
|
|
|
| 3 |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
| 4 |
-
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
| 5 |
-
from sqlalchemy.orm import sessionmaker, declarative_base
|
| 6 |
-
from sqlalchemy import Column, String, DateTime, func, select
|
| 7 |
-
import asyncio
|
| 8 |
-
|
| 9 |
-
# --------- Banco de dados (Supabase) -------------
|
| 10 |
-
import os
|
| 11 |
from dotenv import load_dotenv
|
| 12 |
-
load_dotenv()
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
|
| 31 |
-
# ---------
|
| 32 |
model_name = "google/gemma-3-270m-it"
|
| 33 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 34 |
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 35 |
gen_pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 36 |
|
| 37 |
-
# ---------
|
| 38 |
-
async def create_user(name: str):
|
| 39 |
-
key = str(uuid.uuid4())
|
| 40 |
-
async with SessionLocal() as session:
|
| 41 |
-
user = User(id=str(uuid.uuid4()), name=name, api_key=key)
|
| 42 |
-
session.add(user)
|
| 43 |
-
await session.commit()
|
| 44 |
-
return key
|
| 45 |
-
|
| 46 |
-
async def check_key(key: str):
|
| 47 |
-
async with SessionLocal() as session:
|
| 48 |
-
result = await session.execute(select(User).where(User.api_key == key))
|
| 49 |
-
user = result.scalar_one_or_none()
|
| 50 |
-
return user is not None
|
| 51 |
-
|
| 52 |
def generate_text(prompt, api_key):
|
| 53 |
-
|
| 54 |
-
loop = asyncio.get_event_loop()
|
| 55 |
-
valid = loop.run_until_complete(check_key(api_key))
|
| 56 |
-
if not valid:
|
| 57 |
return "API Key inválida!"
|
| 58 |
result = gen_pipe(prompt, max_length=100, do_sample=True)
|
| 59 |
return result[0]["generated_text"]
|
| 60 |
|
| 61 |
-
# --------- Interface Gradio
|
| 62 |
with gr.Blocks() as demo:
|
| 63 |
-
gr.Markdown("##
|
|
|
|
| 64 |
with gr.Tab("Gerar Texto"):
|
| 65 |
prompt_input = gr.Textbox(label="Prompt")
|
| 66 |
api_key_input = gr.Textbox(label="API Key")
|
| 67 |
output_text = gr.Textbox(label="Resultado")
|
| 68 |
generate_btn = gr.Button("Gerar")
|
| 69 |
generate_btn.click(fn=generate_text, inputs=[prompt_input, api_key_input], outputs=output_text)
|
| 70 |
-
|
| 71 |
with gr.Tab("Criar API Key"):
|
| 72 |
name_input = gr.Textbox(label="Nome do Usuário")
|
| 73 |
key_output = gr.Textbox(label="Sua API Key")
|
| 74 |
create_btn = gr.Button("Criar")
|
| 75 |
-
create_btn.click(fn=
|
| 76 |
|
| 77 |
-
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import uuid
|
| 3 |
+
import json
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import requests
|
| 6 |
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
from dotenv import load_dotenv
|
|
|
|
| 8 |
|
| 9 |
+
# --------- Carregar secrets -------------
|
| 10 |
+
load_dotenv()
|
| 11 |
+
SUPABASE_URL = os.environ.get("SUPABASE_URL") # Ex.: https://xyz.supabase.co
|
| 12 |
+
SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
|
| 13 |
+
HEADERS = {
|
| 14 |
+
"apikey": SUPABASE_KEY,
|
| 15 |
+
"Authorization": f"Bearer {SUPABASE_KEY}",
|
| 16 |
+
"Content-Type": "application/json"
|
| 17 |
+
}
|
| 18 |
|
| 19 |
+
# --------- Funções Supabase -------------
|
| 20 |
+
def create_user(name: str):
|
| 21 |
+
api_key = str(uuid.uuid4())
|
| 22 |
+
data = {
|
| 23 |
+
"name": name,
|
| 24 |
+
"api_key": api_key
|
| 25 |
+
}
|
| 26 |
+
response = requests.post(f"{SUPABASE_URL}/rest/v1/users",
|
| 27 |
+
headers=HEADERS,
|
| 28 |
+
data=json.dumps(data))
|
| 29 |
+
if response.status_code in [200, 201]:
|
| 30 |
+
return api_key
|
| 31 |
+
else:
|
| 32 |
+
return f"Erro: {response.text}"
|
| 33 |
|
| 34 |
+
def check_key(api_key: str):
|
| 35 |
+
response = requests.get(f"{SUPABASE_URL}/rest/v1/users?api_key=eq.{api_key}",
|
| 36 |
+
headers=HEADERS)
|
| 37 |
+
data = response.json()
|
| 38 |
+
return len(data) > 0
|
| 39 |
|
| 40 |
+
# --------- Carregar modelo Gemma 270M -------------
|
| 41 |
model_name = "google/gemma-3-270m-it"
|
| 42 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 43 |
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 44 |
gen_pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
|
| 45 |
|
| 46 |
+
# --------- Função de geração de texto -------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
def generate_text(prompt, api_key):
|
| 48 |
+
if not check_key(api_key):
|
|
|
|
|
|
|
|
|
|
| 49 |
return "API Key inválida!"
|
| 50 |
result = gen_pipe(prompt, max_length=100, do_sample=True)
|
| 51 |
return result[0]["generated_text"]
|
| 52 |
|
| 53 |
+
# --------- Interface Gradio -------------
|
| 54 |
with gr.Blocks() as demo:
|
| 55 |
+
gr.Markdown("## Gemma 270M API - Espaço Gratuito")
|
| 56 |
+
|
| 57 |
with gr.Tab("Gerar Texto"):
|
| 58 |
prompt_input = gr.Textbox(label="Prompt")
|
| 59 |
api_key_input = gr.Textbox(label="API Key")
|
| 60 |
output_text = gr.Textbox(label="Resultado")
|
| 61 |
generate_btn = gr.Button("Gerar")
|
| 62 |
generate_btn.click(fn=generate_text, inputs=[prompt_input, api_key_input], outputs=output_text)
|
| 63 |
+
|
| 64 |
with gr.Tab("Criar API Key"):
|
| 65 |
name_input = gr.Textbox(label="Nome do Usuário")
|
| 66 |
key_output = gr.Textbox(label="Sua API Key")
|
| 67 |
create_btn = gr.Button("Criar")
|
| 68 |
+
create_btn.click(fn=create_user, inputs=name_input, outputs=key_output)
|
| 69 |
|
| 70 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|