File size: 1,127 Bytes
606f6c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import gradio as gr
import requests
import os
from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build

HF_TOKEN = os.getenv("HF_TOKEN")
SPREADSHEET_ID = os.getenv("SPREADSHEET_ID")
SERVICE_FILE = "service_account.json"  # upload to Space secrets

creds = Credentials.from_service_account_file(SERVICE_FILE, scopes=["https://www.googleapis.com/auth/spreadsheets"])
sheets = build("sheets", "v4", credentials=creds)

def ask_ai(prompt):
    # 1) Call HF model
    headers = {"Authorization": f"Bearer {HF_TOKEN}"}
    payload = {"inputs": prompt}
    r = requests.post(
        "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2",
        headers=headers, json=payload
    )
    answer = r.json()[0]["generated_text"]

    # 2) Save to Sheets
    sheets.spreadsheets().values().append(
        spreadsheetId=SPREADSHEET_ID,
        range="Sheet1!A:B",
        valueInputOption="RAW",
        body={"values": [[prompt, answer]]}
    ).execute()

    return answer

iface = gr.Interface(fn=ask_ai, inputs="text", outputs="text", title="Ask AI")
iface.launch()