oleh.rostovtsev commited on
Commit
2fbd0f4
·
1 Parent(s): 278dd8e

Add complete tarot reading app with AI model integration

Browse files

- Add app.py with Gradio interface and API endpoint
- Add requirements.txt with all necessary dependencies
- Add README.md with comprehensive documentation
- Add config.yaml for Space configuration
- Add test scripts for API testing
- Add deployment guide
- Integrate barissglc/tinyllama-tarot-v1 model for tarot predictions

Files changed (7) hide show
  1. DEPLOYMENT.md +126 -0
  2. README.md +71 -6
  3. app.py +148 -0
  4. config.yaml +10 -0
  5. requirements.txt +5 -0
  6. test_api.py +77 -0
  7. test_curl.sh +43 -0
DEPLOYMENT.md ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 Deployment Guide for Tarot Space
2
+
3
+ ## Step 1: Create a Hugging Face Space
4
+
5
+ 1. Go to [Hugging Face Spaces](https://huggingface.co/new-space)
6
+ 2. Choose a name for your space (e.g., `your-username-tarot-reading`)
7
+ 3. Select **Gradio** as the SDK
8
+ 4. Choose **Public** or **Private** visibility
9
+ 5. Click **Create Space**
10
+
11
+ ## Step 2: Upload Files
12
+
13
+ Upload these files to your Space:
14
+
15
+ - `app.py` - Main application file
16
+ - `requirements.txt` - Python dependencies
17
+ - `README.md` - Space description and documentation
18
+ - `config.yaml` - Space configuration (optional)
19
+
20
+ ## Step 3: Configure Space Settings
21
+
22
+ In your Space settings:
23
+
24
+ 1. **Hardware**: Choose **CPU basic** (free) or **GPU** (paid) for faster inference
25
+ 2. **Variables**: No additional environment variables needed
26
+ 3. **Secrets**: No secrets required for this model
27
+
28
+ ## Step 4: Deploy
29
+
30
+ 1. The Space will automatically build and deploy
31
+ 2. Wait for the build to complete (usually 2-5 minutes)
32
+ 3. Your Space will be available at: `https://your-username-tarot-reading.hf.space`
33
+
34
+ ## Step 5: Test Your API
35
+
36
+ Once deployed, you can test the API using the provided test script:
37
+
38
+ ```bash
39
+ python test_api.py
40
+ ```
41
+
42
+ Or test manually with curl:
43
+
44
+ ```bash
45
+ curl -X POST "https://your-username-tarot-reading.hf.space/api/predict" \
46
+ -H "Content-Type: application/json" \
47
+ -d '{
48
+ "data": ["The Fool", "upright", "What should I focus on in my career?"]
49
+ }'
50
+ ```
51
+
52
+ ## API Endpoints
53
+
54
+ ### Main Interface
55
+ - **URL**: `https://your-username-tarot-reading.hf.space`
56
+ - **Method**: GET
57
+ - **Description**: Interactive web interface
58
+
59
+ ### API Endpoint
60
+ - **URL**: `https://your-username-tarot-reading.hf.space/api/predict`
61
+ - **Method**: POST
62
+ - **Content-Type**: application/json
63
+ - **Body**:
64
+ ```json
65
+ {
66
+ "data": ["Card Name", "orientation", "question"]
67
+ }
68
+ ```
69
+
70
+ ### Response Format
71
+ ```json
72
+ {
73
+ "data": "Your tarot reading response here..."
74
+ }
75
+ ```
76
+
77
+ ## Troubleshooting
78
+
79
+ ### Common Issues
80
+
81
+ 1. **Model Loading Errors**
82
+ - Check if the model name is correct
83
+ - Ensure you have sufficient memory allocated
84
+ - Try reducing model precision if needed
85
+
86
+ 2. **API Not Working**
87
+ - Verify the Space is fully deployed
88
+ - Check the Space logs for errors
89
+ - Ensure the API endpoint URL is correct
90
+
91
+ 3. **Slow Responses**
92
+ - Consider upgrading to GPU hardware
93
+ - Optimize model loading (load once, reuse)
94
+ - Reduce max_new_tokens parameter
95
+
96
+ ### Performance Optimization
97
+
98
+ 1. **Model Loading**: The model loads once when the Space starts
99
+ 2. **Caching**: Responses are not cached by default
100
+ 3. **Concurrency**: Gradio handles multiple requests automatically
101
+
102
+ ## Monitoring
103
+
104
+ - Check Space logs in the Hugging Face interface
105
+ - Monitor API usage and performance
106
+ - Set up alerts for errors if needed
107
+
108
+ ## Cost Considerations
109
+
110
+ - **Free Tier**: CPU basic hardware, limited usage
111
+ - **Paid Tiers**: GPU hardware, higher usage limits
112
+ - **API Calls**: No additional cost for API usage
113
+
114
+ ## Security
115
+
116
+ - The Space is public by default
117
+ - No authentication required
118
+ - Rate limiting handled by Hugging Face
119
+ - Input validation in the application
120
+
121
+ ## Next Steps
122
+
123
+ 1. **Customize**: Modify the UI, add more features
124
+ 2. **Scale**: Upgrade hardware if needed
125
+ 3. **Integrate**: Use the API in your applications
126
+ 4. **Share**: Share your Space with others
README.md CHANGED
@@ -1,12 +1,77 @@
1
  ---
2
- title: Tarot
3
- emoji: 🏢
4
- colorFrom: gray
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 5.44.1
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: AI Tarot Reading
3
+ emoji: 🔮
4
+ colorFrom: purple
5
+ colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 4.0.0
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
+ short_description: Get AI-powered tarot card readings using a fine-tuned TinyLlama model
12
  ---
13
 
14
+ # 🔮 AI Tarot Reading
15
+
16
+ This Space provides AI-powered tarot card readings using a fine-tuned TinyLlama model specifically trained for tarot predictions.
17
+
18
+ ## Features
19
+
20
+ - **AI-Powered Readings**: Get insightful tarot card interpretations using advanced language models
21
+ - **Customizable Inputs**: Choose any tarot card and orientation (upright/reversed)
22
+ - **Optional Questions**: Ask specific questions for personalized readings
23
+ - **API Access**: Use the model programmatically via API endpoints
24
+
25
+ ## How to Use
26
+
27
+ 1. **Select a Card**: Enter the name of any tarot card (e.g., "The Fool", "The Magician")
28
+ 2. **Choose Orientation**: Select "upright" or "reversed"
29
+ 3. **Ask a Question** (Optional): Add a specific question for more personalized readings
30
+ 4. **Get Your Reading**: Click "Get Reading" to receive your AI-generated tarot interpretation
31
+
32
+ ## API Usage
33
+
34
+ You can also use this model via API:
35
+
36
+ ```python
37
+ import requests
38
+
39
+ # Make a prediction
40
+ response = requests.post(
41
+ "https://your-space-url.hf.space/api/predict",
42
+ json={
43
+ "data": ["The Fool", "upright", "What should I focus on in my career?"]
44
+ }
45
+ )
46
+
47
+ result = response.json()
48
+ print(result["data"]) # Your tarot reading
49
+ ```
50
+
51
+ ## Model Information
52
+
53
+ - **Base Model**: TinyLlama-1.1B-Chat-v1.0
54
+ - **Fine-tuned for**: Tarot card predictions and interpretations
55
+ - **Training Data**: Custom tarot dataset
56
+ - **Capabilities**: Love, career, and general life guidance
57
+
58
+ ## Popular Tarot Cards
59
+
60
+ - **The Fool** - New beginnings, innocence, spontaneity
61
+ - **The Magician** - Manifestation, willpower, skill
62
+ - **The High Priestess** - Intuition, mystery, subconscious
63
+ - **The Empress** - Fertility, abundance, nature
64
+ - **The Emperor** - Authority, structure, control
65
+ - **The Lovers** - Love, relationships, choices
66
+ - **The Chariot** - Determination, willpower, victory
67
+ - **Strength** - Inner strength, courage, patience
68
+ - **The Hermit** - Soul-searching, introspection, guidance
69
+ - **Wheel of Fortune** - Change, cycles, destiny
70
+
71
+ ## Disclaimer
72
+
73
+ This is an AI-generated tarot reading tool for entertainment purposes. The readings should not be considered as professional advice or predictions of the future.
74
+
75
+ ## License
76
+
77
+ Apache 2.0
app.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ import json
5
+
6
+ # Load the model and tokenizer
7
+ model_name = "barissglc/tinyllama-tarot-v1"
8
+ print(f"Loading model: {model_name}")
9
+
10
+ try:
11
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
12
+ model = AutoModelForCausalLM.from_pretrained(
13
+ model_name,
14
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
15
+ device_map="auto" if torch.cuda.is_available() else None
16
+ )
17
+ print("Model loaded successfully!")
18
+ except Exception as e:
19
+ print(f"Error loading model: {e}")
20
+ tokenizer = None
21
+ model = None
22
+
23
+ def generate_tarot_response(card_name, orientation, question=""):
24
+ """
25
+ Generate a tarot reading based on card name, orientation, and optional question
26
+ """
27
+ if model is None or tokenizer is None:
28
+ return "Error: Model not loaded properly. Please try again later."
29
+
30
+ try:
31
+ # Format the input prompt
32
+ if question:
33
+ input_text = f"Card: {card_name}, orientation: {orientation}. Question: {question}. Explain in 3 short sentences."
34
+ else:
35
+ input_text = f"Card: {card_name}, orientation: {orientation}. Explain in 3 short sentences."
36
+
37
+ # Tokenize input
38
+ inputs = tokenizer(input_text, return_tensors="pt")
39
+
40
+ # Move to same device as model
41
+ if torch.cuda.is_available():
42
+ inputs = {k: v.cuda() for k, v in inputs.items()}
43
+
44
+ # Generate response
45
+ with torch.no_grad():
46
+ outputs = model.generate(
47
+ **inputs,
48
+ max_new_tokens=150,
49
+ temperature=0.7,
50
+ do_sample=True,
51
+ pad_token_id=tokenizer.eos_token_id,
52
+ eos_token_id=tokenizer.eos_token_id
53
+ )
54
+
55
+ # Decode response
56
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
57
+
58
+ # Remove the input text from the response
59
+ if input_text in response:
60
+ response = response.replace(input_text, "").strip()
61
+
62
+ return response
63
+
64
+ except Exception as e:
65
+ return f"Error generating response: {str(e)}"
66
+
67
+ def api_predict(card_name, orientation, question=""):
68
+ """
69
+ API endpoint for tarot predictions
70
+ """
71
+ result = generate_tarot_response(card_name, orientation, question)
72
+ return {
73
+ "card": card_name,
74
+ "orientation": orientation,
75
+ "question": question,
76
+ "reading": result
77
+ }
78
+
79
+ # Create Gradio interface
80
+ def create_interface():
81
+ with gr.Blocks(title="Tarot Reading with AI", theme=gr.themes.Soft()) as demo:
82
+ gr.Markdown("# 🔮 AI Tarot Reading")
83
+ gr.Markdown("Get insights from tarot cards using AI. Enter a card name, orientation, and optional question.")
84
+
85
+ with gr.Row():
86
+ with gr.Column():
87
+ card_name = gr.Textbox(
88
+ label="Card Name",
89
+ placeholder="e.g., The Fool, The Magician, The Lovers",
90
+ value="The Fool"
91
+ )
92
+
93
+ orientation = gr.Dropdown(
94
+ choices=["upright", "reversed"],
95
+ label="Orientation",
96
+ value="upright"
97
+ )
98
+
99
+ question = gr.Textbox(
100
+ label="Question (Optional)",
101
+ placeholder="e.g., What should I focus on in my career?",
102
+ lines=2
103
+ )
104
+
105
+ generate_btn = gr.Button("🔮 Get Reading", variant="primary")
106
+
107
+ with gr.Column():
108
+ output = gr.Textbox(
109
+ label="Tarot Reading",
110
+ lines=8,
111
+ interactive=False
112
+ )
113
+
114
+ # Example cards
115
+ gr.Markdown("### Popular Tarot Cards:")
116
+ gr.Markdown("""
117
+ - **The Fool** - New beginnings, innocence, spontaneity
118
+ - **The Magician** - Manifestation, willpower, skill
119
+ - **The High Priestess** - Intuition, mystery, subconscious
120
+ - **The Empress** - Fertility, abundance, nature
121
+ - **The Emperor** - Authority, structure, control
122
+ - **The Lovers** - Love, relationships, choices
123
+ - **The Chariot** - Determination, willpower, victory
124
+ - **Strength** - Inner strength, courage, patience
125
+ - **The Hermit** - Soul-searching, introspection, guidance
126
+ - **Wheel of Fortune** - Change, cycles, destiny
127
+ """)
128
+
129
+ # Event handlers
130
+ generate_btn.click(
131
+ fn=generate_tarot_response,
132
+ inputs=[card_name, orientation, question],
133
+ outputs=output
134
+ )
135
+
136
+ # API endpoint
137
+ demo.api_predict = api_predict
138
+
139
+ return demo
140
+
141
+ # Create and launch the interface
142
+ if __name__ == "__main__":
143
+ demo = create_interface()
144
+ demo.launch(
145
+ server_name="0.0.0.0",
146
+ server_port=7860,
147
+ share=True
148
+ )
config.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ title: AI Tarot Reading
2
+ emoji: 🔮
3
+ colorFrom: purple
4
+ colorTo: pink
5
+ sdk: gradio
6
+ sdk_version: 4.0.0
7
+ app_file: app.py
8
+ pinned: false
9
+ license: apache-2.0
10
+ short_description: Get AI-powered tarot card readings using a fine-tuned TinyLlama model
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ transformers>=4.37.0
3
+ torch>=2.0.0
4
+ accelerate>=0.20.0
5
+ safetensors>=0.3.0
test_api.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Test script for the Tarot Space API
4
+ """
5
+
6
+ import requests
7
+ import json
8
+
9
+ def test_tarot_api(space_url, card_name="The Fool", orientation="upright", question=""):
10
+ """
11
+ Test the tarot API endpoint
12
+ """
13
+ api_url = f"{space_url}/api/predict"
14
+
15
+ payload = {
16
+ "data": [card_name, orientation, question]
17
+ }
18
+
19
+ try:
20
+ response = requests.post(api_url, json=payload)
21
+ response.raise_for_status()
22
+
23
+ result = response.json()
24
+ return result
25
+
26
+ except requests.exceptions.RequestException as e:
27
+ return {"error": f"API request failed: {str(e)}"}
28
+
29
+ def main():
30
+ # Replace with your actual Space URL
31
+ space_url = "https://your-username-tarot-space.hf.space"
32
+
33
+ print("🔮 Testing Tarot API...")
34
+ print(f"Space URL: {space_url}")
35
+ print("-" * 50)
36
+
37
+ # Test cases
38
+ test_cases = [
39
+ {
40
+ "card_name": "The Fool",
41
+ "orientation": "upright",
42
+ "question": "What should I focus on in my career?"
43
+ },
44
+ {
45
+ "card_name": "The Magician",
46
+ "orientation": "upright",
47
+ "question": ""
48
+ },
49
+ {
50
+ "card_name": "The Lovers",
51
+ "orientation": "reversed",
52
+ "question": "What does this mean for my relationship?"
53
+ }
54
+ ]
55
+
56
+ for i, test_case in enumerate(test_cases, 1):
57
+ print(f"\nTest {i}:")
58
+ print(f"Card: {test_case['card_name']}")
59
+ print(f"Orientation: {test_case['orientation']}")
60
+ print(f"Question: {test_case['question'] or 'None'}")
61
+
62
+ result = test_tarot_api(
63
+ space_url,
64
+ test_case['card_name'],
65
+ test_case['orientation'],
66
+ test_case['question']
67
+ )
68
+
69
+ if 'error' in result:
70
+ print(f"❌ Error: {result['error']}")
71
+ else:
72
+ print(f"✅ Response: {result.get('data', 'No data returned')}")
73
+
74
+ print("-" * 30)
75
+
76
+ if __name__ == "__main__":
77
+ main()
test_curl.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Test script for Tarot Space API using curl
4
+ # Replace YOUR_SPACE_URL with your actual Space URL
5
+
6
+ SPACE_URL="https://your-username-tarot-reading.hf.space"
7
+ API_URL="${SPACE_URL}/api/predict"
8
+
9
+ echo "🔮 Testing Tarot Space API with curl"
10
+ echo "Space URL: $SPACE_URL"
11
+ echo "API URL: $API_URL"
12
+ echo "=================================="
13
+
14
+ # Test 1: Basic tarot reading
15
+ echo "Test 1: Basic tarot reading (The Fool, upright)"
16
+ curl -X POST "$API_URL" \
17
+ -H "Content-Type: application/json" \
18
+ -d '{
19
+ "data": ["The Fool", "upright", ""]
20
+ }' | jq '.'
21
+
22
+ echo -e "\n=================================="
23
+
24
+ # Test 2: Tarot reading with question
25
+ echo "Test 2: Tarot reading with question (The Magician, upright)"
26
+ curl -X POST "$API_URL" \
27
+ -H "Content-Type: application/json" \
28
+ -d '{
29
+ "data": ["The Magician", "upright", "What should I focus on in my career?"]
30
+ }' | jq '.'
31
+
32
+ echo -e "\n=================================="
33
+
34
+ # Test 3: Reversed card reading
35
+ echo "Test 3: Reversed card reading (The Lovers, reversed)"
36
+ curl -X POST "$API_URL" \
37
+ -H "Content-Type: application/json" \
38
+ -d '{
39
+ "data": ["The Lovers", "reversed", "What does this mean for my relationship?"]
40
+ }' | jq '.'
41
+
42
+ echo -e "\n=================================="
43
+ echo "✅ All tests completed!"